opencv-python threshold和adaptiveThreshold小记

opencv-python threshold和adaptiveThreshold

threshold用法
cv2.threshold第一个参数是源图像,它应该是灰度图像. 第二个参数是用于对像素值进行分类的阈值, 第三个参数是maxVal,它表示如果像素值大于(有时小于)阈值则要给出的值. OpenCV提供不同类型的阈值,它由函数的第四个参数决定. 第4个参数类型如下:

描述
cv2.THRESH_BINARY 如果 src(x,y)>threshold ,dst(x,y) = max_value; 否则,dst(x,y)=0
cv.THRESH_BINARY_INV 如果 src(x,y)>threshold,dst(x,y) = 0; 否则,dst(x,y) = max_value
cv.THRESH_TRUNC 如果 src(x,y)>threshold,dst(x,y) = max_value; 否则dst(x,y) = src(x,y)
cv.THRESH_TOZERO 如果src(x,y)>threshold,dst(x,y) = src(x,y) ; 否则 dst(x,y) = 0
cv.THRESH_TOZERO_INV 如果 src(x,y)>threshold,dst(x,y) = 0 ; 否则dst(x,y) = src(x,y)
# -*- coding:utf-8 -*- 
import cv2
from matplotlib import pyplot as plt
#读取灰度图
img = cv2.imread('test.png',0)
#或者使用
# img = cv2.imread('test.png')
# img=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
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]
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()

测试图片
opencv-python threshold和adaptiveThreshold小记_第1张图片

效果图
opencv-python threshold和adaptiveThreshold小记_第2张图片

你可能感兴趣的:(opencv,opencv,threshold,阈值处理,自适应阈值处理)