1 import cv2
2 from matplotlib import pyplot as plt
3
4 img = cv2.imread('default.png')
5 img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
6 cv2.imshow('test', img_gray)
7
8 '''
9 ret, thresh = cv2.threshold(src, thresh, maxval, type)
10 src:输入图,只能输入单通道图像,一般为灰度图
11 thresh:输出图
12 thresh:阈值
13 maxval:当像素值超过了阈值,所赋予的值
14 type:二值化操作类型,即如何处理阈值
15 '''
16 ret1, thresh1 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY) # 超过阈值部分取maxval,否则取0
17 ret2, thresh2 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY_INV) # THRESH_BINARY的反转
18 ret3, thresh3 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TRUNC) # 大于阈值部分设为阈值,否则不变
19 ret4, thresh4 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO) # 大于阈值部分不改变,否则设为0
20 ret5, thresh5 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO_INV) # THRESH_TOZERO的反转
21 titles = ['Original Image', 'BINARY', 'BINARY_INV', 'TRUNC', 'TOZERO', 'TOZERO_INV']
22 images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]
23 for i in range(6):
24 plt.subplot(2, 3, i+1)
25 plt.imshow(images[i], 'gray')
26 plt.title(titles[i])
27 plt.xticks([]), plt.yticks([])
28 plt.show()
29 cv2.waitKey(0)
30 cv2.destroyAllWindows()