OpenCV 之 圖像分割 (一)


1  基於閾值

1.1  灰度閾值化

  灰度閾值化,是最簡單,速度最快的圖像分割方法,廣泛用於硬件圖像處理領域 (例如,基於 FPGA 的實時圖像處理等)。

  設輸入圖像 $f$,輸出圖像 $g$,則閾值化公式為:

  $\quad g(i, j) = \begin{cases} 1 & \text{當 f(i, j) ≥ T 時} \\0 & \text{當 f(i, j) < T 時} \\ \end{cases} $

  即,遍歷圖像中所有像素,當像素值 $f (i, j) ≥ T$ 時,分割后的圖像元素 $g (i, j)$ 是物體像素,否則為背景像素。

  當各物體不接觸,且 物體和背景的灰度值差別比較明顯 時,灰度閾值化是非常合適的分割方法。

 

1.2  固定閾值化

  固定閾值化函數為 threshold,如下:

double cv::threshold (     
    InputArray  src,   // 輸入圖像 (單通道,8位或32位浮點型)   
    OutputArray  dst,  // 輸出圖像 (大小和類型,都同輸入) 
    double    thresh, // 閾值
    double    maxval, // 最大灰度值(使用 THRESH_BINARY 和 THRESH_BINARY_INV類型時) 
    int      type   // 閾值化類型(THRESH_BINARY, THRESH_BINARY_INV; THRESH_TRUNC; THRESH_TOZERO, THRESH_TOZERO_INV) 
)

  1) THRESH_BINARY

$\qquad dst(x, y) = \begin{cases} maxval & \text{if src(x, y) > thresh} \\0 & \text{otherwise} \\ \end{cases} $

  2) THRESH_TRUNC

$\qquad dst(x, y) = \begin{cases} threshold & \text{if src(x, y) > thresh} \\src(x, y) & \text{otherwise} \\ \end{cases} $

  3) THRESH_TOZERO 

 $\qquad dst(x, y) = \begin{cases} src(x, y) & \text{if src(x, y) > thresh} \\0 & \text{otherwise} \\ \end{cases} $

1.3  自適應閾值化

   整幅圖像使用同一個閾值做二值化,對於一些情況並不適用,尤其是當圖像中的不同區域,照明條件各不相同時。這種情況下,就需要自適應閾值算法,該算法可根據像素所在的區域,來確定一個適合的閾值。因此,對於一幅圖中光照不同的區域,可取各自不同的閾值做二值化。

    OpenCV 中,自適應閾值化函數為 adaptiveThreshold(),如下:

void cv::adaptiveThreshold ( InputArray src, //     OutputArray     dst,       //     double   maxValue,         //     int      adaptiveMethod,   // 自適應閾值算法,目前有 ADAPTIVE_THRESH_MEAN_C 和 ADAPTIVE_THRESH_GAUSSIAN_C 兩種     int      thresholdType,    // 閾值化類型,同 threshold() 中的 type     int      blockSize,        // 鄰域大小     double   C                 // )     

 1.4  示例

  1)閾值化類型和閾值可選的代碼示例,摘自 OpenCV 例程,略作修改

#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"

using namespace cv;

int threshold_value = 0;
int threshold_type = 3;
int const max_value = 255;
int const max_type = 4;
int const max_BINARY_value = 255;

Mat src, src_gray, dst;
const char* window_name = "Threshold Demo";

const char* trackbar_type = "Type: \n 0: Binary \n 1: Binary Inverted \n 2: Truncate \n 3: To Zero \n 4: To Zero Inverted";
const char* trackbar_value = "Value";

void Threshold_Demo(int, void*);

int main( int, char** argv )
{
  // 讀圖
  src = imread("Musikhaus.jpg",IMREAD_COLOR);
  if( src.empty() )
      return -1;

  // 轉化為灰度圖
  cvtColor( src, src_gray, COLOR_BGR2GRAY );
  // 顯示窗口
  namedWindow( window_name, WINDOW_AUTOSIZE );
  // 滑動條 - 閾值化類型
  createTrackbar( trackbar_type, window_name, &threshold_type,max_type,Threshold_Demo);
  // 滑動條 - 閾值
  createTrackbar( trackbar_value,window_name, &threshold_value,max_value,Threshold_Demo);

  Threshold_Demo(0, 0);

  waitKey(0);
}

void Threshold_Demo(int, void*)
{
    /* 0: Binary
    1: Binary Inverted
    2: Threshold Truncated
    3: Threshold to Zero
    4: Threshold to Zero Inverted
    */
    threshold(src_gray, dst, threshold_value, max_BINARY_value, threshold_type);
    imshow(window_name, dst);
}
View Code

  2)全局閾值和自適應閾值的比較,代碼如下:

#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>

using namespace cv;

int main()
{
    // read an image
    Mat img = imread("sudoku.png");
    cvtColor(img,img,COLOR_BGR2GRAY);

    // adaptive
    Mat dst1, dst2, dst3;
    threshold(img, dst1, 100, 255, THRESH_BINARY);
    adaptiveThreshold(img, dst2, 255,ADAPTIVE_THRESH_MEAN_C ,THRESH_BINARY,11,2);
    adaptiveThreshold(img, dst3, 255,ADAPTIVE_THRESH_GAUSSIAN_C ,THRESH_BINARY,11,2);

    // show images
    imshow("img", img);
    imshow("threshold", dst1);
    imshow("mean_c", dst2);
    imshow("gauss_c", dst3);

    waitKey(0);
}

   對比顯示的結果為:

   

 

2  基於邊緣

  前一篇 <OpenCV 之 邊緣檢測> 中,介紹了三種常用的邊緣檢測算子: Sobel, Laplace 和 Canny 算子。

  實際上,邊緣檢測的結果是一個個的點,並不能作為圖像分割的結果,必須采用進一步的處理,將邊緣點沿着圖像的邊界連接起來,形成邊緣鏈。

2.1  輪廓函數

  OpenCV 中,可在圖像的邊緣檢測之后,使用 findContours 尋找到輪廓,該函數參數如下:

  image 一般為二值化圖像,可由 compare, inRange, threshold , adaptiveThreshold, Canny 等函數來獲得;

  hierarchy 為可選的參數,如果不選擇該參數,則可得到 findContours 函數的第二種形式;

// 形式一
void
findContours ( InputOutputArray image, // 輸入圖像 OutputArrayOfArrays contours, // 檢測到的輪廓 OutputArray hierarchy, // 可選的輸出向量 int mode, // 輪廓獲取模式 (RETR_EXTERNAL, RETR_LIST, RETR_CCOMP,RETR_TREE, RETR_FLOODFILL) int method, // 輪廓近似算法 (CHAIN_APPROX_NONE, CHAIN_APPROX_SIMPLE, CHAIN_APPROX_TC89_L1, CHAIN_APPROX_TC89_KCOS) Point offset = Point() // 輪廓偏移量 )
// 形式二
void findContours (
  InputOutputArray   image,
  OutputArrayOfArrays contours,
  int    mode,
  int    method,
  Point   offset = Point()
)

  drawContours 函數參數如下:

void drawContours ( 
    InputOutputArray     image,         // 目標圖像
    InputArrayOfArrays   contours,      // 所有的輸入輪廓
    int               contourIdx,      //
    const Scalar &     color,           //  輪廓顏色
    int          thickness = 1,         //  輪廓線厚度
    int          lineType = LINE_8,     //
    InputArray   hierarchy = noArray(), //
    int          maxLevel = INT_MAX,    //
    Point        offset = Point()       //     
)     

2.2  例程

  代碼摘自 OpenCV 例程,略有修改

#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"

using namespace cv;
using namespace std;

Mat src,src_gray;
int thresh = 100;
int max_thresh = 255;
RNG rng(12345);

void thresh_callback(int, void* );

int main( int, char** argv )
{
  // 讀圖
  src = imread("Pillnitz.jpg", IMREAD_COLOR); 
  if (src.empty())
      return -1;

  // 轉化為灰度圖
  cvtColor(src, src_gray, COLOR_BGR2GRAY );
  blur(src_gray, src_gray, Size(3,3) );
  
  // 顯示
  namedWindow("Source", WINDOW_AUTOSIZE );
  imshow( "Source", src );

  // 滑動條
  createTrackbar("Canny thresh:", "Source", &thresh, max_thresh, thresh_callback );

  // 回調函數
  thresh_callback( 0, 0 );

  waitKey(0);
}

// 回調函數
void thresh_callback(int, void* )
{
  Mat canny_output;
  vector<vector<Point> > contours;
  vector<Vec4i> hierarchy;
  
  // canny 邊緣檢測
  Canny(src_gray, canny_output, thresh, thresh*2, 3);
  
  // 尋找輪廓
  findContours( canny_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0) );

  Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3);
  
  // 畫出輪廓
  for( size_t i = 0; i< contours.size(); i++ ) {
      Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
      drawContours( drawing, contours, (int)i, color, 2, 8, hierarchy, 0, Point() );
  }

  namedWindow( "Contours", WINDOW_AUTOSIZE );
  imshow( "Contours", drawing );
}

  以 Dresden 的 Schloss Pillnitz 為源圖,輸出如下:

 

 

參考資料

  OpenCV Tutorials / imgproc module / Basic Thresholding Operations

  OpenCV Tutorials / imgproc module / Finding contours in your image

  OpenCV-Python Tutorials / Image Processing in OpenCV / Image Thresholding

  <圖像處理、分析與機器視覺>_第3版  第 6 章

  Topological structural analysis of digitized binary images by border following [J], Satoshi Suzuki, 1985

 

更新記錄

   2020年4月26日,增加 “1.3  自適應閾值化” 和 “1.4 示例 - 自適應閾值代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM