基于ZNCC的自定义模板匹配函数内存溢出问题及优化求助
零均值归一化互相关(ZNCC)模板匹配函数的内存优化问题
我编写了一个基于**零均值归一化互相关(ZNCC)**的自定义模板匹配函数,参考ZNCC公式实现:
def ZNCC_mat(array1, array2): array1 = array1 / 255 array2 = array2 / 255 zmean_array1 = array1 - np.mean(array1) zmean_array1_norm = zmean_array1 / np.linalg.norm(zmean_array1) array2_view = np.lib.stride_tricks.sliding_window_view( array2, window_shape=array1.shape ) zmean_array2 = array2_view - np.mean(array2_view, axis=(2, 3), keepdims=True) zmean_array2_view_norm = zmean_array2 / np.linalg.norm( zmean_array2, axis=(2, 3), keepdims=True ) result = np.einsum("ij,klij->kl", zmean_array1_norm, zmean_array2_view_norm) return result
函数步骤说明
- 将灰度图像归一化至0-1区间
- 对模板图像进行去均值并除以标准差处理
- 使用
np.lib.stride_tricks.sliding_window_view将源图像划分为子图像/矩阵 - 对每个子区域进行去均值并除以标准差处理
- 通过
np.einsum计算归一化模板与每个归一化子区域的互相关值
但在计算得到array2_view后,对子矩阵操作时内存占用过大,出现如下错误:
Traceback (most recent call last): File "test/similarity_metrics_comparisons.py", line 17, in <module> result = ZNCC_mat(template_gray, source_gray) File "test/einsum_tests.py", line 145, in ZNCC_mat zmean_array2 = array2_view - np.mean(array2_view, axis=(2, 3), keepdims=True) numpy.core._exceptions._ArrayMemoryError: Unable to allocate 35.4 GiB for an array with shape (478, 1150, 97, 89) and data type float64
请问有哪些可以优化该操作的方法?
测试示例代码(含匹配结果可视化)
需自行读取源图像和模板图像(可使用示例源图像、示例模板图像进行测试):
# 请先读取源图像和模板图像 source = cv2.imread() template = cv2.imread() source_gray = cv2.cvtColor(source, cv2.COLOR_BGR2GRAY) template_gray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY) result = ZNCC_mat(template_gray, source_gray) print(result.max()) h, w = template_gray.shape y, x = np.unravel_index(result.argmax(), result.shape) top_left = (x, y) bottom_right = (x + w, y + h) cv2.rectangle(source, top_left, bottom_right, (0, 255, 0), 2) plt.subplot(131),plt.imshow(source) plt.subplot(132),plt.imshow(result) plt.subplot(133),plt.imshow(template) plt.show()
内容的提问来源于stack exchange,提问作者ms92
相关产品推荐
相关产品推荐

