Threshold-Based Segmentation
Threshold-based segmentation converts a grayscale image into a binary mask by comparing each pixel to a threshold value. It is the simplest and fastest segmentation method.
10 min•By Priygop Team•Updated 2026
Segmenting with Thresholds
Segmenting with Thresholds
import cv2
import numpy as np
image = cv2.imread("photo.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# Simple threshold: fixed value
_, simple = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# Otsu's threshold: auto-detect best value
threshold_val, otsu = cv2.threshold(
blurred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU
)
print(f"Otsu threshold: {threshold_val:.0f}")
# Adaptive threshold: handles uneven lighting
adaptive = cv2.adaptiveThreshold(
blurred, 255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY,
blockSize=11, C=2
)
# Use mask to extract segmented region
segmented = cv2.bitwise_and(image, image, mask=otsu)
# Count segmented pixels
fg_pixels = cv2.countNonZero(otsu)
total_pixels = otsu.shape[0] * otsu.shape[1]
print(f"Foreground: {fg_pixels:,} pixels ({fg_pixels/total_pixels*100:.1f}%)")
cv2.imwrite("threshold_segment.jpg", segmented)
cv2.imwrite("threshold_mask.jpg", otsu)Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment