阈值化:给定一个数组和一个与之,然后根据数组中的每个元素的值,是高于还是低于阈值而进行一些操作。如果像素值大于阈值,则分配给它一个值(如白色的),否则它被分配给另一个值(如黑色)。
一、固定阈值化
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('gradient.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 xrange(6):
plt.subplot(2,3,i+1),plt.imshow(images[i],'gray')
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()
此为固定阈值的事例。具体效果如下:
ret,thresh1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
函数中四个参数分别是原图像、阈值、最大值、阈值类型
阈值类型一般分为五种:
cv2.THRESH_BINARY——大于阈值的部分像素值变为最大值,其他变为0
cv2.THRESH_BINARY_INV——大于阈值的部分变为0,其他部分变为最大值
cv2.THRESH_TRUNC——大于阈值的部分变为阈值,其余部分不变
cv2.THRESH_TOZERO——大于阈值的部分不变,其余部分变为0
cv2.THRESH_TOZERO_INV——大于阈值的部分变为0,其余部分不变
二、自适应阈值化
自适应阈值是根据图像上的每一个小区域计算与其对应的阈值,因此在同一幅图像上采用的是不同的阈值,从而能使我们在亮度 不同的情况下得到更好的结果。
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('dave.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 Thresholding', 'Adaptive Gaussian Thresholding']
images = [img, th1, th2, th3]
for i in xrange(4):
plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()
th2为算术平均法的自适应二值化
th3为高斯加权均值法自适应二值化
结果如下: