Implement Image Matching with Threshold in Python OpenCV – OpenCV Tutorial

By | October 21, 2020

When we are using opencv to match multiple objects from an image, we usually do not know how many objects in image. In order to detect correct object numbers, we can use a threshold when detecting. In this tutorial, we will introduce you how to do.

For example, in this tutorial, we have known how to detect multiple objects from an image:

Python OpenCV Match Multiple Objects From an Image: A Beginner Guide – OpenCV Tutorial

Look at this example code:

method = cv2.TM_SQDIFF_NORMED
objects = 5
for i in range(objects):
    res = cv2.matchTemplate(img2, template, method)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    
    top_left = min_loc
    print(top_left) #(268, 839)  w, h
    print(min_val)
    
    bottom_right = (top_left[0] + w, top_left[1] + h)
 
    cv2.rectangle(img, top_left, bottom_right, 255, 2)
    

We suppose there are 5 template objects in image img2. However, img2 may do not contain any objects.

In order to fix this problem, we can use a threshold when matching.

In this example code, we use cv2.TM_SQDIFF_NORMED to match image, the value of res is smaller, the result is better.

Understand OpenCV Template Matching Algorithm: A Completed Guide – OpenCV Tutorial

We can modify this example code to:

method = cv2.TM_SQDIFF_NORMED
objects = 5
for i in range(objects):
    res = cv2.matchTemplate(img2, template, method)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    
    top_left = min_loc
    print(top_left) #(268, 839)  w, h
    print(min_val)
    if min_val > 0.01:
        break
    
    bottom_right = (top_left[0] + w, top_left[1] + h)
 
    cv2.rectangle(img, top_left, bottom_right, 255, 2)

It means we will ignore the threshold > 0.01.

Then we can get a correct object number.

Leave a Reply