我正在尝试将OpenCV图像Mat对象调整为较小的尺寸,如下所示:
small = cv2.resize(big, (small_height, small_width))
这很好,但是,每次调用此行代码时,它最终都会创建一个新的小型OpenCV Mat对象。
因此,我试图找到一种避免每次创建新的Mat小对象的方法。有谁知道甚至可以重用预先分配的Mat对象来调整输出大小?
代替使用small = cv2.resize(...)
,您可以通过引用传递输出对象:cv2.resize(big, (w, h), small)
。
我不能说我真的很了解幕后发生的事情,但是我几乎可以肯定,可以使用以下方法来重新使用预先分配的Python对象进行大小调整:
# Pre-allocate object (assume output format is uint8 BGR):
small = np.zeros((small_height, small_width, 3), np.uint8)
# Pass output ndarray by reference:
cv2.resize(big, (small_width, small_height), small)
注意:OpenCV约定为(width, height)
,而不是示例代码中的(height, width)
。
实际上,检查cv2.resize
是创建一个新对象还是重用现有对象很简单。
这里是一个简单的测试,显示OpenCV重用了现有对象:
import cv2
import numpy as np
big = cv2.imread('chelsea.png', cv2.IMREAD_COLOR)
small_width, small_height = 160, 90
# Allocate as twice as much rows (allocate small_height*2 rows istead of small_height rows)
small = np.zeros((small_height*2, small_width, 3), np.uint8)
small[:, :, 1] = 255 # Fill small image with green color
small_slice = small[small_height//2:small_height*3//2, :, :] #Get a slice in the expected size of resized output
# Pass small_slice by reference
cv2.resize(big, (small_width, small_height), small_slice)
cv2.imshow('small', small)
cv2.waitKey(0)
cv2.destroyAllWindows()
如您所见,绿色保留了原始对象的颜色,并且切片由resize
的输出填充。