user2013535
user2013535

Reputation: 73

Complex Numbers and Naive Fourier Transform (C++)

I'm trying to get fourier transforms to work, I have to do it for an assignment and I think I have it to where it should be working and i'm not sure why it's not. I think it has something to do with the complex numbers since 'i' is involved. I've looked at many references and I understand the formula but i'm having trouble programming it. this is what i have so far

void NaiveDFT::Apply( Image & img )
{
    //make the fourier transform using the naive method and set that to the image.
    Image dft(img);
    Pixel ** dftData = dft.GetImageData();
    Pixel ** imgData = img.GetImageData();
    for(unsigned u = 0; u < img.GetWidth(); ++u)
    {
        for(unsigned v = 0; v < img.GetHeight(); ++v)
        {
            std::complex<double> sum = 0;
            for(unsigned x = 0; x < img.GetWidth(); ++x)
            {
                for(unsigned y = 0; y < img.GetHeight(); ++y)
                {
                    std::complex<double> i = sqrt(std::complex<double>(-1));
                    std::complex<double> theta = 2 * M_PI * (((u * x) / img.GetWidth()) + ((v * y) / img.GetHeight()));
                    sum += std::complex<double>(imgData[x][y]._red) * cos(theta) + (-i * sin(theta));
                    //sum += std::complex<double>(std::complex<double>(imgData[x][y]._red) * pow(EULER, -i * theta));

                }
            }
            dftData[u][v] = (sum.imag() / (img.GetWidth() * img.GetHeight()));
        }
    }
    img = dft;
}

I have a few test images i'm testing this with and i'm either getting like an all black image or like, an all gray image.

I've also tried the sum of e^(-i*2*PI*(x*u*width + y*v*height) * 1/width * height which gets the same result as expected although it's still not the desiered output.

I've also tried the sum.real() number and that doesn't look right either

if anyone has any tips or can point me in the right direction, that'd be great, at this point, i just keep trying different things and checking the output until I get what I should be getting.

thanks.

Upvotes: 1

Views: 538

Answers (1)

fatihk
fatihk

Reputation: 7919

I think that there can be a problem during the multiplication with the complex term. The line:

sum += std::complex<double>(imgData[x][y]._red) * cos(theta) + (-i * sin(theta));

should be:

sum += std::complex<double>(imgData[x][y]._red) * ( cos(theta) + -i * sin(theta));

Moreover, while calculating theta you need to use double precision:

std::complex<double> theta = 2 * M_PI * ((((double)u * x) / (double)(img.GetWidth())) + (((double)v * y) / (double)(img.GetHeight())));

Upvotes: 1

Related Questions