python - 重用预先分配的 opencv Mat/Python 对象来调整大小
问题描述
我正在尝试将 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
.
推荐阅读
- node.js - 如何在 AWS Lambda 的 Node js 中安装“ical”包?
- javascript - 如何根据容器高度和宽度拉伸内容图标跨度元素的 50% 宽度和 100% 高度
- javascript - 在jquery中检查同一列中的相同顺序时验证复选框
- javascript - 如何从 Markdown 代码块字符串中提取代码?
- laravel-5 - 多个应用程序的相同用户和配置文件表
- c - 可以在 posix_spawn 的 argv 中传递字符串文字吗?
- android - 如何在清单中添加应用程序名称
- android - 用于创建应用程序包的 Android Studio 3.2 Canary 15 中的 Gradle 同步失败
- qt - eventFilter 可以对 Qt 上的信号做出反应吗
- c# - 当一个条件为真时如何从循环中中断?