函数作用 | 1.若为普通阈值分割,则设定一个阈值,当像素值高于阈值时,我们给这个像素赋予一个新的值(可能是白色),否则我们给它赋予另外一个新值(也许是黑色)。有两个返回值,第一个是得到的阈值值,第二个就是阈值化后的图像 2.若为OTSU阈值分割,要把阈值设为 0。 此时的函数 cv2.threshold()会自动寻找最优阈值,并将返回该阈值。 |
src | 输入图像(只能输入灰度图) |
thresh | 设定的阈值,若使用的OTSU大津阈值,则该值为0 |
maxval | 当像素值高于(或者小于)阀值时,应该被赋予新的像素值 |
type | 二值化操作的类型,共有五种类型(见下述) 若使用OTSU阈值处理,则在其后+cv2.THRESH_OTSU (例如:cv2.THRESH_BINARY+cv2.THRESH_OTSU) |
函数作用 | 以每个像素点作为中心取一定的区域,计算这个区域的阈值,决定这个像素点变0还是变255 |
src | 输入图像(只能输入灰度图) |
maxvalue | 当像素值高于(或者小于)阀值时,应该被赋予新的像素值 |
method | 自适应阈值算法,ADAPTIVE_THRESH_MEAN_C(阈值取自相邻区域的平均值)或ADAPTIVE_THRESH_GAUSSIAN_C(阈值取相邻区域的加权和,权重为一个高斯窗口) |
type | 只能选择THRESH_BINARY或者THRESH_BINARY_INV |
size | 领域大小,高宽一般取奇数 |
c | 每个邻域计算出的值需要再减去c得到阈值 |
其中,type包含以下5种类型:
5种类型图解如下:
cv2.threshold()
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('D:/4.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,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()
效果图
cv2.adaptiveThreshold()
import numpy as np
from matplotlib import pyplot as plt
import cv2
img = cv2.imread('D:/Images/Lena.jpg',0)
img = cv2.medianBlur(img,5)
ret , th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C , cv2.THRESH_BINARY,11,2 )
th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C , cv2.THRESH_BINARY,11,2)
titles = ['original image' , 'global thresholding (v=127)','Adaptive mean thres holding', 'adaptive gaussian thresholding']
images = [img,th1,th2,th3]
for i in range(4):
plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
plt.title(titles[i])
plt.show()
效果图