#include<opencv2/opencv.hpp> #include<opencv2/highgui/highgui.hpp> #include<iostream> using namespace cv; using namespace std; int main() { Mat srcImage=imread("redflo.bmp",0);//读取并转成灰度图 int m=getOptimalDFTSize(srcImage.rows);//计算离散傅里叶变换最佳尺寸 int n=getOptimalDFTSize(srcImage.cols); Mat padded; //尺寸为2,3,5倍时,离散傅里叶变换较快,因此进行扩边,并用0补充 copyMakeBorder(srcImage,padded,0,m-srcImage.rows,0,n-srcImage.cols,BORDER_CONSTANT,Scalar::all(0)); //为傅里叶变换实部和虚部分配空间 Mat planes[]={Mat_<float>(padded),Mat::zeros(padded.size(),CV_32F)}; Mat complexI; merge(planes,2,complexI); //进行离散傅里叶变换 dft(complexI,complexI); split(complexI,planes); //求幅值放到planes[0] magnitude(planes[0],planes[1],planes[0]); Mat magnitudeImage=planes[0]; //对数变换,原因是幅值太大,必须缩小到合适显示的区间 magnitudeImage+=Scalar::all(1); log(magnitudeImage,magnitudeImage); //若是奇数,需要频谱裁剪 magnitudeImage=magnitudeImage(Rect(0,0,magnitudeImage.cols&-2,magnitudeImage.rows&(INT_MAX-2)));//-2或(INT_MAX-2) int cx=magnitudeImage.cols/2; int cy=magnitudeImage.rows/2; Mat q0(magnitudeImage,Rect(0,0,cx,cy)); Mat q1(magnitudeImage,Rect(cx,0,cx,cy)); Mat q2(magnitudeImage,Rect(0,cy,cx,cy)); Mat q3(magnitudeImage,Rect(cx,cy,cx,cy)); //交换1,3(2,4)像限,直流和低频放中间,将(0,0)放中间 Mat tmp; q0.copyTo(tmp); q3.copyTo(q0); tmp.copyTo(q3); q1.copyTo(tmp); q2.copyTo(q1); tmp.copyTo(q2); //归一化至[0,1] normalize(magnitudeImage,magnitudeImage,0,1,CV_MINMAX); imshow("srcImage",srcImage); imshow("spectrum",magnitudeImage); cout<<srcImage.rows<<endl<<srcImage.cols<<endl;//676*1024 cout<<magnitudeImage.rows<<endl<<magnitudeImage.cols<<endl;//720*1024 waitKey(0); }