python - How to count the number of objects detected with Template Matching?

Python - How to count the number of objects detected with Template Matching?

To count the number of objects detected with template matching in Python using OpenCV, you can follow these steps:

  1. Read the main image and the template image.
  2. Perform template matching.
  3. Identify locations where the template matches the main image.
  4. Filter out overlapping detections if necessary.
  5. Count the unique detection points.

Here's a detailed example of how to achieve this:

Step-by-Step Code Example

Step 1: Import Libraries

First, import the required libraries.

import cv2 import numpy as np 

Step 2: Read Images

Load the main image and the template image using OpenCV.

# Load the main image and convert to grayscale main_image = cv2.imread('main_image.jpg') main_gray = cv2.cvtColor(main_image, cv2.COLOR_BGR2GRAY) # Load the template image and convert to grayscale template = cv2.imread('template.jpg', 0) template_height, template_width = template.shape 

Step 3: Perform Template Matching

Use OpenCV's matchTemplate function to perform template matching.

# Perform template matching result = cv2.matchTemplate(main_gray, template, cv2.TM_CCOEFF_NORMED) # Set a threshold to identify matches threshold = 0.8 locations = np.where(result >= threshold) 

Step 4: Identify and Filter Detections

Filter overlapping detections using a non-maximum suppression technique to count unique detections.

# Extract the coordinates of matching locations locations = list(zip(*locations[::-1])) # Non-maximum suppression parameters rects = [] for loc in locations: rects.append([int(loc[0]), int(loc[1]), int(loc[0] + template_width), int(loc[1] + template_height)]) # Apply non-maximum suppression to filter overlapping detections rects = np.array(rects) indices = cv2.dnn.NMSBoxes(rects.tolist(), [1] * len(rects), score_threshold=0, nms_threshold=0.5) # Count the number of unique detections unique_detections = len(indices) print(f'Number of unique detections: {unique_detections}') 

Step 5: Draw Bounding Boxes (Optional)

Optionally, draw bounding boxes around detected areas to visualize the detections.

for i in indices: x, y, x2, y2 = rects[i[0]] cv2.rectangle(main_image, (x, y), (x2, y2), (0, 255, 0), 2) # Display the result cv2.imshow('Detected Objects', main_image) cv2.waitKey(0) cv2.destroyAllWindows() 

Full Example Code

Here's the full example code combining all the steps:

import cv2 import numpy as np # Load the main image and convert to grayscale main_image = cv2.imread('main_image.jpg') main_gray = cv2.cvtColor(main_image, cv2.COLOR_BGR2GRAY) # Load the template image and convert to grayscale template = cv2.imread('template.jpg', 0) template_height, template_width = template.shape # Perform template matching result = cv2.matchTemplate(main_gray, template, cv2.TM_CCOEFF_NORMED) # Set a threshold to identify matches threshold = 0.8 locations = np.where(result >= threshold) # Extract the coordinates of matching locations locations = list(zip(*locations[::-1])) # Non-maximum suppression parameters rects = [] for loc in locations: rects.append([int(loc[0]), int(loc[1]), int(loc[0] + template_width), int(loc[1] + template_height)]) # Apply non-maximum suppression to filter overlapping detections rects = np.array(rects) indices = cv2.dnn.NMSBoxes(rects.tolist(), [1] * len(rects), score_threshold=0, nms_threshold=0.5) # Count the number of unique detections unique_detections = len(indices) print(f'Number of unique detections: {unique_detections}') # Draw bounding boxes around detected areas for i in indices: x, y, x2, y2 = rects[i[0]] cv2.rectangle(main_image, (x, y), (x2, y2), (0, 255, 0), 2) # Display the result cv2.imshow('Detected Objects', main_image) cv2.waitKey(0) cv2.destroyAllWindows() 

Explanation:

  1. Reading and Converting Images: The main image and the template image are read and converted to grayscale.
  2. Template Matching: cv2.matchTemplate performs template matching, and results are filtered based on a threshold.
  3. Non-Maximum Suppression: This step helps to eliminate multiple overlapping detections of the same object.
  4. Counting Unique Detections: The unique detections are counted after applying non-maximum suppression.
  5. Visualizing Detections: Bounding boxes are drawn around detected objects for visualization.

By following this approach, you can count the number of objects detected using template matching in Python with OpenCV.

Examples

  1. "python template matching count objects opencv"

    • Description: Use OpenCV to perform template matching and count the number of detected objects.
    • Code:
      import cv2 import numpy as np # Load the main image and template image img = cv2.imread('main_image.jpg', 0) template = cv2.imread('template.jpg', 0) w, h = template.shape[::-1] # Perform template matching res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED) threshold = 0.8 loc = np.where(res >= threshold) count = 0 for pt in zip(*loc[::-1]): count += 1 cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0, 255, 0), 2) print(f'Number of objects detected: {count}') cv2.imshow('Detected Objects', img) cv2.waitKey(0) cv2.destroyAllWindows() 
  2. "opencv template matching multiple objects detection"

    • Description: Detect and count multiple objects using OpenCV template matching by iterating through all matches.
    • Code:
      import cv2 import numpy as np # Load images image = cv2.imread('image.jpg', 0) template = cv2.imread('template.jpg', 0) w, h = template.shape[::-1] # Apply template matching result = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED) threshold = 0.8 locations = np.where(result >= threshold) detected_points = [] for pt in zip(*locations[::-1]): detected_points.append(pt) cv2.rectangle(image, pt, (pt[0] + w, pt[1] + h), (0, 255, 0), 2) print(f'Total detected objects: {len(detected_points)}') cv2.imshow('Detected', image) cv2.waitKey(0) cv2.destroyAllWindows() 
  3. "python count objects template matching threshold"

    • Description: Adjust the threshold value in template matching to count the number of detected objects accurately.
    • Code:
      import cv2 import numpy as np # Read images image = cv2.imread('main.jpg', 0) template = cv2.imread('template.jpg', 0) w, h = template.shape[::-1] # Template matching result = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED) threshold = 0.7 locations = np.where(result >= threshold) count = len(list(zip(*locations[::-1]))) print(f'Number of objects: {count}') for pt in zip(*locations[::-1]): cv2.rectangle(image, pt, (pt[0] + w, pt[1] + h), (255, 0, 0), 2) cv2.imshow('Result', image) cv2.waitKey(0) cv2.destroyAllWindows() 
  4. "opencv python template matching detect and count"

    • Description: Detect and count objects in an image using OpenCV template matching with a confidence threshold.
    • Code:
      import cv2 import numpy as np # Load images img_rgb = cv2.imread('image.jpg') img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY) template = cv2.imread('template.jpg', 0) w, h = template.shape[::-1] # Template matching result = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED) threshold = 0.6 loc = np.where(result >= threshold) count = 0 for pt in zip(*loc[::-1]): count += 1 cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 255, 255), 2) print(f'Detected objects: {count}') cv2.imshow('Detected', img_rgb) cv2.waitKey(0) cv2.destroyAllWindows() 
  5. "python detect objects template matching multiple instances"

    • Description: Use template matching to detect and count multiple instances of an object in an image.
    • Code:
      import cv2 import numpy as np # Load images main_image = cv2.imread('main_image.jpg', 0) template = cv2.imread('template.jpg', 0) w, h = template.shape[::-1] # Perform template matching result = cv2.matchTemplate(main_image, template, cv2.TM_CCOEFF_NORMED) threshold = 0.75 locations = np.where(result >= threshold) # Count matches and draw rectangles matches_count = 0 for pt in zip(*locations[::-1]): matches_count += 1 cv2.rectangle(main_image, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 1) print(f'Total matches found: {matches_count}') cv2.imshow('Matches', main_image) cv2.waitKey(0) cv2.destroyAllWindows() 
  6. "template matching opencv python count occurrences"

    • Description: Count the number of occurrences of an object in an image using OpenCV template matching.
    • Code:
      import cv2 import numpy as np # Load the main image and the template image = cv2.imread('main.jpg', 0) template = cv2.imread('template.jpg', 0) w, h = template.shape[::-1] # Template matching res = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED) threshold = 0.8 loc = np.where(res >= threshold) matches = zip(*loc[::-1]) match_count = sum(1 for _ in matches) print(f'Number of occurrences: {match_count}') for pt in zip(*loc[::-1]): cv2.rectangle(image, pt, (pt[0] + w, pt[1] + h), (255, 255, 0), 1) cv2.imshow('Detected', image) cv2.waitKey(0) cv2.destroyAllWindows() 
  7. "count template matches opencv python example"

    • Description: Example code to count the number of template matches using OpenCV in Python.
    • Code:
      import cv2 import numpy as np # Load the images img = cv2.imread('image.jpg', 0) template = cv2.imread('template.jpg', 0) w, h = template.shape[::-1] # Perform template matching res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED) threshold = 0.8 loc = np.where(res >= threshold) count = len(list(zip(*loc[::-1]))) print(f'Matched templates: {count}') for pt in zip(*loc[::-1]): cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0, 255, 0), 1) cv2.imshow('Result', img) cv2.waitKey(0) cv2.destroyAllWindows() 
  8. "template matching object counting python tutorial"

    • Description: A tutorial on how to count detected objects using template matching in Python with OpenCV.
    • Code:
      import cv2 import numpy as np # Load images img = cv2.imread('scene.jpg', 0) template = cv2.imread('template.jpg', 0) w, h = template.shape[::-1] # Perform template matching result = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED) threshold = 0.8 locations = np.where(result >= threshold) # Count the number of matches matches = list(zip(*locations[::-1])) num_matches = len(matches) print(f'Number of detected objects: {num_matches}') for pt in matches: cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 1) cv2.imshow('Detected', img) cv2.waitKey(0) cv2.destroyAllWindows() 

More Tags

headless-browser bots facebook-login higher-order-functions httpserver controller-action rootview iqueryable ncdf4 kotlin-null-safety

More Programming Questions

More Chemical reactions Calculators

More Math Calculators

More Internet Calculators

More Mixtures and solutions Calculators