Ask Your Question

Revision history [back]

How to do multiple template matching with multiple objects by opencv Python.

Hi, I'm just beginner to the python and opencv. Based on this Template Matching, the following code is detect multiple object:

import numpy as np
import cv2

img = cv2.imread("C:\\xampp\\htdocs\\IRR\\images\\Try.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
template = cv2.imread("C:\\xampp\\htdocs\\IRR\\Scanner\\RM1FS.jpg",0)

 res = cv2.matchTemplate(gray, template, cv2.TM_SQDIFF_NORMED)
 min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
min_thresh = (min_val + 1e-6) * 1.5
 match_locations = np.where(res<=min_thresh)

w, h = template.shape[::-1]
for (x, y) in zip(match_locations[1], match_locations[0]):
    cv2.rectangle(img, (x, y), (x+w, y+h), [0,255,255], 2)

cv2.namedWindow('image', cv2.WINDOW_NORMAL)
cv2.imshow('', img)
cv2.waitKey(0)

So Try.jpg is

image description

and RM1FS.jpg is

image description

But i get the result after run the code is :

image description

Can anyone share me ideas how to get the yellow square that only square up the RM 1 corner place with thin yellow line?