SQDIFF 定义为 openCV definition 。 (我相信他们省略了 channel )
在初级 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
函数类似的结果?
最佳答案
作为最后的手段,您可以在图 block 中执行计算,而不是“一次全部”计算。
np.lib.stride_tricks.sliding_window_view
返回数据的 View ,因此不会消耗大量 RAM。
表达式B - locations
无法使用 View ,并且需要 RAM 来存储具有浮点元素形状 (781, 984, 1, 248, 249, 3) 的数组。
用于存储B - locations
的总RAM是 781*984*1*248*249*3*4
= 569,479,908,096 字节。
为了避免存储B - locations
的需要立即在 RAM 中,我们可以计算 sqdiff
在图 block 中,当“图 block ”计算需要更少的 RAM 时。
一个简单的图 block 划分是将每一行用作图 block - 在 sqdiff
的行上循环。 ,并逐行计算输出。
示例:
sqdiff = np.zeros((locations.shape[0], locations.shape[1]), np.float32) # Allocate an array for storing the result.
# Compute sqdiff row by row instead of computing all at once.
for i in range(sqdiff.shape[0]):
sqdiff[i, :] = np.sum((B - locations[i, :, :, :, :, :]) ** 2, axis=(-1, -2, -3, -4))
可执行代码示例:
import numpy as np
import cv2
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)
cv_result = cv2.matchTemplate(A, B, cv2.TM_SQDIFF) # this result is the same as the simple for loops
#sqdiff = np.sum((B - locations) ** 2, axis=(-1, -2, -3, -4)) # This will fail with normal sized images
sqdiff = np.zeros((locations.shape[0], locations.shape[1]), np.float32) # Allocate an array for storing the result.
# Compute sqdiff row by row instead of computing all at once.
for i in range(sqdiff.shape[0]):
sqdiff[i, :] = np.sum((B - locations[i, :, :, :, :, :]) ** 2, axis=(-1, -2, -3, -4))
assert np.allclose(cv_result, sqdiff)
我知道这个解决方案有点令人失望...但这是我能找到的唯一通用解决方案。
关于python - NumPy 模板将 SQDIFF 与 `sliding window_view` 匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68122570/