http://docs.opencv.org/master/d7/d4d/tutorial_py_thresholding.html
(一)简单阈值
import cv2
import numpy as np
from matplotlib import pyplot as plt
img=cv2.imread('1.bmp')
# 转灰度图
GrayImage=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#
ret,thresh1=cv2.threshold(GrayImage,127,255,cv2.THRESH_BINARY)
ret,thresh2=cv2.threshold(GrayImage,127,255,cv2.THRESH_BINARY_INV)
ret,thresh3=cv2.threshold(GrayImage,127,255,cv2.THRESH_TRUNC)
ret,thresh4=cv2.threshold(GrayImage,127,255,cv2.THRESH_TOZERO)
ret,thresh5=cv2.threshold(GrayImage,127,255,cv2.THRESH_TOZERO_INV)
titles = ['Gray Image','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']
images = [GrayImage, 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()
(二)自适应阈值:
自适应的二值化处理不同于固定阈值的处理,每个像素的阈值依赖于其邻近的像素灰度,为了得到(x,y)点的阈值T(x,y),我们需要进行以下处理。
在此像素周边选取一个bxb的区域,其中了是用户指定的。
计算此bxb区域的加权平均值。OpenCV提供了两种方法计算此加权均值,一种是算术平均法,另一种是高斯加权平均法,后者要计算均值时距离区域中心越近权重越大。我们将得到的加权均值计为WA(x,y)
将上述加权均值与一固定参数相减得到阈值T(x,y),此固定参数设为param1,则(x,y)点的阈值可以用下式进行计算:
T(x,y)=WA(x,y)-param1
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('sudoku.png',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()
# cv2.adaptiveThreshold(src, maxValue, adaptiveMethod, thresholdType, blockSize, C[, dst])
其中:
# src 为输入图像;
# maxval 为输出图像的最大值;
# adaptiveMethod 设置为cv2.ADAPTIVE_THRESH_MEAN_C表示利用算术均值法,设置为cv2.ADAPTIVE_THRESH_GAUSSIAN_C表示用高斯权重均值法;
# thresholdType: 阈值的类型;
# blockSize: b的值;
# C 为从均值中减去的常数,用于得到阈值;
# dst 为目标图像。
(三)Otsu’s二值化