且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Python中以较大的图像查找图像的所有位置

更新时间:2023-11-26 11:33:22

我设法使用相对简单的python脚本来实现此功能,以进行多对象模板匹配.

I managed to get this working with a relatively simple python script for multiple object template matching.

我使用以下图像作为模板.jpg

I used the following image as a template.jpg

我写的脚本如下

import cv2
import numpy as np

#load image into variable
img_rgb = cv2.imread('scan.jpg')

#load template
template = cv2.imread('template.jpg')

#read height and width of template image
w, h = template.shape[0], template.shape[1]

res = cv2.matchTemplate(img_rgb,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where( res >= threshold)
for pt in zip(*loc[::-1]):
    cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,255,0), 2)

img_rgb = cv2.resize(img_rgb,(800,600))
cv2.imshow("result",img_rgb)
cv2.waitKey(10000)

结果为

但是,如果这些黑色贴纸的大小或多或少不一致,则可能要使用多尺度模板匹配.

However, if the size of these black stickers is not more or less consistent, you might want to use a multi-scaled approach to template matching.