Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

OpenCV 圖像預處理:灰度化、二值化與閾值選取

前幾天開始接觸影像處理,用 OpenCV 確實方便,畢竟很多細節都封裝好了;但要研究裡面的原理就麻煩得多。腐蝕、膨脹、仿射、透射這些基本操作之外,還有傅里葉、積分、卷積、頻譜、加權等一堆演算法,一時之間很難全部消化。所以先籠統地過一遍,之後遇到再深入。以下記錄目前整理出的三件事。

灰度處理

最直接的方式是在載入時就指定:

IplImage* Igray = cvLoadImage("test.jpg",CV_LOAD_IMAGE_GRAYSCALE);

得到的就是單通道影像。也可以載入後再轉換:

CVAPI(void) cvCvtColor( const CvArr* src, CvArr* dst, int code );
// code = CV_BGR2GRAY;

OpenCV 還提供了其他做法,這裡就不逐一列舉。

二值化

二值化是把影像上每個像素的灰度值設為 0 或 255,讓整張圖呈現鮮明的黑白效果。灰度化之後即可進行,是後續處理的重要一步。不過它並不適合對顏色有要求的影像,對著重輪廓的應用則相當有效。

CVAPI(double) cvThreshold( const CvArr*  src, CvArr*  dst,
                           double  threshold, double  max_value,
                           int threshold_type );

threshold 是閾值,max_value 一般取 255;threshold_type 決定輸出的樣貌:

/* Types of thresholding */
#define CV_THRESH_BINARY       0  /* value = value > threshold ? max_value : 0      */
#define CV_THRESH_BINARY_INV   1  /* value = value > threshold ? 0 : max_value        */
#define CV_THRESH_TRUNC        2  /* value = value > threshold ? threshold : value    */
#define CV_THRESH_TOZERO       3  /* value = value > threshold ? value : 0            */
#define CV_THRESH_TOZERO_INV   4  /* value = value > threshold ? 0 : value            */
#define CV_THRESH_MASK         7

#define CV_THRESH_OTSU         8  /* use Otsu algorithm to choose the optimal threshold value;
                                     combine the flag with one of the above CV_THRESH_* values */

閾值怎麼選

一般會直接取 100、127 這類固定值,取值相當隨意,得到的結果也還可以。但更推薦的做法是自適應閾值:它依據每個像素周圍的區域自行算出閾值,對光照不均勻的影像明顯更穩。

    IplImage* Igray = 0, *It = 0, *Iat;

    int threshold_type = CV_THRESH_BINARY;
    int adaptive_method = CV_ADAPTIVE_THRESH_GAUSSIAN_C;
    int blocksize = 31;
    double offset = 15;
    int threshold = 100;
    if(0 == (Igray = cvLoadImage("test.jpg",CV_LOAD_IMAGE_GRAYSCALE))){
        return -1;
    }
    It = cvCreateImage(cvSize(Igray->width,Igray->height),
                       IPL_DEPTH_8U, 1);
    Iat = cvCreateImage(cvSize(Igray->width,Igray->height),
                        IPL_DEPTH_8U, 1);

    //Threshold
    cvThreshold(Igray,It,threshold,255,threshold_type);//閥值100
    cvAdaptiveThreshold(Igray,Iat,255,adaptive_method,//自適應閥值,blocksize為奇數
                        threshold_type,blocksize,offset);

使用 cvAdaptiveThreshold 時要記得 blocksize 必須是奇數,offset 則是從算出的均值中扣除的常數,可依效果微調。

Copyright © Linux教程網 All Rights Reserved