Blob Detection OpenCV Python Read it later

5/5 - (1 vote)

If you’ve ever wondered how to identify and analyze blobs within images, you’ve come to the right place. Get ready to unlock the secrets of blob detection in Python and witness the sheer power of image analysis. So, buckle up and let’s embark on this exciting journey together!

What are Blobs?

Blob detection is a fundamental technique in computer vision used to identify and locate regions of interest (blobs) within an image.

A blob is typically defined as a group of connected pixels that share similar properties, such as color, intensity, or texture.

Think of blobs as objects or regions that stand out from the background, like stars in the night sky or cells in a microscopic image.

Application of Blob Detection

Blob detection is widely used in a plethora of real-world applications. Let’s explore a few of them and see how blob detection can empower these domains.

Object Recognition and Tracking

Blob detection forms the foundation for object recognition and tracking tasks. By detecting and tracking blobs, we can identify and follow objects of interest in video streams or surveillance footage.

This capability is invaluable in applications such as motion detection, autonomous vehicles, and augmented reality.

Counting Objects in an Image

Need to count the number of cells in a microscopic image or track the number of people in a crowded scene? Blob detection can come to the rescue!

By detecting and analyzing blobs, we can accurately count objects and gather valuable quantitative data.

Identifying Irregularities and Anomalies

Blobs can help us identify irregularities or anomalies in images or video frames. For example, in medical imaging, blob detection can be used to detect tumors or abnormalities in X-ray or MRI scans.

Similarly, in manufacturing processes, blob detection can identify defects or malfunctions in products or components.

Blob Detection Using SimpleBlobDetector

OpenCV provides various algorithms to detect blobs in an image. One such algorithm is the SimpleBlobDetector algorithm, which is based on the concept of finding the local maxima of the Laplacian of the image.

The SimpleBlobDetector algorithm uses a set of parameters to filter out the blobs that do not match the criteria set by the user. These parameters include:

  1. Threshold: The minimum threshold value for the Laplacian of the image. Blobs with Laplacian values below this threshold will be ignored.
  2. Area: The minimum and maximum area of the blobs to be detected.
  3. Circularity: The minimum and maximum circularity of the blobs to be detected.
  4. Convexity: The minimum and maximum convexity of the blobs to be detected.
  5. Inertia Ratio: The minimum and maximum inertia ratio of the blobs to be detected.

SimpleBlobDetector Example

To detect blobs using the SimpleBlobDetector algorithm in OpenCV, we first need to import the necessary libraries and load an image.

import cv2
import numpy as np

# Load image
img = cv2.imread("image.jpg", cv2.IMREAD_GRAYSCALE)

Next, we need to create a SimpleBlobDetector object and set the parameters for blob detection.

# Set up the SimpleBlobDetector with default parameters
params = cv2.SimpleBlobDetector_Params()

# Set the threshold
params.minThreshold = 10
params.maxThreshold = 200

# Set the area filter
params.filterByArea = True
params.minArea = 100
params.maxArea = 1000

# Set the circularity filter
params.filterByCircularity = True
params.minCircularity = 0.1
params.maxCircularity = 1

# Set the convexity filter
params.filterByConvexity = True
params.minConvexity = 0.87
params.maxConvexity = 1

# Set the inertia filter
params.filterByInertia = True
params.minInertiaRatio = 0.01
params.maxInertiaRatio = 1

# Create a detector with the parameters
detector = cv2.SimpleBlobDetector_create(params)

We can now detect the blobs in the image using the detect method of the detector object.

# Detect blobs
keypoints = detector.detect(img)

# Draw detected blobs as red circles
img_with_keypoints = cv2.drawKeypoints(img, keypoints, np.array([]), (0, 0, 255),
                                       cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

# Show the image with detected blobs
cv2.imshow("Blobs", img_with_keypoints)
cv2.waitKey(0)
cv2.destroyAllWindows()

The above code will detect the blobs in the image and display the image with detected blobs as red circles.

SimpleBlobDetector Parameter

The SimpleBlobDetector algorithm in OpenCV provides various parameters that can be adjusted to improve the blob detection accuracy.

Here are some of the most commonly used parameters:

  • filterByArea: Enables filtering blobs by their area. This parameter takes a boolean value (True or False).
  • minArea: Sets the minimum area of a blob to be detected. Blobs smaller than this value will be ignored.
  • maxArea: Sets the maximum area of a blob to be detected. Blobs larger than this value will be ignored.
  • filterByCircularity: Enables filtering blobs by their circularity. This parameter takes a boolean value (True or False).
  • minCircularity: Sets the minimum circularity of a blob to be detected. Blobs with circularity values smaller than this will be ignored.
  • maxCircularity: Sets the maximum circularity of a blob to be detected. Blobs with circularity values larger than this will be ignored.
  • filterByConvexity: Enables filtering blobs by their convexity. This parameter takes a boolean value (True or False).
  • minConvexity: Sets the minimum convexity of a blob to be detected. Blobs with convexity values smaller than this will be ignored.
  • maxConvexity: Sets the maximum convexity of a blob to be detected. Blobs with convexity values larger than this will be ignored.
  • filterByInertia: Enables filtering blobs by their inertia. This parameter takes a boolean value (True or False).
  • minInertiaRatio: Sets the minimum inertia ratio of a blob to be detected. Blobs with inertia ratios smaller than this will be ignored.
  • maxInertiaRatio: Sets the maximum inertia ratio of a blob to be detected. Blobs with inertia ratios larger than this will be ignored.

Filtering Blobs

Now that you have the basics of blob detection under your belt, let’s explore how to customize the parameters for more precise and tailored blob detection.

Blob Color Filtering

If you’re interested in blobs with specific colors, you can apply color filtering to the image before blob detection.

Color filtering allows you to isolate blobs based on their color or hue, effectively filtering out unwanted blobs.

# Apply color filtering to isolate blobs of a specific color range
filtered = cv2.inRange(image, lower_color, upper_color)
Adjusting Blob Size and Shape

You can also fine-tune the size and shape of blobs you want to detect. By setting appropriate minimum and maximum thresholds for blob size and shape, you can filter out blobs that are too small or too large.

# Configure blob size filtering
params.filterByArea = True
params.minArea = 100
params.maxArea = 1000

# Configure blob shape filtering
params.filterByCircularity = True
params.minCircularity = 0.8

# Re-create the detector with the updated parameters
detector = cv2.SimpleBlobDetector_create(params)
Filtering Blobs by Circularity and Convexity

Circularity and convexity are two essential characteristics of blobs. By adjusting the circularity and convexity thresholds, you can selectively detect blobs based on their roundness or convex shape.

# Configure blob circularity filtering
params.filterByCircularity = True
params.minCircularity = 0.7

# Configure blob convexity filtering
params.filterByConvexity = True
params.minConvexity = 0.8

# Re-create the detector with the updated parameters
detector = cv2.SimpleBlobDetector_create(params)

Blob Detection Using Laplacian of Gaussian (LoG)

Laplacian of Gaussian is a popular technique used for blob detection that applies a Gaussian filter to an image and then applies Laplacian filter to detect the regions of high intensity variation.

This technique is more robust than simple blob detection and can detect blobs of different sizes and shapes.

Let’s take an example and detect blobs in an image using Laplacian of Gaussian.

import cv2
import numpy as np

# Load image
image = cv2.imread('blob.jpg', cv2.IMREAD_GRAYSCALE)

# Apply Laplacian of Gaussian
blobs_log = cv2.Laplacian(image, cv2.CV_64F)
blobs_log = np.uint8(np.absolute(blobs_log))
    
# Set up the detector with default parameters.
params = cv2.SimpleBlobDetector_Params()

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

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

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

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

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

# Create a detector with the parameters
detector = cv2.SimpleBlobDetector_create(params)

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

# Draw detected blobs as red circles.
# cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the size of the circle corresponds to the size of the blob
im_with_keypoints = cv2.drawKeypoints(image, keypoints, np.array([]), (0, 0, 255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

# Show keypoints
cv2.imshow("Keypoints", im_with_keypoints)
cv2.waitKey(0)

In the above example, we have loaded an image ‘blob.jpg’ in grayscale and applied Laplacian of Gaussian on it to detect the blobs.

We have set the parameters to filter blobs based on area, circularity, convexity, and inertia, and then created a detector using these parameters.

Finally, we have detected the blobs and drawn red circles around them using the cv2.drawKeypoints function.

Blob Detection Using Difference of Gaussians (DoG)

Difference of Gaussians is another popular technique used for blob detection that applies a difference filter to an image by subtracting two Gaussian filters of different sizes.

This technique is also more robust than simple blob detection and can detect blobs of different sizes and shapes.

Let’s take an example and detect blobs in an image using Difference of Gaussians.

import cv2
import numpy as np

# Load image
image = cv2.imread('blob.jpg', cv2.IMREAD_GRAYSCALE)

# Apply Difference of Gaussian
blobs_dog = cv2.GaussianBlur(image, (5,5), 0) - cv2.GaussianBlur(image, (15,15), 0)
    
# Set up the detector with default parameters.
params = cv2.SimpleBlobDetector_Params()

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

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

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

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

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

# Create a detector with the parameters
detector = cv2.SimpleBlobDetector_create(params)

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

# Draw detected blobs as red circles.
# cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the size of the circle corresponds to the size of the blob
im_with_keypoints = cv2.drawKeypoints(image, keypoints, np.array([]), (0, 0, 255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

# Show keypoints
cv2.imshow("Keypoints", im_with_keypoints)
cv2.waitKey(0)

In the above example, we have loaded an image ‘blob.jpg’ in grayscale and applied Difference of Gaussian on it to detect the blobs.

We have set the parameters to filter blobs based on area, circularity, convexity, and inertia, and then created a detector using these parameters.

Finally, we have detected the blobs and drawn red circles around them using the cv2.drawKeypoints function.

Blob Detection Using Masking technique

Another technique that can be used for blob detection is the masking technique. In this technique, we first create a mask of the image where we set the regions of interest to white and the background to black. Then, we apply thresholding on the mask to get a binary image, which is further processed to detect the blobs.

Let’s take an example and detect blobs in an image using the masking technique.

import cv2
import numpy as np

# Load image
image = cv2.imread('blob.jpg', cv2.IMREAD_GRAYSCALE)

# Create a mask
mask = np.zeros(image.shape[:2], np.uint8)
mask[100:300, 100:400] = 255

# Apply thresholding
thresholded = cv2.threshold(image, 50, 255, cv2.THRESH_BINARY)[1]

# Combine mask and thresholded image
masked = cv2.bitwise_and(thresholded, thresholded, mask=mask)

# Set up the detector with default parameters.
params = cv2.SimpleBlobDetector_Params()

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

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

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

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

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

# Create a detector with the parameters
detector = cv2.SimpleBlobDetector_create(params)

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

# Draw detected blobs as red circles.
# cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the size of the circle corresponds to the size of the blob
im_with_keypoints = cv2.drawKeypoints(image, keypoints, np.array([]), (0, 0, 255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

# Show keypoints
cv2.imshow("Keypoints", im_with_keypoints)
cv2.waitKey(0)

In this example, we have first created a mask of the image by setting the region of interest to white and the background to black.

We then applied thresholding on the image and combined it with the mask to get a binary image with only the regions of interest. Then set the parameters to filter blobs based on area, circularity, convexity, and inertia and created a detector using these parameters.

Finally, we have detected the blobs and drawn red circles around them using the cv2.drawKeypoints function.

Wrapping Up

Congratulations! You’ve successfully embarked on an exciting journey into the world of blob detection using OpenCV in Python. We covered the basics of blob detection, explored different techniques of blob detection like SimpleBlogDetector, Laplacian of Gaussian (LoG), Difference of Gaussian (DoG) and Masking Technique, filtering blobs and detecting blobs, and even discovered real-world applications of this powerful technique.

References

Was This Article Helpful?

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *