如何找到一个图像出现在另一个图像中的概率百分比?

2024-06-16 12:16:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图获得OpenCV中一个图像出现在另一个图像中的概率百分比

以下是我正在比较的图像:

Small image

Large image]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中是可能的吗


Tags: the图像imageimportasmatchcv2opencv
1条回答
网友
1楼 · 发布于 2024-06-16 12:16:14

一般来说,您的方法和代码是正确的。缺少什么:请注意,您的模板(小图像)有一些透明度,因此是alpha通道。要保留该选项,请在相应的cv2.imread调用中使用^{}标志。现在,模板的背景充满了黑白像素,这会导致在将像素与实际图像(大图像)匹配时出现错误结果

幸运的是,^{}有一个mask参数。因此,要匹配的像素被限制为由该掩模描述的像素。很好,这正是我们从你的模板的alpha通道得到的

下面是一些(大量)修改和缩短的代码:

import cv2

# Read images; preserve alpha channel in template
image = cv2.imread('image.png')
templ = cv2.imread('template.png', cv2.IMREAD_UNCHANGED)

# Actual template matching; use alpha channel of template as mask
result = cv2.matchTemplate(image, templ[..., :3], cv2.TM_SQDIFF_NORMED,
                           mask=templ[..., 3])

# Get location of best match, and draw rectangle
mpx, mpy = cv2.minMaxLoc(result)[2]
h, w = templ.shape[:2]
cv2.rectangle(image, (mpx, mpy), (mpx + w, mpy + h), (0, 0, 255), 2)

# Output
cv2.imshow('image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

这就是结果,我想这应该是预期的结果:

Output

顺便说一下:小心cv2.matchTemplate的参数。第一个参数是实际图像(大图像),第二个参数是模板(小图像)。那是你的密码!不使用遮罩时,顺序无效,但提供遮罩时,形状必须与模板相同,并根据第二个参数的形状自动进行检查

                    
System information
                    
Platform:      Windows-10-10.0.19042-SP0
Python:        3.9.6
PyCharm:       2021.2
OpenCV:        4.5.3
                    

相关问题 更多 >