Blobs, blobs, and more blobs detection in Python.

Misha Ysabel
Data Caffeine
Published in
3 min readFeb 2, 2021

Blob Detection

Have you ever wondered how do computers detect objects and count? How something so intuitive for us humans is complicated for computers.

Thankfully we have scikit-image feature tools. In this article, we will discuss several methods in detecting blobs. The package has three kinds of blob detection methods:

1. Laplacian of Gaussian (LoG)
2. Difference of Gaussian (DoG)
3. Determinant of Hessian (DoH).

Importing the libraries

from skimage.feature import blob_dog, blob_log, blob_doh
from skimage.io import imread, imshow
from skimage.color import rgb2gray
from math import sqrt
import matplotlib.pyplot as plt
import numpy as np
from skimage.morphology import erosion, dilation, opening, closing
from skimage.measure import label, regionprops
from skimage.color import label2rgb
im = rgb2gray(imread('nuts.PNG'))
imshow(im);
im_bw = im<0.8
imshow(im_bw)

In this example, we will be detecting and counting almond nuts on a plate. First, we have to binarize the image as learned in the previous articles. Secondly, we make a mask that marks the nuts with “1” and the background with “0”.

Now to the blob part. We get the blob using the functions imported above. The output is a list of blob objects with their coordinate values and area. We can adjust the blob detection by changing the parameters max_sigma, num_sigma, and threshold.

blobs = blob_log(im_bw, max_sigma=30, min_sigma = 23, num_sigma=2, threshold=0.3, overlap = 0.1)fig, ax = plt.subplots()
ax.imshow(im_bw, cmap='gray')
for blob in blobs:
y, x, area = blob
ax.add_patch(plt.Circle((x, y), area*np.sqrt(2), color='r',
fill=False))

Doing a simple len() function over the blob output will allow us to count the number of almond nuts — 26.

Connected Components

On the other hand, what if we want to detect objects that are irregular in shape — not circular in shape. Given this circumstance, we can detect objects

def multi_dil(im,num):
for i in range(num):
im = dilation(im)
return im
def multi_ero(im,num):
for i in range(num):
im = erosion(im)
return im

First, we apply morphological operations of dilation and erosion to the image giving us the image below.

Next, we label the image and use regionprops to detect the various almond nuts in the photo.

label_im = label(im_cleaned)
imshow(label_im)
fig, ax = plt.subplots(figsize=(10, 100))imshow(label_im)for i in regionprops(label_im):
minr, minc, maxr, maxc = i.bbox
rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
fill=False, edgecolor='red', linewidth=2)
ax.add_patch(rect)
ax.set_axis_off()

plt.show()

As you have noticed, the nuts that are interconnected are detected as one object by regionprops. Regionprops has the following properties….

That’s all for now, on the next article in my image processing series.

--

--