#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main(int argc, char **argv)
{
Mat srcImage = imread("/home/cjk/图片/777.png");
cout << "@@@@@ 1 @@@" << endl;
if (srcImage.empty() )
{
std::cerr << "fail to load image " << std::endl;
return -1;
}
//转换为灰度图像
Mat grayImage;
cvtColor(srcImage,grayImage,COLOR_BGR2GRAY);
cout << "@@@@@ 2 @@@" << endl;
//将图像拓展到傅里叶变换的最佳尺寸
int row = getOptimalDFTSize(grayImage.rows);
int col = getOptimalDFTSize(grayImage.cols);
//将扩展后的尺寸设置为0
Mat padded;
copyMakeBorder(grayImage,padded,0,row-grayImage.rows,
0,col-grayImage.cols,BORDER_CONSTANT,Scalar::all(0));
//傅里叶计算的实部与虚部
cout << "@@@@@ 3 @@@" << endl;
Mat planes[] = {Mat_<float>(padded),Mat_<float>(padded.size(),CV_32F)};
Mat complexI;
merge(planes,2,complexI);
//进行傅里叶变换
dft(complexI,complexI);
//将复数转换为幅值
cout << "@@@@@ 4 @@@" << endl;
split(complexI,planes);
magnitude(planes[0],planes[1],planes[0]);
Mat magnitudeImage = planes[0];
//尺寸缩放
magnitudeImage += Scalar::all(1);
log(magnitudeImage,magnitudeImage);
cout << "----------------" << endl;
//剪切和重分布图像
cout << "magnitudeImage.size() : " << magnitudeImage.size() << endl;
cout << "magnitudeImage.rows : " << magnitudeImage.rows << endl;
cout << "magnitudeImage.cols : " << magnitudeImage.cols << endl;
magnitudeImage = magnitudeImage(Rect(0,0,magnitudeImage.cols ,magnitudeImage.rows ));
cout << "----------------" << endl;
int cx = magnitudeImage.cols / 2;
int cy = magnitudeImage.rows / 2;
cout << "cx : " << cx << endl;
cout << "cy : " << cy << endl;
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));
//交换象限 左上和右下
cout << "@@@@@ 6 @@@" << endl;
Mat temp;
q0.copyTo(temp);
q3.copyTo(q0);
temp.copyTo(q3);
//右上和左下
q1.copyTo(temp);
q2.copyTo(q1);
temp.copyTo(q2);
//归一化
normalize(magnitudeImage,magnitudeImage,0,1,NORM_MINMAX);
imshow("srcImage",srcImage);
imshow("freq and Amplitude",magnitudeImage);
waitKey();
//cvDestroyAllWindows();
return 0;
}