Merge pull request #3121 from akarsakov:ocl_dft_opt
[profile/ivi/opencv.git] / samples / cpp / dft.cpp
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 lena.jpg]\n");
18 }
19
20 const char* keys =
21 {
22     "{@image|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     string filename = parser.get<string>(0);
30
31     Mat img = imread(filename.c_str(), IMREAD_GRAYSCALE);
32     if( img.empty() )
33     {
34         help();
35         printf("Cannot read image file: %s\n", filename.c_str());
36         return -1;
37     }
38     int M = getOptimalDFTSize( img.rows );
39     int N = getOptimalDFTSize( img.cols );
40     Mat padded;
41     copyMakeBorder(img, padded, 0, M - img.rows, 0, N - img.cols, BORDER_CONSTANT, Scalar::all(0));
42
43     Mat planes[] = {Mat_<float>(padded), Mat::zeros(padded.size(), CV_32F)};
44     Mat complexImg;
45     merge(planes, 2, complexImg);
46
47     dft(complexImg, complexImg);
48
49     // compute log(1 + sqrt(Re(DFT(img))**2 + Im(DFT(img))**2))
50     split(complexImg, planes);
51     magnitude(planes[0], planes[1], planes[0]);
52     Mat mag = planes[0];
53     mag += Scalar::all(1);
54     log(mag, mag);
55
56     // crop the spectrum, if it has an odd number of rows or columns
57     mag = mag(Rect(0, 0, mag.cols & -2, mag.rows & -2));
58
59     int cx = mag.cols/2;
60     int cy = mag.rows/2;
61
62     // rearrange the quadrants of Fourier image
63     // so that the origin is at the image center
64     Mat tmp;
65     Mat q0(mag, Rect(0, 0, cx, cy));
66     Mat q1(mag, Rect(cx, 0, cx, cy));
67     Mat q2(mag, Rect(0, cy, cx, cy));
68     Mat q3(mag, Rect(cx, cy, cx, cy));
69
70     q0.copyTo(tmp);
71     q3.copyTo(q0);
72     tmp.copyTo(q3);
73
74     q1.copyTo(tmp);
75     q2.copyTo(q1);
76     tmp.copyTo(q2);
77
78     normalize(mag, mag, 0, 1, NORM_MINMAX);
79
80     imshow("spectrum magnitude", mag);
81     waitKey();
82     return 0;
83 }