Teng Ma Teng Ma - 1 year ago 409
Python Question

Blob detection using OpenCV -Solved

I am trying to do some white blob detection using OpenCV. But my script failed to detect the big white block which is my goal while some small blobs are detected. I am new to OpenCV, and am i doing something wrong when using simpleblobdetection in OpenCV? [Solved partially, please read below]

And here is the script:


# Standard imports
import cv2
import numpy as np;

from matplotlib import pyplot as plt

# Read image
im = cv2.imread('whiteborder.jpg', cv2.IMREAD_GRAYSCALE)
imfiltered = cv2.inRange(im,255,255)

kernel = np.ones((5,5))

opening = cv2.morphologyEx(imfiltered,cv2.MORPH_OPEN,kernel)

#write out the filtered image


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

params.blobColor= 255
params.filterByColor = True

# Create a detector with the parameters
ver = (cv2.__version__).split('.')
if int(ver[0]) < 3 :
detector = cv2.SimpleBlobDetector(params)
else :
detector = cv2.SimpleBlobDetector_create(params)

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

# Draw detected blobs as green circles.
# the size of the circle corresponds to the size of blob

print str(keypoints)

im_with_keypoints = cv2.drawKeypoints(opening, keypoints, np.array([]), (0,255,0), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

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




By adding a bigger value of area maximum value, i am able to identify a big blob but my end goal is to identify the big white rectangle exist or not. And the white blob detection i did returns not only the rectangle but also the surrounding areas as well. [This part solved]


Based on the answer from @PSchn, i update my code to apply the logic, first set the color filter to only get the white pixels and then remove the noise point using opening. It works for the sample data and i can successfully get the keypoint after blob detection.
enter image description here

Answer Source

If you just want to detect the white rectangle you can try to set a higher threshold, e.g. 253, erase small object with an opening and take the biggest blob. I first smoothed your image, then thresholding it:

enter image description here

and the opening:

enter image description here

now you just have to use findContours and take the boundingRect. If your rectangle is always that white it should work. If you get lower then 251 with your threshold the other small blobs will appear and your region merges with them, like here:

enter image description here

Then you could still do an opening several times and you get this: enter image description here

But i dont think that it is the fastest idea ;)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download