Detect white blobs using opencv python


I am trying to simply find white circular blobs in an image. When i tried going with houghcircles, I keep getting letters and digits mistaken for circles, whereas I only need complete circles, i.e. blobs.

So I ran this blob detector code with custom params to find the circular IC pin mark on the upper left corner. But I keep getting dark circles inside ‘9’ and ‘0’.
It doesnt detect any white blobs at all.

Here is the code I tried:

import cv2
import numpy as np;

# Read image
img = cv2.imread("C:\chi4.jpg", cv2.IMREAD_GRAYSCALE)
retval, threshold = cv2.threshold(img, 200, 255, cv2.THRESH_BINARY)

params = cv2.SimpleBlobDetector_Params()

# Change thresholds
params.minThreshold = 10;
params.maxThreshold = 255;

blur = cv2.GaussianBlur(img,(5,5),0)

params.filterByCircularity = True
params.minCircularity = 0.2

params.filterByArea = True;
params.minArea = 1000;

ver = (cv2.__version__).split('.')
if int(ver[0]) < 3 :
    detector = cv2.SimpleBlobDetector(params)
else :
    detector = cv2.SimpleBlobDetector_create(params)

# Set up the detector with default parameters.
#detector = cv2.SimpleBlobDetector()

# Detect blobs.
keypoints = detector.detect(threshold)

# Draw detected blobs as red circles.
# cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the size of the circle corresponds to the size of blob
im_with_keypoints = cv2.drawKeypoints(img, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

# Show keypoints
cv2.imshow("Keypoints", im_with_keypoints)

Here is my output image:
Output image

The red circles are the detected ones. I want the white circular blob, in the top marked in blue to be detected.

I tried changing the threshold parameters, still no impact. Kindly let me know where I am going wrong or suggestions to improve the output.
Thanks in advance 😀


Blobs are generally assumed to be gray/black. In your case the blobs in side the letters are black. However the blob you have intended is white. Hence it Is not recognized.

In your code you have to change the fourth line to:

retval, threshold = cv2.threshold(img, 200, 255, cv2.THRESH_BINARY_INV)

I followed the same approach for the following:

I performed blob detection on the following image:

enter image description here

but did not find any blob:

enter image description here

I inverted the binary image to the following:

enter image description here

now I was able to detect them as shown:

enter image description here

Answered By – Jeru Luke

Answer Checked By – Dawn Plyler (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.