Opencv實現圖像的灰度處理,二值化,閥值選擇


前幾天接觸了圖像的處理,發現用OPencv處理確實比較方便。畢竟是非常多東西都封裝好的。可是要研究里面的東西,還是比較麻煩的,首先,你得知道圖片處理的一些知識,比方腐蝕,膨脹,仿射,透射等,還有非常多算法,傅里葉。積分,卷積,頻譜,加權。

。。,反正我看了半天,是雲里霧里的。所以就想先就籠統的過一遍,以后遇到了再詳細分析,比較這方面的基礎沒那么扎實。

先來記錄下眼下學習到的一些知識。

首先是圖像的灰度處理:

CV_LOAD_IMAGE_GRAYSCALE,這是最簡單之間的辦法,在加載圖像時直接處理

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




免責聲明!

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



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