3

我想用C++语言实现DFT(离散傅里叶变换)来处理图像

一维 DFT 的公式

当我学习理论时,我知道,我可以将 2D DFT 分成两个 1D DFT部分。首先,我对每一行执行 1D DFT,然后对每一列执行此操作。当然,我应该对复数进行运算。

这里会出现一些问题,因为我不确定在哪里使用实数,以及在哪里使用复数的虚部。我在某处发现,我应该将输入图像像素的值视为实部,虚部设置为 0。

我做了一个实现,但我认为结果图像不正确。

莱纳克lenac_dft

如果有人能帮我解决这个问题,我将不胜感激。

对于读取和保存图像,我使用CImg library

void DFT (CImg<unsigned char> image)
{
    int w=512;
    int h=512;
    int rgb=3;
    complex <double> ***obrazek=new complex <double>**[w];
    for (int b=0;b<w;b++) //making 3-dimensional table to store DFT values
    {
        obrazek[b]=new complex <double>*[h];
        for (int a=0;a<h;a++)
        {
            obrazek[b][a]=new complex <double>[rgb];
        }
    }

    CImg<unsigned char> kopia(image.width(),image.height(),1,3,0);

    complex<double> sum=0;
    complex<double> sum2=0;
    double pi = 3.14;

    for (int i=0; i<512; i++){
    for (int j=0; j<512; j++){
    for (int c=0; c<3; c++){
        complex<double> cplx(image(i,j,c), 0);
        obrazek[i][j][c]=cplx;
    }}}

    for (int c=0; c<3; c++) //for rows
    {
            for (int y=0; y<512; y++)
            {
                sum=0;
                for (int x=0; x<512; x++)
                {
                    sum+=(obrazek[x][y][c].real())*cos((2*pi*x*y)/512)-(obrazek[x][y][c].imag())*sin((2*pi*x*y)/512);
                    obrazek[x][y][c]=sum;
                }
            }
    }

    for (int c=0; c<3; c++) //for columns
    {
            for (int y=0; y<512; y++)//r
            {
                sum2=0;
                for (int x=0; x<512; x++)
                {
                    sum2+=(obrazek[y][x][c].real())*cos((2*pi*x*y)/512)-(obrazek[y][x][c].imag())*sin((2*pi*x*y)/512);
                    obrazek[y][x][c]=sum2;
                }
            }
    }

    for (int i=0; i<512; i++){
    for (int j=0; j<512; j++){
    for (int c=0; c<3; c++){
        kopia(i,j,c)=obrazek[i][j][c].real();
    }}}

    CImgDisplay image_disp(kopia,"dft");

    while (!image_disp.is_closed() )
    {

        image_disp.wait();

    }
    saving(kopia);
}
4

0 回答 0