图像阈值
![](https://i-blog.csdnimg.cn/blog_migrate/b8a09de0b426b6b1dc838a3712265f83.png)
import cv2
import matplotlib.pyplot as plt
import numpy as np
cat=cv2.imread('D:/BaiduNetdiskDownload/opencv/cat.jpg')
cat_GRAY=cv2.imread('D:/BaiduNetdiskDownload/opencv/cat.jpg',cv2.IMREAD_GRAYSCALE)
cat = cv2.cvtColor(cat, cv2.COLOR_BGR2RGB)
# cv2.threshold()有两个返回值,第一个retVal(得到的阈值值(在后面一个方法中会用到)),第二个就是阈值化后的图像
ret, img1 = cv2.threshold(cat_GRAY,127,255,cv2.THRESH_BINARY)
ret, img2 = cv2.threshold(cat_GRAY,127,255,cv2.THRESH_BINARY_INV)
ret, img3 = cv2.threshold(cat_GRAY,127,255,cv2.THRESH_TRUNC)
ret, img4 = cv2.threshold(cat_GRAY,127,255,cv2.THRESH_TOZERO)
ret, img5 = cv2.threshold(cat_GRAY,127,255,cv2.THRESH_TOZERO_INV)
titles=['ORIGIN','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']
images=[cat,img1,img2,img3,img4,img5]
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()
运行效果
![](https://i-blog.csdnimg.cn/blog_migrate/cebf106ba989aa2aa2cbd2877d59a2cd.png)