功率谱如图: (C++实现) (MATLAB实现)
代码: C++:
#include<opencv2\core.hpp>
#include<opencv2\imgproc.hpp>
#include<opencv2\imgcodecs.hpp>
#include<opencv2\highgui.hpp>
#include<iostream>
using namespace cv;
using namespace std;
void ShiftDFT(Mat img);
int main(int argc, char ** argv)
{
Mat I = imread("Lena.jpg");
if (I.empty())
{
cout << "Error opening image" << endl;
return EXIT_FAILURE;
}
Mat padded;
int m = getOptimalDFTSize(I.rows);
int n = getOptimalDFTSize(I.cols);
copyMakeBorder(I,padded,0,m-I.rows,0,n-I.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);
Mat Re = planes[0];
Mat Im = planes[1];
Mat P;
P = Re*Re + Im*Im;
P += Scalar::all(1);
log(P, P);
ShiftDFT(P);
normalize(P,P,0,1,NORM_MINMAX);
imshow("spectrum power",P);
waitKey();
return EXIT_SUCCESS;
}
void ShiftDFT(Mat img)
{
int cx = img.cols / 2;
int cy = img.rows / 2;
Mat q0(img, Rect(0, 0, cx, cy));
Mat q1(img, Rect(cx, 0, cx, cy));
Mat q2(img, Rect(0, cy, cx, cy));
Mat q3(img, 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);
}
MATLAB:
f=imread("Lena.jpg");
F=fft2(f);
Re=real(F);
Im=imag(F);
Psd=Re.*Re+Im.*Im;
Psd=fftshift(log(1+abs(Psd)));
Psd=mat2gray(Psd,[min(Psd(:)),max(Psd(:))]);
figure;
imshow(Psd);
|