Mathew K Analytics

Lesson 56 · Data Science Projects

How to Count Objects in Images Using Python and OpenCV: A Step-by-Step Guide

Learn how computer vision can count objects in images. Discover the basics of OpenCV and image processing. Experience a practical project you can try…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Counting Number of Objects Using Python and OpenCV#

  • Learn how computer vision can count objects in images.
  • Discover the basics of OpenCV and image processing.
  • Experience a practical project you can try yourself.
  • This lesson is beginner friendly!

What is Object Counting?#

  • Object counting means finding how many items or shapes are in a picture.
  • This is used in traffic monitoring, manufacturing, health, and lots more.
  • We use computer vision, which means teaching computers to see and understand pictures.
  • OpenCV is a popular tool for this.
# Suppress warnings to keep our output clean
import warnings; warnings.filterwarnings("ignore")
import numpy as np
np.random.seed(42)
 

Data setup: Creating a Simple Image with Shapes#

  • Let us make a blank image with white shapes: one circle and one rectangle.
  • This makes it easy to test object detection.
  • We will use NumPy and OpenCV for this.
# Data setup
import cv2
import numpy as np
img = np.zeros((200, 200, 3), dtype=np.uint8)
cv2.circle(img, (50, 50), 20, (255, 255, 255), -1)
cv2.rectangle(img, (120, 30), (170, 80), (255, 255, 255), -1)
print(img.shape)
(200, 200, 3)
# Show the image using matplotlib
import matplotlib.pyplot as plt
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.title("Synthetic Objects Image")
plt.axis("off")
plt.show()
No description has been provided for this image

How Does Object Counting Work?#

  • Computers see images as numbers, not pictures.
  • The basic steps are: convert to grayscale, make features stand out, find object edges, and detect shapes.
  • We will use contours to count objects. A contour is a line that outlines an object.
# Convert the image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Show the grayscale image
plt.imshow(gray, cmap="gray")
plt.title("Grayscale Image")
plt.axis("off")
plt.show()
No description has been provided for this image
# Apply thresholding to get a binary image
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# Show the thresholded image
plt.imshow(thresh, cmap="gray")
plt.title("Thresholded Image")
plt.axis("off")
plt.show()
No description has been provided for this image

Finding Contours (Object Borders)#

  • Contours are lines following the border of each object.
  • OpenCV can find all contours automatically.
  • Each contour matches one visible shape in the picture.
# Find contours in the thresholded image
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print("Number of contours found:", len(contours))
Number of contours found: 2
# Draw contours on a copy of the image for visualization
img_with_contours = img.copy()
cv2.drawContours(img_with_contours, contours, -1, (0,255,0), 3)
plt.imshow(cv2.cvtColor(img_with_contours, cv2.COLOR_BGR2RGB))
plt.title("Image with Contours")
plt.axis("off")
plt.show()
No description has been provided for this image

Counting the Number of Objects#

  • Each contour found means one separate object detected.
  • Simply count the contours to get the object count.
  • This is how OpenCV helps automate tasks where people would need to count by hand.
# Print the total number of objects found
num_objects = len(contours)
print("Number of objects detected:", num_objects)
Number of objects detected: 2
# Try it yourself: Add another shape and count again
# This will draw an ellipse as a third object
img_more = np.zeros((200, 200, 3), dtype=np.uint8)
cv2.circle(img_more, (50, 50), 20, (255,255,255), -1)
cv2.rectangle(img_more, (120,30), (170,80), (255,255,255), -1)
cv2.ellipse(img_more, (150,150), (20,10), 0, 0, 360, (255,255,255), -1)
gray_more = cv2.cvtColor(img_more, cv2.COLOR_BGR2GRAY)
ret, thresh_more = cv2.threshold(gray_more, 127, 255, cv2.THRESH_BINARY)
contours_more, _ = cv2.findContours(thresh_more, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
num_objects_more = len(contours_more)
print("After adding, number of objects detected:", num_objects_more)
After adding, number of objects detected: 3

Where Can Object Counting Be Useful?#

  • Inventory control to count products on a conveyor belt.
  • Monitoring the number of cars or people.
  • Bird, plant, or bacteria sample counting.
  • Any scene where you want to count things automatically!

Recap: What Did We Learn?#

  • How to create a simple image with shapes using OpenCV.
  • How to preprocess an image: grayscale and thresholding.
  • Finding contours to detect object edges.
  • Counting the objects in a picture with just a few lines of Python.
  • Tuning detection by changing or adding shapes.
# Challenge: Try With Your Own Images
path = input("Enter a path to your own image file, or leave blank to skip: ")
if path.strip():
    user_img = cv2.imread(path)
    if user_img is None:
        print("Sorry, could not read the image. Check the path or file type.")
    else:
        gray_u = cv2.cvtColor(user_img, cv2.COLOR_BGR2GRAY)
        _, thresh_u = cv2.threshold(gray_u, 127, 255, cv2.THRESH_BINARY)
        contours_u, _ = cv2.findContours(thresh_u, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        print("Objects detected in your image:", len(contours_u))
        plt.imshow(cv2.cvtColor(user_img, cv2.COLOR_BGR2RGB))
        plt.title("Your Image")
        plt.axis("off")
        plt.show()
else:
    print("Skipped. You can try with your own images later.")
Skipped. You can try with your own images later.
 

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.