<p>您的代码显示基本模板匹配。请阅读有关该主题的一些<a href="https://docs.opencv.org/master/d4/dc6/tutorial_py_template_matching.html" rel="nofollow noreferrer">tutorial</a>和有关<a href="https://docs.opencv.org/master/df/dfb/group__imgproc__object.html#ga586ebfb0a7fb604b35a23d85391329be" rel="nofollow noreferrer">^{<cd1>}</a>的文档,特别是了解不同的<a href="https://docs.opencv.org/master/df/dfb/group__imgproc__object.html#ga3a7850640f1fe1f58fe91a2d7583695d" rel="nofollow noreferrer">template match modes</a></p>
<p>我只能想到以下解决方案来处理您的任务:使用<code>TM_SQDIFF_NORMED</code>,而不是使用<code>TM_SQDIFF</code>,这样您可以在<code>result</code>中获得绝对值,而不是相对值:</p>
<ul>
<li>对于<code>TM_SQDIFF_NORMED</code>,最好的匹配总是在<code>0.0</code>附近的某个值,即使匹配不正确</李>
<li>对于<code>TM_SQDIFF</code>,靠近<code>0.0</code>的某个值表示实际正确
匹配</李>
</ul>
<p>现在,只需编写一个方法,进行模板匹配,并检测<code>result</code>的最小值是否低于<code>0.0</code>附近的某个阈值,比如<code>10e-6</code>。如果是,请打印出您想要的内容,如果不是,请执行其他操作:</p>
<pre class="lang-py prettyprint-override"><code>import cv2
def is_template_in_image(img, templ):
# Template matching using TM_SQDIFF: Perfect match => minimum value around 0.0
result = cv2.matchTemplate(img, templ, cv2.TM_SQDIFF)
# Get value of best match, i.e. the minimum value
min_val = cv2.minMaxLoc(result)[0]
# Set up threshold for a "sufficient" match
thr = 10e-6
return min_val <= thr
# Read template
template = cv2.imread('ran_away.png')
# Collect image file names
images = ['pokemon_card.png', 'some_other_image.png']
for image in images:
if is_template_in_image(cv2.imread(image), template):
print('{}: {}'.format(image, 'Pokemon has ran away.'))
else:
print('{}: {}'.format(image, 'Nothing to see here.'))
</code></pre>
<p>输出:</p>
<pre class="lang-none prettyprint-override"><code>pokemon_card.png: Pokemon has ran away.
some_other_image.png: Nothing to see here.
</code></pre>
<pre class="lang-none prettyprint-override"><code>
System information
Platform: Windows-10-10.0.19041-SP0
Python: 3.9.1
PyCharm: 2021.1.1
OpenCV: 4.5.2
</code></pre>