图像二值化( Image Binarization)就是将图像上的像素点的灰度值设置为0或255,也就是将整个图像呈现出明显的黑白效果的过程。
import cv2
img = cv2.imread('img/lena.jpg')
# 转为灰度图
new_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
height, width = new_img.shape[0:2]
# 设置阈值
thresh = 60
# 遍历每一个像素点
for row in range(height):
for col in range(width):
# 获取到灰度值
gray = new_img[row, col]
# 如果灰度值高于阈值 就等于255最大值
if gray > thresh:
new_img[row, col] = 255
# 如果小于阈值,就直接改为0
elif gray < thresh:
new_img[row, col] = 0
cv2.imshow('img', new_img)
cv2.waitKey()
但是实际上二值处理产生的结果上的提高并不如图像分割和透视带来的提高强