1 基於閾值
1.1 灰度閾值化
灰度閾值化,是最簡單,速度最快的圖像分割方法,廣泛用於硬件圖像處理領域 (例如,基於 FPGA 的實時圖像處理等)。
設輸入圖像 ff,輸出圖像 gg,則閾值化公式為:
g(i,j)={10當 f(i, j) ≥ T 時當 f(i, j) < T 時g(i,j)={1當 f(i, j) ≥ T 時0當 f(i, j) < T 時
即,遍歷圖像中所有像素,當像素值 f(i,j)≥Tf(i,j)≥T 時,分割后的圖像元素 g(i,j)g(i,j) 是物體像素,否則為背景像素。
當各物體不接觸,且 物體和背景的灰度值差別比較明顯 時,灰度閾值化是非常合適的分割方法。
1.2 固定閾值化
固定閾值化函數為 threshold,如下:
1 double cv::threshold ( 2 InputArray src, // 輸入圖像 (單通道,8位或32位浮點型)
3 OutputArray dst, // 輸出圖像 (大小和類型,都同輸入)
4 double thresh, // 閾值
5 double maxval, // 最大灰度值(使用 THRESH_BINARY 和 THRESH_BINARY_INV類型時)
6 int type // 閾值化類型(THRESH_BINARY, THRESH_BINARY_INV; THRESH_TRUNC; THRESH_TOZERO, THRESH_TOZERO_INV)
7 )
1.3 自適應閾值化
整幅圖像使用同一個閾值做二值化,對於一些情況並不適用,尤其是當圖像中的不同區域,照明條件各不相同時。這種情況下,就需要自適應閾值算法,該算法可根據像素所在的區域,來確定一個適合的閾值。因此,對於一幅圖中光照不同的區域,可取各自不同的閾值做二值化。
OpenCV 中,自適應閾值化函數為 adaptiveThreshold(),如下:
1 void cv::adaptiveThreshold ( 2 InputArray src, // 3 OutputArray dst, // 4 double maxValue, // 5 int adaptiveMethod, // 自適應閾值算法,目前有 ADAPTIVE_THRESH_MEAN_C 和 ADAPTIVE_THRESH_GAUSSIAN_C 兩種
6 int thresholdType, // 閾值化類型,同 threshold() 中的 type
7 int blockSize, // 鄰域大小
8 double C // 9 )
1.4 示例
1)閾值化類型和閾值可選的代碼示例,摘自 OpenCV 例程,略作修改
1 #include "opencv2/imgproc.hpp"
2 #include "opencv2/imgcodecs.hpp"
3 #include "opencv2/highgui.hpp"
4
5 using namespace cv; 6
7 int threshold_value = 0; 8 int threshold_type = 3; 9 int const max_value = 255; 10 int const max_type = 4; 11 int const max_BINARY_value = 255; 12
13 Mat src, src_gray, dst; 14 const char* window_name = "Threshold Demo"; 15
16 const char* trackbar_type = "Type: \n 0: Binary \n 1: Binary Inverted \n 2: Truncate \n 3: To Zero \n 4: To Zero Inverted"; 17 const char* trackbar_value = "Value"; 18
19 void Threshold_Demo(int, void*); 20
21 int main( int, char** argv ) 22 { 23 // 讀圖
24 src = imread("Musikhaus.jpg",IMREAD_COLOR); 25 if( src.empty() ) 26 return -1; 27
28 // 轉化為灰度圖
29 cvtColor( src, src_gray, COLOR_BGR2GRAY ); 30 // 顯示窗口
31 namedWindow( window_name, WINDOW_AUTOSIZE ); 32 // 滑動條 - 閾值化類型
33 createTrackbar( trackbar_type, window_name, &threshold_type,max_type,Threshold_Demo); 34 // 滑動條 - 閾值
35 createTrackbar( trackbar_value,window_name, &threshold_value,max_value,Threshold_Demo); 36
37 Threshold_Demo(0, 0); 38
39 waitKey(0); 40 } 41
42 void Threshold_Demo(int, void*) 43 { 44 /* 0: Binary 45 1: Binary Inverted 46 2: Threshold Truncated 47 3: Threshold to Zero 48 4: Threshold to Zero Inverted 49 */
50 threshold(src_gray, dst, threshold_value, max_BINARY_value, threshold_type); 51 imshow(window_name, dst); 52 }
2)全局閾值和自適應閾值的比較,代碼如下:
1 #include <opencv2/core.hpp>
2 #include <opencv2/imgproc.hpp>
3 #include <opencv2/highgui.hpp>
4
5 using namespace cv; 6
7 int main() 8 { 9 // read an image
10 Mat img = imread("sudoku.png"); 11 cvtColor(img,img,COLOR_BGR2GRAY); 12
13 // adaptive
14 Mat dst1, dst2, dst3; 15 threshold(img, dst1, 100, 255, THRESH_BINARY); 16 adaptiveThreshold(img, dst2, 255,ADAPTIVE_THRESH_MEAN_C ,THRESH_BINARY,11,2); 17 adaptiveThreshold(img, dst3, 255,ADAPTIVE_THRESH_GAUSSIAN_C ,THRESH_BINARY,11,2); 18
19 // show images
20 imshow("img", img); 21 imshow("threshold", dst1); 22 imshow("mean_c", dst2); 23 imshow("gauss_c", dst3); 24
25 waitKey(0); 26 }
對比顯示的結果為:
2 基於邊緣
前一篇 <OpenCV 之 邊緣檢測> 中,介紹了三種常用的邊緣檢測算子: Sobel, Laplace 和 Canny 算子。
實際上,邊緣檢測的結果是一個個的點,並不能作為圖像分割的結果,必須采用進一步的處理,將邊緣點沿着圖像的邊界連接起來,形成邊緣鏈。
2.1 輪廓函數
OpenCV 中,可在圖像的邊緣檢測之后,使用 findContours 尋找到輪廓,該函數參數如下:
image 一般為二值化圖像,可由 compare, inRange, threshold , adaptiveThreshold, Canny 等函數來獲得;
hierarchy 為可選的參數,如果不選擇該參數,則可得到 findContours 函數的第二種形式;
1 // 形式一
2 void findContours ( 3 InputOutputArray image, // 輸入圖像
4 OutputArrayOfArrays contours, // 檢測到的輪廓
5 OutputArray hierarchy, // 可選的輸出向量
6 int mode, // 輪廓獲取模式 (RETR_EXTERNAL, RETR_LIST, RETR_CCOMP,RETR_TREE, RETR_FLOODFILL)
7 int method, // 輪廓近似算法 (CHAIN_APPROX_NONE, CHAIN_APPROX_SIMPLE, CHAIN_APPROX_TC89_L1, CHAIN_APPROX_TC89_KCOS)
8 Point offset = Point() // 輪廓偏移量
9 ) 10 // 形式二
11 void findContours ( 12 InputOutputArray image, 13 OutputArrayOfArrays contours, 14 int mode, 15 int method, 16 Point offset = Point() 17 )
drawContours 函數參數如下:
1 void drawContours ( 2 InputOutputArray image, // 目標圖像
3 InputArrayOfArrays contours, // 所有的輸入輪廓
4 int contourIdx, // 5 const Scalar & color, // 輪廓顏色
6 int thickness = 1, // 輪廓線厚度
7 int lineType = LINE_8, // 8 InputArray hierarchy = noArray(), // 9 int maxLevel = INT_MAX, // 10 Point offset = Point() //
11 )
2.2 例程
代碼摘自 OpenCV 例程,略有修改
1 #include "opencv2/imgcodecs.hpp"
2 #include "opencv2/highgui.hpp"
3 #include "opencv2/imgproc.hpp"
4
5 using namespace cv; 6 using namespace std; 7
8 Mat src,src_gray; 9 int thresh = 100; 10 int max_thresh = 255; 11 RNG rng(12345); 12
13 void thresh_callback(int, void* ); 14
15 int main( int, char** argv ) 16 { 17 // 讀圖
18 src = imread("Pillnitz.jpg", IMREAD_COLOR); 19 if (src.empty()) 20 return -1; 21
22 // 轉化為灰度圖
23 cvtColor(src, src_gray, COLOR_BGR2GRAY ); 24 blur(src_gray, src_gray, Size(3,3) ); 25
26 // 顯示
27 namedWindow("Source", WINDOW_AUTOSIZE ); 28 imshow( "Source", src ); 29
30 // 滑動條
31 createTrackbar("Canny thresh:", "Source", &thresh, max_thresh, thresh_callback ); 32
33 // 回調函數
34 thresh_callback( 0, 0 ); 35
36 waitKey(0); 37 } 38
39 // 回調函數
40 void thresh_callback(int, void* ) 41 { 42 Mat canny_output; 43 vector<vector<Point> > contours; 44 vector<Vec4i> hierarchy; 45
46 // canny 邊緣檢測
47 Canny(src_gray, canny_output, thresh, thresh*2, 3); 48
49 // 尋找輪廓
50 findContours( canny_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0) ); 51
52 Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3); 53
54 // 畫出輪廓
55 for( size_t i = 0; i< contours.size(); i++ ) { 56 Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) ); 57 drawContours( drawing, contours, (int)i, color, 2, 8, hierarchy, 0, Point() ); 58 } 59
60 namedWindow( "Contours", WINDOW_AUTOSIZE ); 61 imshow( "Contours", drawing ); 62 }
以 Dresden 的 Schloss Pillnitz 為源圖,輸出如下: