In this article, we will use image processing to count the number of Objects using OpenCV in Python.
Module needed
- OpenCv: OpenCv is an open-source library that is useful for computer vision applications such as image processing, video processing, facial recognition, and detection, etc.
- Numpy: Numpy is a python package for scientific computing. It is a popular math library for Machine Learning. The main Object of Numpy is a multidimensional array.
- Matplotlib: Matplotlib is a Python library used for data visualization and graphical plotting of the data.
Image Used:.
Stepwise implementation
Step 1: Import required libraries.
Python3
# Import libraries import cv2 import numpy as np import matplotlib.pyplot as plt |
Step 2: We will read the image by using “cv2.imread(image-name)” command & then convert this image into grayscale image using “cv2.cvtColor(image-name, cv2.COLOR_BGR2GRAY)” command.
Python3
image = cv2.imread( 'coins.jpg' ) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) plt.imshow(gray, cmap = 'gray' ) |
Output:
Step 3: For counting, we have to detect the edges but before detecting the edges we have to make the image blur to avoid the noises. Use “cv2.GaussianBlur(image-name, Kernal size, std. deviation)”.
Python3
blur = cv2.GaussianBlur(gray, ( 11 , 11 ), 0 ) plt.imshow(blur, cmap = 'gray' ) |
Output:
Step 4: Now we will detect edges using a canny algorithm, 2nd & 3rd parameters in cv2.canny() function are threshold values. a value between 30 & 150 are consider as an edge for this image.
Python3
canny = cv2.Canny(blur, 30 , 150 , 3 ) plt.imshow(canny, cmap = 'gray' ) |
Output:
Step 5: We can see that edges are not connected. We need to connect the edges, have to make more thiker & visible.
Python3
dilated = cv2.dilate(canny, ( 1 , 1 ), iterations = 0 ) plt.imshow(dilated, cmap = 'gray' ) |
Output:
Step 6: Now we have to calculate the contour in the image & convert the image into RGB from BGR & then draw the contours.
Python3
(cnt, hierarchy) = cv2.findContours( dilated.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) cv2.drawContours(rgb, cnt, - 1 , ( 0 , 255 , 0 ), 2 ) plt.imshow(rgb) |
Output:
Step 7: Printing the result
Python3
print ( "coins in the image : " , len (cnt)) |
Output:
coins in the image: 5
Below is the complete implementation:
Python3
# Import libraries import cv2 import numpy as np import matplotlib.pyplot as plt image = cv2.imread( 'coins.jpg' ) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, ( 11 , 11 ), 0 ) canny = cv2.Canny(blur, 30 , 150 , 3 ) dilated = cv2.dilate(canny, ( 1 , 1 ), iterations = 0 ) (cnt, hierarchy) = cv2.findContours( dilated.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) cv2.drawContours(rgb, cnt, - 1 , ( 0 , 255 , 0 ), 2 ) print ( "coins in the image : " , len (cnt)) |
Output:
coins in the image : 5