基本阈值处理方法cv2.threshold
,函数原型如下:
ret, thresh = cv2.threshold(src, thresh, maxval, type)
参数说明:
-
src
:输入图像,通常是单通道的灰度图像。 -
thresh
:阈值。 -
maxval
:超过或低于阈值时赋予的新值。 - type:阈值类型,常见的有以下几种:
-
cv2.THRESH_BINARY
:如果像素值大于阈值,设置为maxval
;否则设置为 0。 -
cv2.THRESH_BINARY_INV
:如果像素值大于阈值,设置为 0;否则设置为maxval
。 -
cv2.THRESH_TRUNC
:如果像素值大于阈值,设置为阈值;否则保持不变。 -
cv2.THRESH_TOZERO
:如果像素值大于阈值,保持不变;否则设置为 0。 -
cv2.THRESH_TOZERO_INV
:如果像素值大于阈值,设置为 0;否则保持不变。
-
【示例】
import matplotlib.pyplot as plt
img = cv2.imread('cat.jpg',0)
# 阈值处理只接收一个通道的数据
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 = ['Orininal Image','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']
images =[img,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([])
print(ret)
运行结果: