图像二值化
原理
- 图像灰度化
- 灰度化后图像根据阈值threshold进行二值化
注意
- 本文中方法一为自己实现
- 方法二利用opencv函数实现
代码
def bgr2bin(file=cartoon, threshold=128):
"""图像二值化"""
color = cv2.imread(file) # 读取图像
gray = cv2.cvtColor(color, cv2.COLOR_BGR2GRAY) # 灰度化
binarization = gray.copy()
binarization[gray < threshold] = 0 # 根据阈值进行二值化
binarization[gray >= threshold] = 255 # 根据阈值进行二值化
ret, binary = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY) # OpenCV自带函数实现
cv2.imshow('color', color)
cv2.imshow('binarization', binarization)
cv2.imshow('binary', binary)
cv2.waitKey()
cv2.destroyAllWindows()
if __name__ == '__main__':
bgr2bin()