【发布时间】:2021-09-08 08:25:15
【问题描述】:
SQDIFF 定义为openCV definition。 (我相信他们省略了频道)
在初级numpy Python中应该是什么
A = np.arange(27, dtype=np.float32)
A = A.reshape(3,3,3) # The "image"
B = np.ones([2, 2, 3], dtype=np.float32) # window
rw, rh = A.shape[0] - B.shape[0] + 1, A.shape[1] - B.shape[1] + 1 # End result size
result = np.zeros([rw, rh])
for i in range(rw):
for j in range(rh):
w = A[i:i + B.shape[0], j:j + B.shape[1]]
res = B - w
result[i, j] = np.sum(
res ** 2
)
cv_result = cv.matchTemplate(A, B, cv.TM_SQDIFF) # this result is the same as the simple for loops
assert np.allclose(cv_result, result)
这是相对较慢的解决方案。我已经阅读了有关 sliding_window_view 的信息,但无法正确理解。
# This will fail with these large arrays but is ok for smaller ones
A = np.random.rand(1028, 1232, 3).astype(np.float32)
B = np.random.rand(248, 249, 3).astype(np.float32)
locations = np.lib.stride_tricks.sliding_window_view(A, B.shape)
sqdiff = np.sum((B - locations) ** 2, axis=(-1,-2, -3, -4)) # This will fail with normal sized images
即使结果很容易符合记忆,也会以MemoryError 失败。如何以这种更快的方式产生与cv2.matchTemplate 函数相似的结果?
【问题讨论】:
-
你能发布你的“正常大小的图像”和正常大小的窗口吗?您发布的示例无法重现
MemoryError... -
我已经用
np.random.rand生成了一个源代码和一个模板。 -
现在可以重现了。我收到一个错误:
numpy.core._exceptions.MemoryError: Unable to allocate 530. GiB for an array with shape (781, 984, 1, 248, 249, 3) and data type float32。 NumPy 尝试分配内存以一次存储(B - locations)的所有结果。
标签: python numpy opencv stride