OpenCV + Python的阈值处理

阈值处理先经过灰度化,在进行二值化的操作,这里有五种方法介绍,具体代码如下:

import cv2
import matplotlib.pyplot as plt

img = cv2.imread("haizei.jpg")
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

ret, thresh1 = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)  #   自定义阈值【大于设定值为白色,小于为黑色】
ret, thresh2 = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV) #   与THRESH_BINARY方法相反
ret, thresh3 = cv2.threshold(gray, 127, 255, cv2.THRESH_TRUNC)  #   取截断值【大于设定值的值就修改为设定值,小于则不变】
ret, thresh4 = cv2.threshold(gray, 127, 255, cv2.THRESH_TOZERO) #   大于阈值部分不改变,否则设为0
ret, thresh5 = cv2.threshold(gray, 127, 255, cv2.THRESH_TOZERO_INV) #   大于阈值部分不改变,否则设为1

titles = ['Original 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([])
plt.show()
cv2.waitKey()
cv2.destroyAllWindows()

结果图:
OpenCV + Python的阈值处理_第1张图片

你可能感兴趣的:(毕设过程)