Teng Ma Teng Ma - 1 year ago 744
Python Question

Blob detection using OpenCV

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?

Please see the image below:

Greyscale source image

And here is the script:


# Standard imports
import cv2
import numpy as np;

import Image
import ImageOps

# Apply a one pixel red border to the image
source = Image.open('white.jpg')
bordered = ImageOps.expand(source,border=1,fill='#ffffff')

# Read image
im = cv2.imread('white2.jpg', cv2.IMREAD_GRAYSCALE)

# Save the greyscale image

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

params.blobColor= 255
params.filterByColor = True

# Change thresholds
#params.minThreshold = 0
#params.maxThreshold = 255

# Filter by Area.
params.filterByArea = True
params.minArea = 800
**params.maxArea = 500000**

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

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

# Filter by Inertia
#params.filterByInertia = True
#params.maxInertiaRatio = 0.5

# 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(im)

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

im_with_keypoints = cv2.drawKeypoints(im, 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.

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