一、cv2.threshold() 的作用将一张灰度图(单通道) 进行 二值化
1、函数详解,
def threshold(src, thresh, maxval, type, dst=None): # real signature unknown; restored from __doc__ """(1)将灰度图变成二值化图像,也具有一定的去噪功能,去掉比较大或比较小的像素值。 threshold(src, thresh, maxval, type[, dst]) -> retval, dst #返回阈值和二值化后的图片 . @brief Applies a fixed-level threshold to each array element.(2)用固定阈值处理每个矩阵元素 . The function applies fixed-level thresholding to a multiple-channel array. The function is typically . used to get a bi-level (binary) image out of a grayscale image ( #compare could be also used for . this purpose) or for removing a noise, that is, filtering out pixels with too small or too large . values. There are several types of thresholding supported by the function. They are determined by . type parameter.(3)有几种阈值可通过参数控制 . . Also, the special values #THRESH_OTSU or #THRESH_TRIANGLE may be combined with one of the . above values. In these cases, the function determines the optimal threshold value using the Otsu's . or Triangle algorithm and uses it instead of the specified thresh. . . @note Currently, (4)the Otsu's and Triangle methods are implemented only for 8-bit single-channel images. . . @param src input array (multiple-channel, 8-bit or 32-bit floating point). . @param (5)dst output array of the same size and type and the same number of channels as src. . @param thresh threshold value. . @param maxval(6) maximum value to use with the #THRESH_BINARY and #THRESH_BINARY_INV thresholding . types. . @param type(7) thresholding type (see #ThresholdTypes). . @return (8)the computed threshold value if Otsu's or Triangle methods used. . . @sa adaptiveThreshold, findContours, compare, min, max """ pass
(1)retval, dst = cv2.threshold( src , thresh, maxval, type)
阈值, 二值化图像 = cv2.threshold(输入灰度图, 阈值,最大值, 阈值类型)
阈值类型有8种:
原图:
5种固定阈值
1)THRESH_BINARY 将大于阈值的像素值设为maxval,将小于阈值的像素值设为0
2)THRESH_BINARY_INV,与THRESH_BINARY相反,将大于阈值的像素值设为0,将小于阈值的像素值设为maxval
3)THRESH_TRUNC,将大于阈值的像素值设为maxval,将小于阈值的像素值保留
4)THRESH_TOZERO,将大于阈值的像素值保留,将小于阈值的像素值设为0
5)THRESH_TOZERO_INV,与THRESH_TOZERO相反,将大于阈值的像素值设为0,将小于阈值的像素值保留
6)THRESH_OTSU:对于双峰图片,可采用该阈值自动寻找双峰之间的波谷,进行二分类划分。第一个返回值就是找到的阈值
在使用函数时需要把thresh=0设置为0. retval, dst = cv2.threshold(gray, thresh=0, 255, cv2.THRESH_OTSU)
7)THRESH_TRIANGLE,三角形算法,(有丢失)适用于单个波峰
8)THRESH_MASK
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('ent.png',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,0,255,cv2.THRESH_OTSU)
titles = ['Original', 'BINARY', 'BINARY_INV', 'TRUNC', 'TOZERO', 'THRESH_OTSU']
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()