openCV學習筆記(二)------圖像平滑處理和邊緣檢測

1.對圖片進行平滑處理:通過圖像數據與高斯或者其他核進行卷積有效的減少圖像信息內容,平滑處理其實就是調用openCV的一個庫函數。
調用的庫函數爲:

CVAPI(void) cvSmooth( const CvArr* src, CvArr* dst,
                      int smoothtype CV_DEFAULT(CV_GAUSSIAN),
                      int size1 CV_DEFAULT(3),
                      int size2 CV_DEFAULT(0),
                      double sigma1 CV_DEFAULT(0),//可以默認,不寫
                      double sigma2 CV_DEFAULT(0));//可以默認,不寫

實現代碼:

void smooth(IplImage* image)
{
    //create some windows to show the
    //input and output images in
    cvNamedWindow("Smooth_in", CV_WINDOW_AUTOSIZE);
    cvNamedWindow("Smooth_out");

    //create a window to show our input image
    cvShowImage("Smooth_in", image);
    //create an image to hold the smoothed ouput
    IplImage* out = cvCreateImage(
        cvGetSize(image),
        IPL_DEPTH_8U,
        3
    );

    //do some smoothing
    //每個像素周圍3*3的區域進行高斯平滑處理
    cvSmooth(image, out, CV_GAUSSIAN, 3, 3);

    //show the smoothed image in the output window
    cvShowImage("Smooth_out", out);


    //Be tidy
    cvReleaseImage(&out);//一旦用完加載到內存的圖像文件,就可以釋放爲該文件所分配的內存

    //Wait for the user to hit a key, then clean up the window
    cvWaitKey(0);
    cvDestroyWindow("Smooth_in");
    cvDestroyWindow("Smooth_out");
}

這裏寫圖片描述
2.邊緣檢測
送入要進行邊緣檢測的圖像只能是單通道的圖像;

CVAPI(void)  cvCanny( const CvArr* image,//原圖像,必須是單通道灰度圖
                      CvArr* edges, //邊緣檢測後的圖像
                      double threshold1,//閾值1
                      double threshold2, //閾值2
                      int  aperture_size CV_DEFAULT(3) );//sobel算子值

實現代碼:

IplImage *g_pSrcImage, *g_pCannyImg;

void on_trackbar(int threhold)
{
    //canny邊緣檢測
    cvCanny(g_pSrcImage, g_pCannyImg, threhold, threhold*3, 3);
    cvShowImage("邊緣檢測圖", g_pCannyImg);//顯示邊緣檢測窗口
}

int doCanny()
{

    g_pSrcImage = cvLoadImage("D:\\picture\\hah.jpg", 0);//將圖像文件加載至內存

    if (g_pSrcImage->nChannels != 1)
    {
        return(0); //Canny only handles gray scale images
    }
    g_pCannyImg = cvCreateImage(
        cvGetSize(g_pSrcImage),
        IPL_DEPTH_8U,
        1
    );

    cvNamedWindow("原圖");
    cvNamedWindow("邊緣檢測圖");

    //創建滑動條
    int pos = 1;
    cvCreateTrackbar("滑塊", "邊緣檢測圖", &pos, 300, on_trackbar);

    cvShowImage("原圖", g_pSrcImage);
    on_trackbar(1);

    cvWaitKey(0);

    cvReleaseImage(&g_pSrcImage);
    cvReleaseImage(&g_pCannyImg);
    cvDestroyAllWindows();
    return 0;
};

void main()
{
    doCanny();
}

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章