dft.cpp 2.07 KB
Newer Older
1 2 3
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
4

5 6
#include <stdio.h>

7 8
using namespace cv;
using namespace std;
Gary Bradski's avatar
Gary Bradski committed
9

10
static void help()
Gary Bradski's avatar
Gary Bradski committed
11
{
12 13 14 15
    printf("\nThis program demonstrated the use of the discrete Fourier transform (dft)\n"
           "The dft of an image is taken and it's power spectrum is displayed.\n"
           "Usage:\n"
            "./dft [image_name -- default lena.jpg]\n");
Gary Bradski's avatar
Gary Bradski committed
16 17
}

18
const char* keys =
19
{
20
    "{1| |lena.jpg|input image file}"
21
};
Gary Bradski's avatar
Gary Bradski committed
22

23
int main(int argc, const char ** argv)
24
{
25
    help();
26 27
    CommandLineParser parser(argc, argv, keys);
    string filename = parser.get<string>("1");
28

29
    Mat img = imread(filename.c_str(), CV_LOAD_IMAGE_GRAYSCALE);
30 31
    if( img.empty() )
    {
Gary Bradski's avatar
Gary Bradski committed
32
        help();
33
        printf("Cannot read image file: %s\n", filename.c_str());
34 35 36 37 38 39
        return -1;
    }
    int M = getOptimalDFTSize( img.rows );
    int N = getOptimalDFTSize( img.cols );
    Mat padded;
    copyMakeBorder(img, padded, 0, M - img.rows, 0, N - img.cols, BORDER_CONSTANT, Scalar::all(0));
40

41 42 43
    Mat planes[] = {Mat_<float>(padded), Mat::zeros(padded.size(), CV_32F)};
    Mat complexImg;
    merge(planes, 2, complexImg);
44

45
    dft(complexImg, complexImg);
46

47 48 49 50 51 52
    // compute log(1 + sqrt(Re(DFT(img))**2 + Im(DFT(img))**2))
    split(complexImg, planes);
    magnitude(planes[0], planes[1], planes[0]);
    Mat mag = planes[0];
    mag += Scalar::all(1);
    log(mag, mag);
53

54 55
    // crop the spectrum, if it has an odd number of rows or columns
    mag = mag(Rect(0, 0, mag.cols & -2, mag.rows & -2));
56

57 58
    int cx = mag.cols/2;
    int cy = mag.rows/2;
59

60 61 62 63 64 65 66
    // rearrange the quadrants of Fourier image
    // so that the origin is at the image center
    Mat tmp;
    Mat q0(mag, Rect(0, 0, cx, cy));
    Mat q1(mag, Rect(cx, 0, cx, cy));
    Mat q2(mag, Rect(0, cy, cx, cy));
    Mat q3(mag, Rect(cx, cy, cx, cy));
67

68 69 70
    q0.copyTo(tmp);
    q3.copyTo(q0);
    tmp.copyTo(q3);
71

72 73 74
    q1.copyTo(tmp);
    q2.copyTo(q1);
    tmp.copyTo(q2);
75

76
    normalize(mag, mag, 0, 1, CV_MINMAX);
77

78 79 80 81 82
    imshow("spectrum magnitude", mag);
    waitKey();
    return 0;
}