DEV Community

loading...
Cover image for How to count objects on an image with Python

How to count objects on an image with Python

Stokry
Front_dev | Machine Learning Enthusiast
・1 min read

In this tutorial, you will learn how you can count the number of objects on an image with Python using CV2.

This is our test image:

enter image description here

Let's jump to the code:

First we need to import our dependencies:

import cv2
import numpy as np
Enter fullscreen mode Exit fullscreen mode

First we need to read our image:

img = cv2.imread('test.jpg')
Enter fullscreen mode Exit fullscreen mode

then we will be converting it into grayscale

img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Enter fullscreen mode Exit fullscreen mode

after that, we doing thresholding on image

_, thresh = cv2.threshold(img, 225, 255, cv2.THRESH_BINARY_INV)
kernal = np.ones((2, 2), np.uint8)
Enter fullscreen mode Exit fullscreen mode

then we are doing dilation process, removing black distortion:

dilation = cv2.dilate(thresh, kernal, iterations=2)
Enter fullscreen mode Exit fullscreen mode

next step is finding contour shapes:

contours, hierarchy = cv2.findContours(
    dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
Enter fullscreen mode Exit fullscreen mode

Then we are getting number of contours (objects found):

objects = str(len(contours))
Enter fullscreen mode Exit fullscreen mode

We can now print number of objects on an image

text = "Obj:"+str(objects)
cv2.putText(dilation, text, (10, 25),  cv2.FONT_HERSHEY_SIMPLEX,
            0.4, (240, 0, 159), 1)
Enter fullscreen mode Exit fullscreen mode

For the lasr step we can show, original, threshold and dilation image:

cv2.imshow('Original', img)
cv2.imshow('Thresh', thresh)
cv2.imshow('Dilation', dilation)

cv2.waitKey(0)
cv2.destroyAllWindows()
Enter fullscreen mode Exit fullscreen mode

This is our final result:

enter image description here

Thank you all.

Discussion (2)

Collapse
mccurcio profile image
Matt Curcio

Nice step-by-step explanations.
Good job

Collapse
stokry profile image
Stokry Author

Thanks😀

Forem Open with the Forem app