2016年3月27日 星期日

Thresholding using OpenCV

Thresholding using OpenCV

門檻值過濾算是最簡單的影像切割方法,OpenCV提供兩個APIcv::thresholdcv::adaptiveThreshold讓開發者使用,threshold這個API必須自己設定門檻值,而adaptiveThreshold可以自動判斷適合的門檻值,依個人需求而決定使用哪一個。

double threshold(InputArray src, OutputArray dst, double thresh, double maxval, int type)

  • src 輸入影像
  • dst 輸出影像
  • thresh 門檻值
  • maxval 滿足條件給予該像素點的值
  • type 計算後輸出影像的呈現型態,型態如下:

    • THRESH_BINARY

    • THRESH_BINARY_INV

    • THRESH_TRUNC

    • THRESH_TOZERO

    • THRESH_TOZERO_INV

cv::Mat grayImg;
cv::cvtColor(srcImg, grayImg, cv::COLOR_BGR2GRAY);

cv::Mat binImg, binInvImg, truncImg, tozeroImg, tozeroInvImg, otsuImg, trianImg;
double th = 127, maxVal = 255;
cv::threshold( grayImg, binImg, th, maxVal, cv::THRESH_BINARY );
cv::threshold( grayImg, binInvImg, th, maxVal, cv::THRESH_BINARY_INV );
cv::threshold( grayImg, truncImg, th, maxVal, cv::THRESH_TRUNC );
cv::threshold( grayImg, tozeroImg, th, maxVal, cv::THRESH_TOZERO );
cv::threshold( grayImg, tozeroInvImg, th, maxVal, cv::THRESH_TOZERO_INV );
cv::threshold( grayImg, trianImg, th, maxVal, cv::THRESH_TRIANGLE );
cv::threshold( grayImg, otsuImg, 0, maxVal, cv::THRESH_BINARY+cv::THRESH_OTSU );

詳細Sample Code請參考GitHub

void adaptiveThreshold(InputArray src, OutputArray dst, double maxValue, int adaptiveMethod, int thresholdType, int blockSize, double C)

  • src 輸入影像(灰階)
  • dst 輸出影像
  • maxValue 滿足條件給予該像素點的值
  • adaptiveMethod 自動篩選門檻值的方法
    • ADAPTIVE_THRESH_MEAN_C 平均加權
    • ADAPTIVE_THRESH_GAUSSIAN_C 高斯函數
  • thresholdType 計算後輸出影像的呈現型態,型態如下:

    • THRESH_BINARY

    • THRESH_BINARY_INV

  • blockSize 鄰近像素需要加入參考的大小

  • C
cv::Mat grayImg;
cv::cvtColor(srcImg, grayImg, cv::COLOR_BGR2GRAY);

cv::Mat adapMaenImg, adapGaussianImg;
double maxVal = 255;

cv::adaptiveThreshold( grayImg, adapMaenImg, maxVal, cv::ADAPTIVE_THRESH_MEAN_C, cv::THRESH_BINARY, 11, 2 );
cv::adaptiveThreshold( grayImg, adapGaussianImg, maxVal, cv::ADAPTIVE_THRESH_GAUSSIAN_C, cv::THRESH_BINARY, 11, 2 );

詳細Sample Code請參考GitHub

更多OpenCV文章請參考:OpenCV Tutorial (學習筆記)

0 意見:

張貼留言