dft.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. #include <stdio.h>
  7. using namespace cv;
  8. using namespace std;
  9. static void help(const char ** argv)
  10. {
  11. printf("\nThis program demonstrated the use of the discrete Fourier transform (dft)\n"
  12. "The dft of an image is taken and it's power spectrum is displayed.\n"
  13. "Usage:\n %s [image_name -- default lena.jpg]\n",argv[0]);
  14. }
  15. const char* keys =
  16. {
  17. "{help h||}{@image|lena.jpg|input image file}"
  18. };
  19. int main(int argc, const char ** argv)
  20. {
  21. help(argv);
  22. CommandLineParser parser(argc, argv, keys);
  23. if (parser.has("help"))
  24. {
  25. help(argv);
  26. return 0;
  27. }
  28. string filename = parser.get<string>(0);
  29. Mat img = imread(samples::findFile(filename), IMREAD_GRAYSCALE);
  30. if( img.empty() )
  31. {
  32. help(argv);
  33. printf("Cannot read image file: %s\n", filename.c_str());
  34. return -1;
  35. }
  36. int M = getOptimalDFTSize( img.rows );
  37. int N = getOptimalDFTSize( img.cols );
  38. Mat padded;
  39. copyMakeBorder(img, padded, 0, M - img.rows, 0, N - img.cols, BORDER_CONSTANT, Scalar::all(0));
  40. Mat planes[] = {Mat_<float>(padded), Mat::zeros(padded.size(), CV_32F)};
  41. Mat complexImg;
  42. merge(planes, 2, complexImg);
  43. dft(complexImg, complexImg);
  44. // compute log(1 + sqrt(Re(DFT(img))**2 + Im(DFT(img))**2))
  45. split(complexImg, planes);
  46. magnitude(planes[0], planes[1], planes[0]);
  47. Mat mag = planes[0];
  48. mag += Scalar::all(1);
  49. log(mag, mag);
  50. // crop the spectrum, if it has an odd number of rows or columns
  51. mag = mag(Rect(0, 0, mag.cols & -2, mag.rows & -2));
  52. int cx = mag.cols/2;
  53. int cy = mag.rows/2;
  54. // rearrange the quadrants of Fourier image
  55. // so that the origin is at the image center
  56. Mat tmp;
  57. Mat q0(mag, Rect(0, 0, cx, cy));
  58. Mat q1(mag, Rect(cx, 0, cx, cy));
  59. Mat q2(mag, Rect(0, cy, cx, cy));
  60. Mat q3(mag, Rect(cx, cy, cx, cy));
  61. q0.copyTo(tmp);
  62. q3.copyTo(q0);
  63. tmp.copyTo(q3);
  64. q1.copyTo(tmp);
  65. q2.copyTo(q1);
  66. tmp.copyTo(q2);
  67. normalize(mag, mag, 0, 1, NORM_MINMAX);
  68. imshow("spectrum magnitude", mag);
  69. waitKey();
  70. return 0;
  71. }