Thresholding is a foundational technique in computer vision and image processing used to segment objects from the background. It works by comparing each pixel value of a grayscale image against a specified threshold value. Based on this comparison, pixels are assigned new values, usually 0 (black) or 255 (white).In OpenCV with Python, the function cv2.threshold is used for thresholding.
In thresholding, for every pixel at position (x,y) with an intensity value f(x,y):
- If f(x,y) < T, set the pixel to 0 (black).
- If f(x,y) ≥ T, set it to the maximum value (typically 255, white).
- Here, T is the threshold value, and the process is usually performed on a grayscale version of the image
| Technique | Description |
|---|---|
| cv2.THRESH_BINARY | Above threshold -> 255, below -> 0. |
| cv2.THRESH_BINARY_INV | Above threshold -> 0, below -> 255 (inverse of binary). |
| cv2.THRESH_TRUNC | Above threshold -> set to threshold, below -> unchanged. |
| cv2.THRESH_TOZERO | Below threshold -> 0, above -> unchanged. |
| cv2.THRESH_TOZERO_INV | Above threshold -> 0, below -> unchanged (inverse of TOZERO). |
Step-by-Step Implementation
Let's implement the various types of simple thresholding techniques,
Step 1: Import libraries and Image Preparation
Sample image can be downloaded from here.
Let's import the required libraries and load our image on which we will perform the operations,
- cv2: Handles image reading, processing, and applies thresholding techniques.
- numpy: Supports efficient array operations, enabling fast image data handling.
- matplotlib.pyplot: Displays images and results in Colab notebooks.
import cv2
import numpy as np
import matplotlib.pyplot as plt
image = cv2.imread('input.png')
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
Step 2: Helper Function
Define the helper function which helps in displaying the images,
def show_image(img, title):
plt.imshow(img, cmap='gray')
plt.title(title)
plt.axis('off')
plt.show()
Step 3: Display the Original Image
show_image(gray_image, 'Original Grayscale Image')
Output: