Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Image Thresholding
Thresholding converts a grayscale image to a binary (black and white) image. Every pixel becomes either 0 (black) or 255 (white) based on whether it crosses a threshold value.
8 min•By Priygop Team•Updated 2026
Thresholding Methods
Thresholding Methods
import cv2
import numpy as np
image = cv2.imread("photo.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Simple threshold: pixels above 127 → 255 (white), below → 0 (black)
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# Inverse threshold: above → 0, below → 255
_, binary_inv = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)
# Otsu's method: automatically finds the best threshold value
_, otsu = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
print(f"Otsu's threshold value: automatically calculated")
# Adaptive threshold: different threshold for different image regions
# Better for images with uneven lighting
adaptive_mean = cv2.adaptiveThreshold(
gray, 255,
cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY,
blockSize=11, # Size of neighbourhood area
C=2 # Constant subtracted from mean
)
adaptive_gaussian = cv2.adaptiveThreshold(
gray, 255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY,
blockSize=11,
C=2
)
cv2.imwrite("binary.jpg", binary)
cv2.imwrite("otsu.jpg", otsu)
cv2.imwrite("adaptive.jpg", adaptive_gaussian)
print("Thresholding complete")Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment