图像阈值操作就是给图片像素设定一个阈值,超过这个值会怎样怎样,如下:
import cv2 import matplotlib.pyplot as plt img_org = cv2.imread('test.png') img = cv2.cvtColor(img_org, cv2.COLOR_BGR2GRAY) img_org = img_org[:, :, ::-1] ''' threshhold(图片, 阈值, 最大值, 类型) 五个常用的阈值操作 THRESH_BINARY 超过阈值的部分取最大值,否则就是0 THRESH_BINARY_INV 这个就是把THRESH_BINARY 的结果反过来 THRESH_TRUNC 大于阈值的部分设为阈值,否则不变 THRESH_TOZERO 大于阈值部分不变,否则设为0 THRESH_TOZERO_INV 就是上边的TOZERO的反转 ''' ret, thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) ret, thresh2 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV) ret, thresh3 = cv2.threshold(img, 127, 255, cv2.THRESH_TRUNC) ret, thresh4 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO) ret, thresh5 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO_INV) titles = ['original', 'binary', 'binary_inv', 'trunc', 'tozero', 'tozero_inv'] images = [img_org, thresh1, thresh2, thresh3, thresh4, thresh5] for i in range(6): plt.subplot(2, 3, i+1), plt.imshow(images[i], 'gray') plt.title(titles[i]) plt.xticks([]), plt.yticks([]) plt.show()