Opencv中的dft()和idft()示例
傅里葉變換的公式,大家腦部,本實例是先將一副圖像做傅里葉變換,再對傅里葉陣列做逆變換,代碼如下:
#include <iostream> #include<opencv2/opencv.hpp> using namespace cv; using namespace std; void dftshift(Mat& ds) { int cx=ds.cols/2;//圖像的中心點x坐標 int cy=ds.rows/2;//圖像的中心點y坐標 Mat q0=ds(Rect(0,0,cx,cy));//左上 Mat q1=ds(Rect(cx,0,cx,cy));//右上 Mat q2=ds(Rect(0,cy,cx,cy));//左下 Mat q3=ds(Rect(cx,cy,cx,cy));//右下 Mat tmp; q0.copyTo(tmp); q3.copyTo(q0); tmp.copyTo(q3); q1.copyTo(tmp); q2.copyTo(q1); tmp.copyTo(q2); } void myimshow(const Mat& complexImg) { Mat mag; //對復數圖像計算幅值 Mat planes[2]; split(complexImg,planes); magnitude(planes[0],planes[1],mag); //對幅值去對數log Mat mag_log; mag +=Scalar::all(1); cv::log(mag,mag_log); //對幅值圖像做歸一化處理 Mat mag_norm; cv::normalize(mag_log,mag_norm,0,1,CV_MINMAX); imshow("dft magnitud",mag_norm); } void myimshow2(const Mat& complexImg) { Mat mag; //對復數圖像計算幅值 Mat planes[2]; split(complexImg,planes); magnitude(planes[0],planes[1],mag); normalize(mag,mag,1,0,CV_MINMAX); imshow("inverce dft magnitud",mag); } int main() { //1.讀入灰度圖像,不要讀入彩色圖像 // Mat img=imread("D:/Qt/MyImage/baboon.jpg",0); Mat img=Mat::zeros(300,300,CV_32F);//定義輸入圖像的實部300×300的0矩陣, //單通道。也可以從外部讀入一灰度圖像。 //下面一行語句,在圖像中央6×6Rect區域賦值為1 img(Rect(img.cols/2-3,img.rows/2-3,6,6))=Scalar::all(1); imshow("original image",img); //2.將單通道圖像轉換成雙通道圖像 Mat img2; img.convertTo(img2,CV_32FC2); //3.調用dft函數實現傅里葉變換 Mat img_dft; dft(img2,img_dft,DFT_COMPLEX_OUTPUT); //4.顯示傅里葉頻譜圖 dftshift(img_dft);//傅里葉普的中心化 myimshow(img_dft); //5.調用idft()函數,執行逆傅里葉變換 Mat iimg; idft(img_dft,iimg); myimshow2(iimg); waitKey(); return 0; }
運行結果如下,左圖是原圖像,中間是頻譜圖,右邊是經逆傅里葉變換得到復原圖像:


浙公網安備 33010602011771號