Image thresholding helps turn a color or gray image into a simple black and white image. This makes it easier to find shapes or objects.
Image thresholding (binary, adaptive, Otsu) in Computer Vision
import cv2 # Binary thresholding _, binary_img = cv2.threshold(src, thresh, maxval, cv2.THRESH_BINARY) # Adaptive thresholding adaptive_img = cv2.adaptiveThreshold(src, maxval, adaptiveMethod, thresholdType, blockSize, C) # Otsu's thresholding _, otsu_img = cv2.threshold(src, 0, maxval, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
src is the input grayscale image.
For adaptive thresholding, blockSize is the size of the area to calculate the threshold, and C is a constant subtracted from the mean or weighted mean.
_, binary_img = cv2.threshold(gray_img, 127, 255, cv2.THRESH_BINARY)
adaptive_img = cv2.adaptiveThreshold(gray_img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
_, otsu_img = cv2.threshold(gray_img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
This code creates a simple image with a bright square on a dark background. It applies three types of thresholding and counts how many pixels are white after each method.
import cv2 import numpy as np # Create a simple grayscale image with a dark and bright area img = np.zeros((100, 100), dtype=np.uint8) img[25:75, 25:75] = 150 # Bright square in the middle # Binary thresholding _, binary_img = cv2.threshold(img, 100, 255, cv2.THRESH_BINARY) # Adaptive thresholding adaptive_img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2) # Otsu's thresholding _, otsu_img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # Print threshold values and sum of white pixels to compare print("Binary threshold sum:", np.sum(binary_img == 255)) print("Adaptive threshold sum:", np.sum(adaptive_img == 255)) print("Otsu threshold sum:", np.sum(otsu_img == 255))
Binary thresholding uses one fixed value for the whole image.
Adaptive thresholding changes the threshold for different parts of the image, useful for uneven lighting.
Otsu's method finds the best threshold automatically by looking at the image histogram.
Image thresholding turns images into black and white for easier analysis.
Binary thresholding uses a fixed cutoff value.
Adaptive and Otsu methods help when lighting or colors vary across the image.