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

asked 2018-03-26 11:21:38 -0500

VivianTio gravatar image

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)

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?

edit retag flag offensive close merge delete


template matching is not invariant to scaling / rotation / perspective distortion.

so it rarelyworks with images from a real world camera, like yours.

berak gravatar imageberak ( 2018-03-26 12:02:10 -0500 )edit

Hi, any suggestion for doing this beside template matching?

VivianTio gravatar imageVivianTio ( 2018-03-26 21:05:49 -0500 )edit