简体   繁体   中英

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.

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())));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM