首页 > 解决方案 > 重用预先分配的 opencv Mat/Python 对象来调整大小

问题描述

我正在尝试将 OpenCV 图像 Mat 对象调整为更小的尺寸,如下所示:

small = cv2.resize(big, (small_height, small_width))

这工作得很好,但是,每次调用这行代码时,它最终都会创建一个新的小型 OpenCV Mat 对象。

因此,我试图找到一种方法来避免每次都创建一个新的小 Mat 对象。有没有人知道是否可以重用预先分配的 Mat 对象来调整输出大小?

标签: pythonopencvpython-3.6image-resizing

解决方案


您可以通过引用传递输出对象,而不是使用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.


推荐阅读