cv2.threshhold():当像素值高于阈值时,我们给这个像素赋予一个新值,否则给他赋予另一个值
这个函数的第一个参数就是原图像,一般是灰度图(貌似非灰度图也可以)。第二个参数就是用来对像素值进行分类的阈值。第三个参数就是当像素值高于阈值时应该被赋予的新像素值。
OpenCV提供了多种不同的阈值方法,这是第四个参数。这些方法包括:
cv2.THRESH_BINARY 超过阈值部分取maxval(最大值),否则取0
cv2.THRESH_BINARY_INV THRESH_BINARY的反转
cv2.THRESH_TRUNC 大于阈值部分设为阈值,否则不变
cv2.THRESH_TOZERO 大于阈值部分不改变,否则设为0
cv2.THRESH_TOZERO_INV THRESH_TOZERO的反
示例代码:
import cv2 from matplotlib import pyplot as plt img = cv2.imread('00.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 = ['Original Image','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV'] images = [img, thresh1, thresh2, thresh3, thresh4, thresh5] #pyplot的绘图方法 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()