Shahbaz Khan
Shahbaz Khan

Reputation: 76

Detecting white blobs on grayscale image using MSER in opencv

I have images which are largely black with few whitish blobs on them. I want to distinguish such images from those which do not have such blobs.

I tried MSER and tuned its parameters to correctly detect blobs in most of the images which have them and return 0 result in those that don't.

Here's my MSER parameter configuration.

mser = cv2.MSER_create(_delta = 3,_min_diversity=0.2,_edge_blur_size = 5 ,_max_variation = 0.10,_min_area = 120,_max_area = 1000)

Below is a test image:

test image

The white region on the top is not being detected.

Upvotes: 3

Views: 1615

Answers (1)

nathancy
nathancy

Reputation: 46620

Instead of using MSER, here are two simpler approaches

Method #1

Convert image to grayscale and Otsu's threshold to obtain a binary image. Then find contours and filter using a minimum threshold area. Depending on how much white blob you want to detect, you can adjust this threshold area. Here's the results with the detected white region highlighted in green

enter image description here

import cv2

image = cv2.imread('1.png')
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

cnts = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    area = cv2.contourArea(c)
    if area > 50:
        cv2.drawContours(original, [c], -1, (36, 255, 12), -1)

cv2.imshow('thresh', thresh)
cv2.imshow('original', original)
cv2.imwrite('original.png', original)
cv2.waitKey()

Method #2

Since OpenCV images are stored as Numpy arrays, we can simply use slicing to create a mask of pixels greater than some threshold. Here's the results

enter image description here

import cv2

image = cv2.imread('1.png')
mask = (image >= [150.,150.,150.]).all(axis=2)
image[mask] = [36, 255, 12]

cv2.imshow('image', image)
cv2.waitKey()

Upvotes: 3

Related Questions