首页 > 解决方案 > matchTemplate 与调整大小的图像不起作用:(-215:断言失败)_img.size().height <= _templ.size().height

问题描述

我在 matchTemplate 调用之前调整了我的图像大小,以确保两个图像具有相同的大小。

# -*- coding: utf-8 -*-
import cv2 as cv
import numpy as np
import time

img_rgb = cv.imread('t2.png')
img_gray = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY)
template = cv.imread('template1.png', 0)

# Make sure that we use the exact same size in the comparison
if img_gray.shape != template.shape:
    img_gray = cv.resize(img_gray, template.shape, interpolation=cv.INTER_AREA)


res = cv.matchTemplate(img_gray, template, cv.TM_CCOEFF_NORMED)
print res

但我得到了这个错误:

res = cv.matchTemplate(img_gray, template, cv.TM_CCOEFF_NORMED)
cv2.error: OpenCV(4.0.0) C:\projects\opencv-python\opencv\modules\imgproc\src\templmatch.cpp:1112: error: (-215:Assertion failed) _img.size().height <= _templ.size().height && _img.size().width <= _templ.size().width in function 'cv::matchTemplate'

标签: pythonopencvmatchtemplate

解决方案


当 ypu 调整图像大小时,您正在使用 template.shape 但您需要使用

template.shape[::-1]

推荐阅读