Find all locations of image in larger image in Python

给你一囗甜甜゛ 提交于 2021-02-05 11:52:29

问题


I have a scan of a panel which I cannot show due to restrictions, but I tried to 'simulate' it:

This picture simulates the scan that I have: a white background with round black stickers, which each have a white smaller circle in the middle. Some stickers differ a bit on the scan, but the type of shape/sticker is always the same.

Now I need to write a code which is able to look in this image and show + return all locations of the stickers. I was able to find this for one location using OpenCV Template Matching, but that is only able to find one exact match with a smaller image which I provide as input. I need to find all locations at the same time.

I could not find a topic here or anywhere that covers my question.

I hope someone can help.

Regards, Ganesh


回答1:


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

I used the following image as a template.jpg

I wrote the script as follows

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)

This gave the result as

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.



来源:https://stackoverflow.com/questions/61156473/find-all-locations-of-image-in-larger-image-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!