DEV Community

Esther
Esther

Posted on • Edited on

Binary Images & Image Thresholding

Thresholding

Thresholding is a simple yet effective technique used in image processing to convert a grayscale image into a binary image. The core idea is to segment the image into two parts (usually 0 - black and 255 - white) based on a specific threshold value. Think of the threshold value as a certain number that must be exceeded (or not) for a certain result.

Thresholding involves setting a threshold value that separates the pixel values of the image into two distinct groups:

  • Pixels above the threshold: These pixels are usually set to the maximum value (often 255 for white in binary images).
  • Pixels below or equal to the threshold: These pixels are usually set to the minimum value (often 0 for black in binary images).

Types of Thresholding

1. Global Thresholding: A single global threshold value is applied to the entire image.

Example: Setting all pixel values above 165 to 255 (white) and those below or equal to 165 to 0 (black).

cv2.threshold(img, 165, 255, cv2.THRESH_BINARY)

An image with the following values:
[[103 105 105]
 [211 210 210]
 [212 211 211]
 [139 138 137]]

Would become:
[[0 0 0]
 [255 255 255]
 [255 255 255]
 [0 0 0]]
Enter fullscreen mode Exit fullscreen mode

2. Adaptive Thresholding: The threshold value is determined for smaller regions of the image, allowing for different threshold values in different parts of the image.

Example: Setting all pixel values above the calculated mean to 255 (white) and those below or equal to 165 to 0 (black).

cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 3, 7)
Enter fullscreen mode Exit fullscreen mode

Read more about how Adaptive Thresholding is calculated.

Adaptive thresholding is useful for images with varying lighting conditions. For each pixel, the best possible value is used which results in a clearer image.

Binary Image

A binary image is a type of image that has only two possible pixel values: 0 and 255. These values represent black and white, respectively. Binary images are used to simplify the analysis of images by reducing the complexity of the data. We use thresholding algorithms to achieve binary images.

Significance of Binary Images

  • Simplification: It reduces the complexity of an image by converting it to two colors, making it easier to analyze.

  • Segmentation: In application of object detection, it can help in isolating objects from the background.

  • Feature Extraction: It is useful for identifying and extracting specific features from an image, such as shapes or edges.

Top comments (0)