歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> OpenCV入門教程之七 圖像濾波

OpenCV入門教程之七 圖像濾波

日期:2017/3/1 9:45:26   编辑:Linux編程

濾波實際上是信號處理裡的一個概念,而圖像本身也可以看成是一個二維的信號。其中像素點灰度值的高低代表信號的強弱。

高頻:圖像中灰度變化劇烈的點。

低頻:圖像中平坦的,灰度變化不大的點。

根據圖像的高頻與低頻的特征,我們可以設計相應的高通與低通濾波器,高通濾波可以檢測圖像中尖銳、變化明顯的地方;低通濾波可以讓圖像變得光滑,濾除圖像中的噪聲。

2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> int main() { using namespace cv; Mat image=imread("../cat.png"); cvtColor(image,image,CV_BGR2GRAY); Mat blurResult; Mat gaussianResult; Mat medianResult; blur(image,blurResult,Size(5,5)); GaussianBlur(image,gaussianResult,Size(5,5),1.5); medianBlur(image,medianResult,5); namedWindow("blur");imshow("blur",blurResult); namedWindow("Gaussianblur");imshow("Gaussianblur",gaussianResult); namedWindow("medianBlur");imshow("medianBlur",medianResult); waitKey(); return 0; }

二、高通濾波:邊緣檢測

高通濾波器最好的一個應用就是邊緣檢測,由文章開頭分析可知高頻是圖像中變化劇烈的地方,所以圖像的邊緣區域恰好符合這一特性,我們可以利用高通濾波讓圖像的邊緣顯露出來,進一步計算圖像的一些特征。

邊緣檢測本來打算作為一個單獨的主題來寫一篇文章,但是由於Canny邊緣檢測算法比較復雜,��幅也較大,所以先把Sobel邊緣檢測在高通濾波這裡作為一個實例,以後Canny邊緣檢測作為單獨的一篇文章來寫。

實際上OpenCV有提供了Sobel邊緣檢測的函數,但是一方面阈值好像取的不太好,另一方面沒有對最後邊緣作細化處理,所以效果並不太讓人滿意,本文是模仿Matlab中算法來寫的,相關的理論可以參考我原來寫過的一篇文章《視覺算法:Sobel邊緣檢測》。

下面是Sobel實現的C++代碼:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 bool Sobel(const Mat& image,Mat& result,int TYPE) { if(image.channels()!=1) return false; // 系數設置 int kx(0); int ky(0); if( TYPE==SOBEL_HORZ ){ kx=0;ky=1; } else if( TYPE==SOBEL_VERT ){ kx=1;ky=0; } else if( TYPE==SOBEL_BOTH ){ kx=1;ky=1; } else return false; // 設置mask float mask[3][3]={{1,2,1},{0,0,0},{-1,-2,-1}}; Mat y_mask=Mat(3,3,CV_32F,mask)/8; Mat x_mask=y_mask.t(); // 轉置 // 計算x方向和y方向上的濾波 Mat sobelX,sobelY; filter2D(image,sobelX,CV_32F,x_mask); filter2D(image,sobelY,CV_32F,y_mask); sobelX=abs(sobelX); sobelY=abs(sobelY); // 梯度圖 Mat gradient=kx*sobelX.mul(sobelX)+ky*sobelY.mul(sobelY); // 計算阈值 int scale=4; double cutoff=scale*mean(gradient)[0]; result.create(image.size(),image.type()); result.setTo(0); for(int i=1;i<image.rows-1;i++) { float* sbxPtr=sobelX.ptr<float>(i); float* sbyPtr=sobelY.ptr<float>(i); float* prePtr=gradient.ptr<float>(i-1); float* curPtr=gradient.ptr<float>(i); float* lstPtr=gradient.ptr<float>(i+1); uchar* rstPtr=result.ptr<uchar>(i); // 阈值化和極大值抑制 for(int j=1;j<image.cols-1;j++) { if( curPtr[j]>cutoff && ( (sbxPtr[j]>kx*sbyPtr[j] && curPtr[j]>curPtr[j-1] && curPtr[j]>curPtr[j+1]) || (sbyPtr[j]>ky*sbxPtr[j] && curPtr[j]>prePtr[j] && curPtr[j]>lstPtr[j]) )) rstPtr[j]=255; } } return true; }

Copyright © Linux教程網 All Rights Reserved