bg

Count Number of Dots in an Image With OpenCV


Posted on May 13, 2022

Example Image

The following image will used as an example.

Process

file.py

_15
# OpenCV library will be needed.
_15
import cv2
_15
# OPTIONAL display image for Google Colaboratory ONLY
_15
from google.colab.patches import cv2_imshow
_15
_15
_15
# Load the image with opencv
_15
new_image = cv2.imread("example.png")
_15
_15
# Grayscale image
_15
gray = cv2.cvtColor(new_image, cv2.COLOR_BGR2GRAY)
_15
_15
# OPTIONAL invert image color
_15
gray = ~gray
_15
cv2_imshow(gray) or cv2.imshow('title',gray)

Displayed Image

file.py

_10
# Using Adaptive Thresholding to recognize the dots and make them true black(0, 0, 0)
_10
# OpenCV Adaptive Thresholding Documentation: https://docs.opencv.org/4.x/d7/d4d/tutorial_py_thresholding.html
_10
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 21, 50)
_10
cv2_imshow(thresh) or cv2.imshow('title',thresh)

Displayed Image

file.py

_10
# OpenCV Contours Documentation: https://docs.opencv.org/4.x/d4/d73/tutorial_py_contours_begin.html
_10
Contours, Hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
_10
# Draw contours over original image
_10
Image = cv2.drawContours(new_image, Contours, -1, (0, 255, 0), 1)
_10
cv2_imshow(Image) or cv2.imshow('title',Image)
_10
# Contour count = number of dots
_10
print(len(Contours))

Displayed Image

Total number of dots found: 474

Full Code

file.py

_19
import cv2
_19
from google.colab.patches import cv2_imshow # OPTIONAL display image for Google Colaboratory ONLY
_19
_19
new_image = cv2.imread("example.png")
_19
gray = cv2.cvtColor(new_image, cv2.COLOR_BGR2GRAY)
_19
gray = ~gray
_19
_19
cv2_imshow(gray) or cv2.imshow('title',gray) # Show image
_19
_19
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 21, 50)
_19
_19
cv2_imshow(thresh) or cv2.imshow('title',thresh) # Show image
_19
_19
Contours, Hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
_19
Image = cv2.drawContours(new_image, Contours, -1, (0, 255, 0), 1)
_19
_19
cv2_imshow(Image) or cv2.imshow('title',Image) # Show image
_19
_19
print(len(Contours))

© cocdeshijie. All rights reserved.