1
#include "opencv2/core/core.hpp"
2
#include "opencv2/imgproc/imgproc.hpp"
3
#include "opencv2/imgcodecs.hpp"
4
#include "opencv2/highgui/highgui.hpp"
11
static void help(char* progName)
14
<< "This program demonstrated the use of the discrete Fourier transform (DFT). " << endl
15
<< "The dft of an image is taken and it's power spectrum is displayed." << endl
17
<< progName << " [image_name -- default ../data/lena.jpg] " << endl << endl;
20
int main(int argc, char ** argv)
24
const char* filename = argc >=2 ? argv[1] : "../data/lena.jpg";
26
Mat I = imread(filename, IMREAD_GRAYSCALE);
30
Mat padded; //expand input image to optimal size
31
int m = getOptimalDFTSize( I.rows );
32
int n = getOptimalDFTSize( I.cols ); // on the border add zero values
33
copyMakeBorder(I, padded, 0, m - I.rows, 0, n - I.cols, BORDER_CONSTANT, Scalar::all(0));
35
Mat planes[] = {Mat_<float>(padded), Mat::zeros(padded.size(), CV_32F)};
37
merge(planes, 2, complexI); // Add to the expanded another plane with zeros
39
dft(complexI, complexI); // this way the result may fit in the source matrix
41
// compute the magnitude and switch to logarithmic scale
42
// => log(1 + sqrt(Re(DFT(I))^2 + Im(DFT(I))^2))
43
split(complexI, planes); // planes[0] = Re(DFT(I), planes[1] = Im(DFT(I))
44
magnitude(planes[0], planes[1], planes[0]);// planes[0] = magnitude
47
magI += Scalar::all(1); // switch to logarithmic scale
50
// crop the spectrum, if it has an odd number of rows or columns
51
magI = magI(Rect(0, 0, magI.cols & -2, magI.rows & -2));
53
// rearrange the quadrants of Fourier image so that the origin is at the image center
57
Mat q0(magI, Rect(0, 0, cx, cy)); // Top-Left - Create a ROI per quadrant
58
Mat q1(magI, Rect(cx, 0, cx, cy)); // Top-Right
59
Mat q2(magI, Rect(0, cy, cx, cy)); // Bottom-Left
60
Mat q3(magI, Rect(cx, cy, cx, cy)); // Bottom-Right
62
Mat tmp; // swap quadrants (Top-Left with Bottom-Right)
67
q1.copyTo(tmp); // swap quadrant (Top-Right with Bottom-Left)
71
normalize(magI, magI, 0, 1, NORM_MINMAX); // Transform the matrix with float values into a
72
// viewable image form (float between values 0 and 1).
74
imshow("Input Image" , I ); // Show the result
75
imshow("spectrum magnitude", magI);