Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/cpp/dft.cpp
16337 views
1
#include "opencv2/core.hpp"
2
#include "opencv2/core/utility.hpp"
3
#include "opencv2/imgproc.hpp"
4
#include "opencv2/imgcodecs.hpp"
5
#include "opencv2/highgui.hpp"
6
7
#include <stdio.h>
8
9
using namespace cv;
10
using namespace std;
11
12
static void help()
13
{
14
printf("\nThis program demonstrated the use of the discrete Fourier transform (dft)\n"
15
"The dft of an image is taken and it's power spectrum is displayed.\n"
16
"Usage:\n"
17
"./dft [image_name -- default ../data/lena.jpg]\n");
18
}
19
20
const char* keys =
21
{
22
"{help h||}{@image|../data/lena.jpg|input image file}"
23
};
24
25
int main(int argc, const char ** argv)
26
{
27
help();
28
CommandLineParser parser(argc, argv, keys);
29
if (parser.has("help"))
30
{
31
help();
32
return 0;
33
}
34
string filename = parser.get<string>(0);
35
Mat img = imread(filename, IMREAD_GRAYSCALE);
36
if( img.empty() )
37
{
38
help();
39
printf("Cannot read image file: %s\n", filename.c_str());
40
return -1;
41
}
42
int M = getOptimalDFTSize( img.rows );
43
int N = getOptimalDFTSize( img.cols );
44
Mat padded;
45
copyMakeBorder(img, padded, 0, M - img.rows, 0, N - img.cols, BORDER_CONSTANT, Scalar::all(0));
46
47
Mat planes[] = {Mat_<float>(padded), Mat::zeros(padded.size(), CV_32F)};
48
Mat complexImg;
49
merge(planes, 2, complexImg);
50
51
dft(complexImg, complexImg);
52
53
// compute log(1 + sqrt(Re(DFT(img))**2 + Im(DFT(img))**2))
54
split(complexImg, planes);
55
magnitude(planes[0], planes[1], planes[0]);
56
Mat mag = planes[0];
57
mag += Scalar::all(1);
58
log(mag, mag);
59
60
// crop the spectrum, if it has an odd number of rows or columns
61
mag = mag(Rect(0, 0, mag.cols & -2, mag.rows & -2));
62
63
int cx = mag.cols/2;
64
int cy = mag.rows/2;
65
66
// rearrange the quadrants of Fourier image
67
// so that the origin is at the image center
68
Mat tmp;
69
Mat q0(mag, Rect(0, 0, cx, cy));
70
Mat q1(mag, Rect(cx, 0, cx, cy));
71
Mat q2(mag, Rect(0, cy, cx, cy));
72
Mat q3(mag, Rect(cx, cy, cx, cy));
73
74
q0.copyTo(tmp);
75
q3.copyTo(q0);
76
tmp.copyTo(q3);
77
78
q1.copyTo(tmp);
79
q2.copyTo(q1);
80
tmp.copyTo(q2);
81
82
normalize(mag, mag, 0, 1, NORM_MINMAX);
83
84
imshow("spectrum magnitude", mag);
85
waitKey();
86
return 0;
87
}
88
89