Skip to main content

Software Sushi JournalComputer vision

OpenCV Filtering, Thresholding, and Image Segmentation

Clean up noise, turn brightness into a mask, and separate the regions you want to measure.

A red pear and blue cup seen through clear and frosted optical glass
Optical illustration of how smoothing changes visible detail.

From noisy pixels to regions

Run the pipeline on a synthetic grayscale sample or change the filter and cutoff yourself.

Pipeline stage
Original
Connected regions

Each color marks a group of foreground pixels joined horizontally or vertically.

3 regions22.9% foreground

Smoothing filter

Filtering changes pixel values. Thresholding decides which pixels belong to the foreground. Segmentation groups those pixels into regions you can count or measure.

Prepare the input

Load the image in color. Convert BGR to grayscale when brightness separates the objects from the background, or convert to HSV if you need to select a color range. Keep a copy of the original for comparison.

Load the image and convert color spaces

Install opencv-python and numpy, then point the example at a local image. For the mask examples, choose bright objects on a darker background.

Python
import cv2 as cv
import numpy as np

bgr = cv.imread("sample.jpg")
if bgr is None:
    raise FileNotFoundError("Could not open sample.jpg")

rgb = cv.cvtColor(bgr, cv.COLOR_BGR2RGB)
gray = cv.cvtColor(bgr, cv.COLOR_BGR2GRAY)
hsv = cv.cvtColor(bgr, cv.COLOR_BGR2HSV)

Choose a smoothing filter

Start with a small kernel and check the edges you need to keep. A stronger blur can remove specks and also erase a narrow gap between objects.

Mean
Average nearby pixels evenly. Use it as a simple baseline.
Gaussian
Give nearby pixels more weight. Try it when noise is spread across the image.
Median
Take the middle brightness in the neighborhood. Try it for isolated bright and dark specks.
Bilateral
Give more weight to pixels with similar brightness. Compare it when preserving edges matters.
The original colorful bird image, the same image with speckle noise, and the result after median filtering.
Compare the noisy input and the median-filtered image. Inspect the edges as well as the specks.
Compare four OpenCV filters
Python
mean = cv.blur(gray, (5, 5))
gaussian = cv.GaussianBlur(gray, (5, 5), 0)
median = cv.medianBlur(gray, 5)
bilateral = cv.bilateralFilter(gray, 9, 75, 75)

Make a binary mask

With THRESH_BINARY, pixels strictly above the cutoff turn white. The rest turn black. Use THRESH_BINARY_INV to keep darker pixels as foreground.

Use a fixed threshold under consistent lighting, Otsu to choose a global cutoff from the image histogram, or an adaptive threshold when brightness varies across the scene. Inspect the mask each method produces before choosing one.

Compare fixed, Otsu, and adaptive masks
Python
_, fixed = cv.threshold(median, 124, 255, cv.THRESH_BINARY)

otsu_cutoff, otsu = cv.threshold(
    median, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU
)

adaptive = cv.adaptiveThreshold(
    median, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C,
    cv.THRESH_BINARY, 25, 2,
)

See the OpenCV thresholding tutorial for examples with uneven illumination.

Count and measure connected regions

Connected components gives each group of foreground pixels a label. Use four-neighbor connectivity to join horizontal and vertical neighbors, as the lab does. Use eight neighbors if diagonal contact should join two pixels. The background has label zero.

Label the mask and inspect region areas
Python
count, labels, stats, centers = cv.connectedComponentsWithStats(
    fixed, connectivity=4
)
areas = stats[1:, cv.CC_STAT_AREA]
print(f"{count - 1} foreground regions")
print("Areas in pixels:", areas)

Compare the regions with the original image. A bright speck can count as a separate region, and touching objects can count as one.

Handle touching objects and complex backgrounds

Watershed for touching objects

Use marker-based watershed when a binary mask joins objects you need to count separately. A distance transform can help you find seeds inside the objects. Inspect those seeds first because they guide where the separation occurs.

Build markers and run watershed
Python
kernel = np.ones((3, 3), dtype=np.uint8)
clean = cv.morphologyEx(fixed, cv.MORPH_OPEN, kernel)
expanded = cv.dilate(clean, kernel, iterations=2)
distance = cv.distanceTransform(clean, cv.DIST_L2, 5)

_, seeds = cv.threshold(distance, 0.45 * distance.max(), 255, 0)
seeds = seeds.astype(np.uint8)
unknown = cv.subtract(expanded, seeds)

_, markers = cv.connectedComponents(seeds)
markers = markers + 1
markers[unknown == 255] = 0
boundaries = cv.watershed(bgr, markers) == -1

GrabCut for foreground extraction

Use GrabCut to isolate a foreground object in a cluttered image. Start with a rectangle that contains the entire object and leaves some background outside. Refine the mask if the first result misses part of the object.

Extract a foreground object from a rectangle
Python
height, width = bgr.shape[:2]
# Adjust this rectangle so it surrounds the whole object.
rect = (width // 8, height // 8, 3 * width // 4, 3 * height // 4)

classification = np.zeros((height, width), dtype=np.uint8)
background_model = np.zeros((1, 65), dtype=np.float64)
foreground_model = np.zeros((1, 65), dtype=np.float64)
cv.grabCut(
    bgr, classification, rect, background_model, foreground_model,
    5, cv.GC_INIT_WITH_RECT,
)

keep = (classification == cv.GC_FGD) | (classification == cv.GC_PR_FGD)
foreground = cv.bitwise_and(bgr, bgr, mask=keep.astype(np.uint8) * 255)

Where to go next

Continue with edge, shape, and feature detection, or revisit the OpenCV image manipulation guide. For applied examples, see face detection with OpenCV and object detection with YOLO.

For a pipeline that has to work on your own data, see our computer vision development services.

Frequently asked questions

When should I use a median blur instead of a Gaussian blur?

A median blur is usually the better choice for salt-and-pepper noise, because it ignores isolated outliers instead of averaging them in. A Gaussian blur suits general sensor noise. A bilateral filter preserves edges better than either, at a higher computational cost.

What does Otsu's binarization do?

Otsu's method chooses a global threshold automatically from the image histogram, selecting the value that best separates the pixels into two classes. It works best when the histogram has two clear peaks, such as a dark object on a light background.

What is the difference between global and adaptive thresholding?

Global thresholding applies one cutoff to the whole image. Adaptive thresholding computes a separate threshold for each neighborhood, which handles uneven lighting such as shadows across a scanned document.

When should I use watershed instead of GrabCut?

GrabCut extracts a foreground object from a rough rectangle or mask using iterative graph cuts. Watershed is better suited to separating multiple touching objects, such as coins or cells, once you have markers for sure foreground and sure background.