A binary image refers to an image with only two colors, black and white, where 0 represents black and 1 represents white (ie, 255).
The general process of image binarization is to first convert the input image into a grayscale image, and then convert it into a binary image through the binarization method. This process is essentially a binary segmentation of the data, and finding a reasonable segmentation threshold is crucial.
Example
import cv2 import numpy as np image = cv2.imread('lenna.png') cv2.imshow("original image", image) h, w = image.shape[:2] # 转换为灰度图像gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) h, w = gray.shape # 取均值作为阈值T = cv2.mean(gray)[0] print("T: {}".format(T)) binary = np.zeros((h, w), dtype=np.uint8) for row in range(h): for col in range(w): pv = gray[row, col] if pv > T: binary[row, col] = 255 else: binary[row, col] = 0 cv2.imshow("binary", binary) cv2.waitKey(0) cv2.destroyAllWindows()
This article is reprinted from https://xugaoxiang.com/2022/07/16/opencv-binaryzation/
This site is for inclusion only, and the copyright belongs to the original author.