Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count number of dots in an image using python and Opencv?

Tags:

python

opencv

I want to count number of dots in an image. The image looks like Dots Image

I referred to this SOF link count colored dots in image But this is for colored links , So anyone here can guide me over how to handle this and count black dots out of white back.

like image 353
Yash Kumar Atri Avatar asked Oct 27 '25 15:10

Yash Kumar Atri


1 Answers

  1. thredhold using THRESH_BINARY_INV flag, change to black-background-white-foreground.
  2. findContours, filter the contours by area(calculated by contourArea)
  3. You get it

import cv2
gray = cv2.imread("dots.jpg", 0)

## threshold
th, threshed = cv2.threshold(gray, 100, 255,cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)

## findcontours
cnts = cv2.findContours(threshed, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2]


## filter by area
s1= 3
s2 = 20
xcnts = []
for cnt in cnts:
    if s1<cv2.contourArea(cnt) <s2:
        xcnts.append(cnt)

print("Dots number: {}".format(len(xcnts)))
#Dots number: 23

enter image description here

like image 97
Kinght 金 Avatar answered Oct 29 '25 05:10

Kinght 金



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!