目錄
前言
在灰度圖像的處理中,經(jīng)常會用到二值化處理,二值化處理中最常用是就是全局閥值和局部閥值。
我們將對下面這一幅照片進(jìn)行處理。

TIM圖片20190216230535.png
全局閥值
# -*- coding=GBK -*-
import cv2 as cv
image = cv.imread("2.jpg")
#全局閾值
gray = cv.cvtColor(image, cv.COLOR_RGB2GRAY) #把輸入圖像灰度化
#直接閾值化是對輸入的單通道矩陣逐像素進(jìn)行閾值分割。
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_TRIANGLE)
print("threshold value %s"%ret)
cv.namedWindow("binary0", cv.WINDOW_NORMAL)
cv.imshow("normal", gray)
cv.imshow("binary0", binary)
cv.waitKey(0)
cv.destroyAllWindows()
全局閥值二值化圖像

TIM圖片20190216230528.png
函數(shù)說明
函數(shù)說明:
第一個參數(shù)表示輸入圖像,必須為單通道灰度圖。
第二個參數(shù)表示輸出的邊緣圖像,為單通道黑白圖。
第三個參數(shù)表示閾值
第四個參數(shù)表示最大值。
第五個參數(shù)表示運算方法。
在OpenCV的imgproc\types_c.h中可以找到運算方法的定義。
/* Threshold types */
CV_THRESH_BINARY =0, /* value = value > threshold ? max_value : 0 */
CV_THRESH_BINARY_INV =1, /* value = value > threshold ? 0 : max_value */
CV_THRESH_TRUNC =2, /* value = value > threshold ? threshold : value */
CV_THRESH_TOZERO =3, /* value = value > threshold ? value : 0 */
CV_THRESH_TOZERO_INV =4, /* value = value > threshold ? 0 : value */
CV_THRESH_MASK =7,
CV_THRESH_OTSU =8 /* use Otsu algorithm to choose the optimal threshold value; combine the flag with one of the above CV_THRESH_* values */
注釋已經(jīng)寫的很清楚了,因此不再用中文來表達(dá)了。
局部閥值
import cv2 as cv
image = cv.imread("2.jpg")
#全局閾值
gray = cv.cvtColor(image, cv.COLOR_RGB2GRAY) #把輸入圖像灰度化
#直接閾值化是對輸入的單通道矩陣逐像素進(jìn)行閾值分割。
binary = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C,cv.THRESH_BINARY, 25, 10)
cv.namedWindow("binary0", cv.WINDOW_NORMAL)
cv.imshow("normal", gray)
cv.imshow("binary0", binary)
cv.waitKey(0)
cv.destroyAllWindows()
局部閥值二值化圖像

wed.png
自適應(yīng)閾值化能夠根據(jù)圖像不同區(qū)域亮度分布的,改變閾值,具體調(diào)用方法如下:
void cv::adaptiveThreshold(
cv::InputArray src, // 輸入圖像
cv::OutputArray dst, // 輸出圖像
double maxValue, // 向上最大值
int adaptiveMethod, // 自適應(yīng)方法,平均或高斯
int thresholdType // 閾值化類型
int blockSize, // 塊大小
double C // 常量
);
cv::adaptiveThreshold()支持兩種自適應(yīng)方法,即cv::ADAPTIVE_THRESH_MEAN_C(平均)和cv::ADAPTIVE_THRESH_GAUSSIAN_C(高斯)。
在兩種情況下,自適應(yīng)閾值T(x, y)。通過計算每個像素周圍bxb大小像素塊的加權(quán)均值并減去常量C得到。其中,b由blockSize給出,大小必須為奇數(shù);如果使用平均的方法,則所有像素周圍的權(quán)值相同;如果使用高斯的方法,則(x,y)周圍的像素的權(quán)值則根據(jù)其到中心點的距離通過高斯方程得到。