Before you flag the question please read it first-
I found How to count the number of objects detected with Template Matching?, tutorial and it's good but not perfect.
The problem with this and what I am facing is that, It's not giving accurate counts, but draws the rectangle around all the found(objects) ones!
For example, I have this (Before, executing script):-
Then, I have this (After executing script):-
As you can see clearly, there are 3 rectangles
in 4th row
but the count it's giving is 1
.
I've tried changing threshold and sensitivity
, but it didn't work. Here's what I have so far-
# USAGE
===================================================================
# python3 match_template.py --template cod_logo.png --images images
===================================================================
import numpy as np
import argparse
import imutils
import glob
import cv2
from matplotlib import pyplot as plt
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-t", "--template", required=True, help="Path to template image")
ap.add_argument("-i", "--images", required=True,
help="Path to images where template will be matched")
ap.add_argument("-v", "--visualize",
help="Flag indicating whether or not to visualize each iteration")
args = vars(ap.parse_args())
def match_and_count(template, image):
img_rgb = cv2.imread(image)
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread(template,0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where( res >= threshold)
f = set()
for pt in zip(*loc[::-1]):
cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)
sensitivity = 100
f.add((round(pt[0]/sensitivity), round(pt[1]/sensitivity)))
cv2.imwrite('multiple_objects.jpg',img_rgb)
print("Occurence of Object: %s" % len(f))
match_and_count(args["template"], args["images"])
Does anyone have any better approach of doing the same?