StupidGuy
StupidGuy

Reputation: 97

Blob detection not working

I'm trying to detect blobs in an image but its not working somehow. Basically I want to determine number of circles.

Code:

import cv2
import numpy as np
import sys
# Read image
im = cv2.imread("K.jpg", cv2.IMREAD_GRAYSCALE)

# Setup SimpleBlobDetector parameters.
params = cv2.SimpleBlobDetector_Params()

# Change thresholds
params.minThreshold = 10
params.maxThreshold = 200

# Filter by Area.
params.filterByArea = True
params.minArea = 50

# Filter by Circularity
params.filterByCircularity = True
params.minCircularity = 0.75

# Filter by Convexity
params.filterByConvexity = True
params.minConvexity = 0.87

# Filter by Inertia
params.filterByInertia = True
params.minInertiaRatio = 0.7

detector = cv2.SimpleBlobDetector_create(params)


# Detect blobs.
keypoints = detector.detect(im)
print len(keypoints)
# 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(im, keypoints, np.array([]), (0, 0, 255),
                                      cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

# Show blobs
cv2.imshow("Keypoints", im_with_keypoints)
if cv2.waitKey(0) and 0xff==27:
    cv2.destroyAllWindows()

Here's the input image:

Image

Upvotes: 4

Views: 4330

Answers (1)

Jeru Luke
Jeru Luke

Reputation: 21203

I have figured out the solution.

When it comes to detection of blobs; you are identifying outliers/unwanted objects in the image. Hence these so called blobs/outliers are assumed to be black/grayish on a plain background. In other words, blobs are assumed to be easily identifiable against a white background.

When you perform blob detection against a gray scale image of the original image, the background present is black as shown:

enter image description here

Against a black background blob detection finds nothing :(

What do I do?

This is what I did. It was just a single line of a hack. I blurred the gray scale image and then inverted it using inverted_img = cv2.bitwise_not(blur)

I then passed the obtained image to the blob detection function. And this is what I got:

enter image description here

I am able to obtain the number of blobs present as well:

number = 0
for i in keypoints[0:]:
    number = number + 1    

print "Number of blobs:",number

And this is what I got in the console screen:

enter image description here

Upvotes: 8

Related Questions