使用FFTW只是为了转换到频域和返回,结果与源有很大的不同

时间:2017-01-28 16:49:58

标签: c++ signal-processing fft fftw

在我的测试用例中,我只使用FFTW将图像转换为频域并返回空间域。但我最终得到的结果与我开始时的结果完全不同。

要解决一些问题:

  • 我在fft()ifft()的每次调用中创建FFTW计划而不是缓存它们的原因是为了简单起见。这应该不是问题
  • 为了简单起见,在将实值数组传递给fftw之前将其转换为复值数组的原因。我发现这种方法比使用真实到复杂的DFT函数更难弄错。

我的代码(包括实用程序函数,宏和类)如下。它使用libcinder(它的旧版本)用于矢量类和图形,但即使你不了解libcinder,它也是不言自明的。请原谅代码长度,我努力让它变得非常小,但像我的Array2D类这样的实用程序占用了相当大的空间。

的main.cpp

#include "precompiled.h"
typedef std::complex<float> Complexf;
using namespace ci;

void createConsole()
{
    AllocConsole();
    std::fstream* fs = new std::fstream("CONOUT$");
    std::cout.rdbuf(fs->rdbuf());
}

#define forxy(image) \
    for(Vec2i p(0, 0); p.x < image.w; p.x++) \
        for(p.y = 0; p.y < image.h; p.y++)
template<class T>
class ArrayDeleter
{
public:
    ArrayDeleter(T* arrayPtr)
    {
        refcountPtr = new int(0);
        (*refcountPtr)++;

        this->arrayPtr = arrayPtr;
    }

    ArrayDeleter(ArrayDeleter const& other)
    {
        arrayPtr = other.arrayPtr;
        refcountPtr = other.refcountPtr;
        (*refcountPtr)++;
    }

    ArrayDeleter const& operator=(ArrayDeleter const& other)
    {
        reduceRefcount();

        arrayPtr = other.arrayPtr;
        refcountPtr = other.refcountPtr;
        (*refcountPtr)++;

        return *this;
    }

    ~ArrayDeleter()
    {
        reduceRefcount();
    }

private:
    void reduceRefcount()
    {
        (*refcountPtr)--;
        if(*refcountPtr == 0)
        {
            delete refcountPtr;
            fftwf_free(arrayPtr);
        }
    }

    int* refcountPtr;
    T* arrayPtr;
};

template<class T>
struct Array2D
{
    T* data;
    int area;
    int w, h;
    ci::Vec2i Size() const { return ci::Vec2i(w, h); }
    ArrayDeleter<T> deleter;

    Array2D(Vec2i s) : deleter(Init(s.x, s.y)) { }
    Array2D() : deleter(Init(0, 0)) { }

    T* begin() { return data; }
    T* end() { return data+w*h; }

    T& operator()(Vec2i const& v) { return data[v.y*w+v.x]; }

private:
    T* Init(int w, int h) {
        data = (T*)fftwf_malloc(w * h * sizeof(T));
        area = w * h;
        this->w = w;
        this->h = h;
        return data;
    }
};

Array2D<Complexf> fft(Array2D<float> in)
{
    Array2D<Complexf> in_complex(in.Size());
    forxy(in)
    {
        in_complex(p) = Complexf(in(p));
    }

    Array2D<Complexf> result(in.Size());

    auto plan = fftwf_plan_dft_2d(in.h, in.w,
        (fftwf_complex*)in_complex.data, (fftwf_complex*)result.data, FFTW_FORWARD, FFTW_MEASURE);
    fftwf_execute(plan);
    auto mul = 1.0f / sqrt((float)result.area);
    forxy(result)
    {
        result(p) *= mul;
    }
    return result;
}

Array2D<float> ifft(Array2D<Complexf> in)
{
    Array2D<Complexf> result(in.Size());
    auto plan = fftwf_plan_dft_2d(in.h, in.w,
        (fftwf_complex*)in.data, (fftwf_complex*)result.data, FFTW_BACKWARD, FFTW_MEASURE);
    fftwf_execute(plan);

    Array2D<float> out_real(in.Size());
    forxy(in)
    {
        out_real(p) = result(p).real();
    }
    auto mul = 1.0f / sqrt((float)out_real.area);
    forxy(out_real)
    {
        out_real(p) *= mul;
    }
    return out_real;
}

gl::Texture uploadTex(Array2D<float> a)
{
    gl::Texture tex(a.w, a.h);
    tex.bind();
    glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, a.w, a.h, GL_LUMINANCE, GL_FLOAT, a.data);
    return tex;
}

struct SApp : ci::app::AppBasic {
    gl::Texture texSource;
    gl::Texture texbackAndForthed;
    void setup()
    {
        createConsole();

        Array2D<float> source(Vec2i(400, 400));
        forxy(source) {
            float dist = p.distance(source.Size() / 2);
            if(dist < 100)
                source(p) = 1.0f;
            else
                source(p) = 0.0f;
        }
        printSum("source", source);
        texSource = uploadTex(source);
        setWindowSize(source.w, source.h);
        auto backAndForthed = backAndForth(source);
        printSum("backAndForthed", backAndForthed);
        //backAndForthed = backAndForth(loaded);
        texbackAndForthed = uploadTex(backAndForthed);
    }
    void printSum(std::string description, Array2D<float> arr) {
        float sum = std::accumulate(arr.begin(), arr.end(), 0.0f);
        std::cout << "array '" << description << "' has sum " << sum << std::endl;
    }
    void draw()
    {
        gl::clear(Color(0, 0, 0));
        gl::draw(texSource, Rectf(0,0, getWindowWidth() / 2, getWindowHeight() /2));
        gl::draw(texbackAndForthed, Rectf(getWindowWidth() / 2, getWindowWidth() / 2, getWindowWidth(), getWindowHeight()));
    }
    Array2D<float> backAndForth(Array2D<float> in) {
        auto inFd = fft(in);
        auto inResult = ifft(inFd);
        return inResult;
    }
};

CINDER_APP_BASIC(SApp, ci::app::RendererGl)

precompiled.h

#include <complex>
#include <cinder/app/AppBasic.h>
#include <cinder/gl/Texture.h>
#include <cinder/gl/gl.h>
#include <cinder/Vector.h>
#include <fftw3.h>
#include <numeric>

控制台输出:

array 'source' has sum 31397
array 'backAndForthed' has sum -0.110077

图形输出:

screenshot

如您所见,右下方的圆圈有点暗且渐变。

注意:如果取消注释第二条backAndForthed = backAndForth(loaded);行,结果是正确的(因此,结果只是第一次出错)。

1 个答案:

答案 0 :(得分:2)

问题在于:

auto plan = fftwf_plan_dft_2d(in.h, in.w,
    (fftwf_complex*)in_complex.data, (fftwf_complex*)result.data,
     FFTW_FORWARD, FFTW_MEASURE);
fftwf_execute(plan);

然后:

auto plan = fftwf_plan_dft_2d(in.h, in.w,
    (fftwf_complex*)in.data, (fftwf_complex*)result.data,
    FFTW_BACKWARD, FFTW_MEASURE);
fftwf_execute(plan);

使用标志FFTW_MEASURE意味着FFTW尝试许多DFT算法来选择最快的算法。问题是输入数组in.data在途中被覆盖。因此,在fftwf_execute(plan);之后,result.data不是in.data的DFT,就像创建计划之前的DFT一样。根据{{​​3}}上的FFTW文档:

  

重要提示:计划程序会在计划期间覆盖输入数组,除非已为此问题提供已保存的计划(请参阅Wisdom),因此您应在创建计划后初始化输入数据。唯一的例外是FFTW_ESTIMATEFFTW_WISDOM_ONLY标志,如下所述。

该文档提供了一个解决方案:使用标志FFTW_ESTIMATE可确保在规划期间不会覆盖输入/输出数组。

在这种特殊情况下,使用FFTW_ESTIMATE而不是FFTW_MEASURE预计不会触发计算时间的大幅增加。实际上,在计划创建期间计算了许多DFT,使用FFTW_MEASURE创建fftw_plan将比使用FFTW_ESTIMATE创建慢得多。然而,如果要执行许多相同大小的DFT,则必须使用FFTW_MEASURE为所有人创建计划并存储一次。如有必要,可以应用planner flags

我的猜测是你已经知道r2c和c2r变换,旨在将存储空间和计算时间减少近2倍。