1. 程式人生 > >OpenCV 之 圖像分割 (一)

OpenCV 之 圖像分割 (一)

tutorial 轉化 分析 可選 name lar 機器 不能 mes

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 cv::threshold 函數

OpenCV 中的閾值化函數為 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 例程,略作修改

#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);
}

2 基於邊緣

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

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

2.1 輪廓函數

OpenCV 中,可在圖像的邊緣檢測之後,依次使用 cv::findContourscv::drawContours 函數,尋找到輪廓並將其畫出

void cv::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() // 輪廓偏移量
)

cv::drawContours 函數各參數如下:

void cv::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

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

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

OpenCV 之 圖像分割 (一)