我试图获得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中是可能的吗
一般来说,您的方法和代码是正确的。缺少什么:请注意,您的模板(小图像)有一些透明度,因此是alpha通道。要保留该选项,请在相应的} 标志。现在,模板的背景充满了黑白像素,这会导致在将像素与实际图像(大图像)匹配时出现错误结果
cv2.imread
调用中使用^{幸运的是,^{} 有一个
mask
参数。因此,要匹配的像素被限制为由该掩模描述的像素。很好,这正是我们从你的模板的alpha通道得到的下面是一些(大量)修改和缩短的代码:
这就是结果,我想这应该是预期的结果:
顺便说一下:小心
cv2.matchTemplate
的参数。第一个参数是实际图像(大图像),第二个参数是模板(小图像)。那是你的密码!不使用遮罩时,顺序无效,但提供遮罩时,形状必须与模板相同,并根据第二个参数的形状自动进行检查相关问题 更多 >
编程相关推荐