我试图检测一个图像是否与另一个图像中的图像100%匹配,然后将变量设置为True
。但是我读到的所有东西都没有结果,除了给出代码的一个特定线程
import cv2
method = cv2.TM_SQDIFF_NORMED
# Read the images from the file
small_image = cv2.imread('ran_away.png')
large_image = cv2.imread('pokemon_card.png')
result = cv2.matchTemplate(small_image, large_image, method)
# We want the minimum squared difference
mn,_,mnLoc,_ = cv2.minMaxLoc(result)
# Draw the rectangle:
# Extract the coordinates of our best match
MPx,MPy = mnLoc
# Step 2: Get the size of the template. This is the same size as the match.
trows,tcols = small_image.shape[:2]
# Step 3: Draw the rectangle on large_image
cv2.rectangle(large_image, (MPx,MPy),(MPx+tcols,MPy+trows),(0,0,255),2)
# Display the original image with the rectangle around the match.
cv2.imshow('output',large_image)
# The image is only displayed if we call this
cv2.waitKey(0)
然而,这打开了一个输出,并且做了我不想做的事情。我想做的就是检测图像是否在图像中,如果在图像中,则将其打印到控制台。在我的特殊情况下,我试图检测这个图像
在这张图中是什么
如果是,在控制台上打印口袋妖怪已经跑掉了
我使用相对较新的NumPy方法sliding_window_view找到了一个解决方案
注意:由于兼容性问题,我已在新的虚拟环境中安装了最新的NumPy版本
检查滑动窗口视图如何工作的简单测试:
结果开始于:
这意味着
t
按预期从v
的所有“窗口”中减去为测试np.all添加以下命令:
输出为:
如果沿轴3、4和5的所有元素都是
True
,则all(axis=(3, 4, 5))
为True
。在上面的示例中,我们在索引[1,1]中找到了一个匹配项
以下是检测完美匹配的解决方案(使用NumPy):
结果:
您的代码显示基本模板匹配。请阅读有关该主题的一些tutorial和有关^{} 的文档,特别是了解不同的template match modes
我只能想到以下解决方案来处理您的任务:使用
TM_SQDIFF_NORMED
,而不是使用TM_SQDIFF
,这样您可以在result
中获得绝对值,而不是相对值:TM_SQDIFF_NORMED
,最好的匹配总是在0.0
附近的某个值,即使匹配不正确李>TM_SQDIFF
,靠近0.0
的某个值表示实际正确 匹配李>现在,只需编写一个方法,进行模板匹配,并检测
result
的最小值是否低于0.0
附近的某个阈值,比如10e-6
。如果是,请打印出您想要的内容,如果不是,请执行其他操作:输出:
相关问题 更多 >
编程相关推荐