OpenCV 离散傅立叶变换

 1 #include "opencv2/core/core.hpp"
 2 #include "opencv2/imgproc/imgproc.hpp"
 3 #include "opencv2/highgui/highgui.hpp"
 4 #include <iostream>
 5 int main(int argc, char ** argv)
 6 {
 7     const char* filename = argc >=2 ? argv[1] : "lena.jpg";
 8 
 9     Mat I = imread(filename, CV_LOAD_IMAGE_GRAYSCALE);
10     if( I.empty())
11         return -1;
12     
13     Mat padded;                            //expand input image to optimal size
14     int m = getOptimalDFTSize( I.rows );
15     int n = getOptimalDFTSize( I.cols ); // on the border add zero values
16     copyMakeBorder(I, padded, 0, m - I.rows, 0, n - I.cols, BORDER_CONSTANT, Scalar::all(0));
17 
18     Mat planes[] = {Mat_<float>(padded), Mat::zeros(padded.size(), CV_32F)};
19     Mat complexI;
20     merge(planes, 2, complexI);         // Add to the expanded another plane with zeros
21 
22     dft(complexI, complexI);            // this way the result may fit in the source matrix
23 
24     // compute the magnitude and switch to logarithmic scale
25     // => log(1 + sqrt(Re(DFT(I))^2 + Im(DFT(I))^2))
26     split(complexI, planes);                   // planes[0] = Re(DFT(I), planes[1] = Im(DFT(I))
27     magnitude(planes[0], planes[1], planes[0]);// planes[0] = magnitude  
28     Mat magI = planes[0];
29     
30     magI += Scalar::all(1);                    // switch to logarithmic scale
31     log(magI, magI);
32 
33     // crop the spectrum, if it has an odd number of rows or columns
34     magI = magI(Rect(0, 0, magI.cols & -2, magI.rows & -2));
35 
36     // rearrange the quadrants of Fourier image  so that the origin is at the image center        
37     int cx = magI.cols/2;
38     int cy = magI.rows/2;
39 
40     Mat q0(magI, Rect(0, 0, cx, cy));   // Top-Left - Create a ROI per quadrant 
41     Mat q1(magI, Rect(cx, 0, cx, cy));  // Top-Right
42     Mat q2(magI, Rect(0, cy, cx, cy));  // Bottom-Left
43     Mat q3(magI, Rect(cx, cy, cx, cy)); // Bottom-Right
44 
45     Mat tmp;                           // swap quadrants (Top-Left with Bottom-Right)
46     q0.copyTo(tmp);
47     q3.copyTo(q0);
48     tmp.copyTo(q3);
49 
50     q1.copyTo(tmp);                    // swap quadrant (Top-Right with Bottom-Left)
51     q2.copyTo(q1);
52     tmp.copyTo(q2);
53 
54     normalize(magI, magI, 0, 1, CV_MINMAX); // Transform the matrix with float values into a 
55                                             // viewable image form (float between values 0 and 1).
56 
57     imshow("Input Image"       , I   );    // Show the result
58     imshow("spectrum magnitude", magI);    
59     waitKey();
60 
61     return 0;
62 }
原文地址:https://www.cnblogs.com/ybqjymy/p/12170891.html