【发布时间】:2021-08-20 04:25:47
【问题描述】:
我正在尝试获取图像在 OpenCV 中的另一个图像中的百分比。
这是我正在比较的图像:
]2
这是我的代码:
import cv2
import numpy as np
large_image = cv2.imread(r'Directory here')
#Cropping the image so that it's easier to compare
height = large_image.shape[0]
width = large_image.shape[1]
large_image = large_image[5:height-173,260:width-25]
small_image = cv2.imread(r'Directory here')
method = cv2.TM_SQDIFF_NORMED
# Read the images from the file
result = cv2.matchTemplate(small_image, large_image, method)
#BELOW IS ONLY IF YOU WANT TO SEE A RECTANGLE AROUND THE IMAGE
# We want the minimum squared difference
mn,_,mnLoc,_ = cv2.minMaxLoc(result)
# Draw the rectangle:
# Extract the coordinates of our best match
MPx,MPy = mnLoc
# Get the size of the template. This is the same size as the match.
trows,tcols = small_image.shape[:2]
# 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)
cv2.waitKey(0)
OpenCV 甚至可以做到这一点吗?
【问题讨论】:
-
使用 TM_CCOEFF_NORMED 并遵循 HansHirse 下面关于屏蔽的说明。这种方法理论上应该生成一个浮动图像,其范围应该在 -1 和 1 之间,其中 1 是完美匹配,尽管通常在 0 和 1 之间。找到图像中的最大值并乘以 100 以获得匹配百分比。
-
你能包含代码吗,我不知道把“cv2.TM_CCOEFF_NORMED”放在哪里。对不起,如果这听起来很愚蠢,但我不擅长 OpenCV。
-
将
method = cv2.TM_SQDIFF_NORMED替换为method = cv2.TM_CCOEFF_NORMED参见docs.opencv.org/4.1.1/df/dfb/… -
我尝试使用 HansHirse 的代码将“cv2.TM_CCOEFF_NORMED”替换为“cv2.TM_SQDIFF_NORMED”,但它与“cv2.TM_SQDIFF_NORMED”的工作方式不同。
-
我希望你使用
method = cv2.TM_CCOEFF_NORMED完美匹配为 1。另一个完美匹配为 0。所以它们的工作方式不同。如果你想得到一个百分比。使用我所说的乘以 100。
标签: python python-3.x opencv template-matching