“Python-OpenCV” How to Count the Number of Objects on Image.

Python

Hi, I’m higashi.

 

This time, I introduce how to count the number of objects on image as shown below by using Python-OpenCV.

sketch of this page

So, let’s get started!!

 

Sponsored Links

Method of Counting Objects

The approach of counting objects is shown below.

1.Binarize Image

2.Find Contours from Binarize Image

3.Count the Number of Contours

 

The key point is binarize process.

If you set the wrong threshold, you cannot find objects correctly.

 

So, you should try and error until you can find best value of threshold at first.

 

Sponsored Links

Sample Program of Count Objects on Image

So, let’s try by using this image.

Base image for programI think you can confirm that each object’s brightness is different.

Let’s confirm the affect of threshold I introduced before.

 

First of all, the sample program is this.

#import library
import cv2
import numpy as np
#load base image
img=cv2.imread('base_file.jpg',cv2.IMREAD_GRAYSCALE)
h,w=img.shape[:2]
#threshold of binarize
thresh_value=50
#process of binarize
thresh, img_thresh = cv2.threshold(img, thresh_value, 255, cv2.THRESH_BINARY)
#find countours
contours, hierarchy = cv2.findContours(img_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
#count the number of coutours
print(len(contours))
#making image for confirmation of detected objects
black_img=np.zeros((h,w),np.uint8)
for i in range(len(contours)):
    cv2.drawContours(black_img, contours, i, 255, -1)
cv2.imwrite('contours.jpg',black_img)

 

Sponsored Links

Result of Sample Program

So, let’s conduct the program by changing the threshold.

 

At fist I conduct the below setting.

thresh_value=50

 

The result shows 15.

This is the all object program could find.

objects that program could find

Let’s compare original image.

Original Image

I think you can confirm that the program could find all objects.

 

Next let’s try below setting.

thresh_value=150

 

The result shows 7.

This is the all object program could find.

objects that program could find

In this setting, program could not find low brightness object correctly.

 

I think you could confirm the importance of the setting of threshold.

So, please adjust this value to suit your image at first.

 

That’s all. Thank you!!

コメント