1

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):-

enter image description here

Then, I have this (After executing script):-

enter image description here

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?

the.salman.a
  • 945
  • 8
  • 29
  • 1
    Because `f = set()`, which means that `f` is a `set` and it would only contain the unique value(s), any redundant value would not be stored. You can convert it to a list `f = list()` and use `.append()` instead of `add()`. But it also seems that in your use case, you may not need overlapping components. I think you need to fix the value of `sensitivity` to a lower value, since higher value of this variable is leading to fall all rects under same bucket. – ZdaR Mar 29 '18 at 07:20
  • @ZdaR I tried changing `sensitivity` to a lower value(s). No change, I mean it worked in some cases bu wrong values in some cases again. Also tried list instead of set `f.append((round(pt[0]/sensitivity), round(pt[1]/sensitivity)))`, not working.! – the.salman.a Mar 29 '18 at 07:28

0 Answers0