环境:Python3.8 和 OpenCV
内容:图像的灰度化和二值化
import cv2 as cv
import matplotlib.pyplot as plt
# 封装图片显示函数
def image_show(image):
if image.ndim == 2:
plt.imshow(image, cmap='gray')
else:
image = cv.cvtColor(image, cv.COLOR_BGR2RGB)
plt.imshow(image)
plt.show()
if __name__ == '__main__':
# 图像的读取与显示
img = cv.imread('lenna.png')
image_show(img)
# 图像的灰度化
img_gray = cv.cvtColor(img, cv.COLOR_RGB2GRAY)
image_show(img_gray)
# 图像的二值化
threshold = 70 # 二值化分割阈值
max_value = 255 # 图像中的最大值
[_, img_bin] = cv.threshold(img_gray, threshold, max_value , cv.THRESH_BINARY)
image_show(img_bin)