首页 > 解决方案 > 将 SQDIFF 与“滑动窗口视图”匹配的 NumPy 模板

问题描述

SQDIFF 被定义为openCV 定义。(我相信他们省略了频道)

SQDIFF

初级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我怎样才能用这种更快的方式产生与函数相似的结果?

标签: pythonnumpyopencvstride

解决方案


作为最后的手段,您可以在瓦片中执行计算,而不是“一次”计算。

np.lib.stride_tricks.sliding_window_view返回数据视图,因此不会消耗大量 RAM。

该表达式B - locations不能使用视图,并且需要 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,当“tile”计算需要更少的 RAM 时,我们可能会以块计算。

一个简单的瓦片划分是使用每一行作为一个瓦片 - 在 的行上循环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)

我知道解决方案有点令人失望……但这是我能找到的唯一通用解决方案。


推荐阅读