import cv2
method = cv2.TM_SQDIFF_NORMED
# Read the images from the file
small_image = cv2.imread('small_image.png')
large_image = cv2.imread('large_image.jpeg')
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)
因为Moshe's answer只覆盖匹配给定图片中只包含一次的模板。以下是如何同时匹配多个:
(注意:我修改并修正了原始代码中的一些错误)
结果:
来源:https://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_imgproc/py_template_matching/py_template_matching.html
对于任何在未来遇到这种情况的人。
这可以通过template matching完成。总而言之(我的理解),模板匹配寻找一个图像在另一个图像中的精确匹配。
下面是一个如何在Python中实现的示例:
OpenCV有一个可以查看的Python接口。如果是字符,不要更改太多,可以尝试使用matchTemplate函数。
Here是他们的官方教程(教程是用C++接口编写的,但是你应该能从Python中找到函数的用法。
相关问题 更多 >
编程相关推荐