图像阈值
就是将图像通道中的数据对比图像阈值,从而化为0,1二值化的操作
1. ret, dst = cv2.threshold(src, thresh, maxval, type)
参数说明, src表示输入的图片, thresh表示阈值, maxval表示最大值, type表示阈值的类型
2. type的类型
1. cv2.THRESH_BINARY 表示阈值的二值化操作,大于阈值使用maxval表示,小于阈值使用0表示
2. cv2.THRESH_BINARY_INV 表示阈值的二值化翻转操作,大于阈值的使用0表示,小于阈值的使用最大值表示
3. cv2.THRESH_TRUNC 表示进行截断操作,大于阈值的使用阈值表示,小于阈值的不变
4. cv2.THRESH_TOZERO 表示进行化零操作,大于阈值的不变,小于阈值的使用0表示
5. cv2.THRESH_TOZERO_INV 表示进行化零操作的翻转,大于阈值的使用0表示,小于阈值的不变
import cv2
import matplotlib.pyplot as plt
img = cv2.imread('./xing.jpg')
# 1.进行阈值二值化操作,大于阈值127的,使用255表示, 小于阈值127的,使用0表示 thresh-binary
ret, thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
# 2. 进行阈值二值化翻转操作, 大于阈值127的,使用0表示,小于阈值127的,使用255表示 thresh-binary-inv
ret, thresh2 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)
# 3. 进行截断阈值表示,大于阈值127的使用127表示,小于阈值127的不变 thresh-thunc
ret, thresh3 = cv2.threshold(img, 127, 255, cv2.THRESH_TRUNC)
# 4. 对阈值进行0值化表示,大于127的不变,小于127阈值的,用0表示 thresh-tozero
ret, thresh4 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO)
# 5. 对阈值进行0值化反向操作, 大于127的用0表示,小于127的不变 thresh-tozero-inv
ret, thresh5 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO_INV)
images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]
titles = ['ORIGINAL', 'BINARY', 'BINARY_INV', 'TRUNC', 'TOZERO', 'TOZERO_INV']
for i in range(6):
plt.subplot(2, 3, i+1)
plt.imshow(images[i])
plt.title(titles[i])
plt.show()