我有用python编写的代码。它利用numpy计算实际输入的FFT的正部分。我需要将这段代码移植到C++。
import numpy as np
interp=[131.107, 133.089, 132.199, 129.905, 132.977]
res=np.fft.rfft(interp)
print res
结果为659.27700000+0.j,1.27932533-1.4548977j,-3.15032533+2.1158917j。
我尝试使用OpenCV进行一维DFT:
std::vector<double> fft;
std::vector<double> interpolated = {131.107, 133.089, 132.199, 129.905, 132.977};
cv::dft( interpolated, fft );
for( auto it = fft.begin(); it != fft.end(); ++it ) {
std::cout << *it << ' ';
}
std::cout << std::endl;
cv::dft为{1.42109e-14,-127.718,-94.705,6.26856,23.0231}。它与numpy.fft.rfft有很大的不同。看起来奇怪的是,在OpenCV的dft计算之后,所有输入的DC值(零元素)都接近于零。
FFTW3库的使用给我的结果与OpenCV的结果相同:
std::vector<double> interpolated = {131.107, 133.089, 132.199, 129.905, 132.977};
fftw_complex* out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * 3 );
fftw_plan plan = fftw_plan_dft_r2c_1d( interpolated.size( ), interpolated.data( ), out, FFTW_ESTIMATE );
fftw_execute(plan);
fftw_destroy_plan(plan);
for( size_t i = 0; i < interpolated.size( ); ++i ) {
std::cout << " (" << out[ i ][ 0 ] << ", " << out[ i ][ 1 ] << ")";
}
fftw_free(out);
这段代码给出了与OpenCV相同的结果。打印:(1.42109e-14,0) (-127.718,-94.705) (6.26856,23.0231)。
为什么我在C++和python中得到不同的dft结果?我做错了什么?
谢谢!
发布于 2014-01-22 20:41:42
目前我使用的是gcc 4.6,它没有C++11,所以我尝试了这个版本的代码,使用OpenCV 2.4.8:
#include <iostream>
#include "opencv2/core/core.hpp"
int main(int argc, char *argv[])
{
double data[] = {131.107, 133.089, 132.199, 129.905, 132.977};
std::vector<double> interpolated (data, data + sizeof(data) / sizeof(double));
std::vector<double> fft;
cv::dft(interpolated, fft);
for (std::vector<double>::const_iterator it = fft.begin(); it != fft.end(); ++it) {
std::cout << *it << ' ';
}
std::cout << std::endl;
}
输出量
659.277 1.27933 -1.4549 -3.15033 2.11589
与numpy和cv2
python模块一致:
In [55]: np.set_printoptions(precision=3)
In [56]: x
Out[56]: array([ 131.107, 133.089, 132.199, 129.905, 132.977])
In [57]: np.fft.rfft(x)
Out[57]: array([ 659.277+0.j , 1.279-1.455j, -3.150+2.116j])
In [58]: cv2.dft(x)
Out[58]:
array([[ 659.277],
[ 1.279],
[ -1.455],
[ -3.15 ],
[ 2.116]])
我不知道为什么您的代码不起作用,所以我想这是一个长篇大论,而不是一个回答。
发布于 2014-01-27 05:19:22
请查一下文件。libfft rfft方法将实际输入的向量转化为复Fourier系数。利用傅里叶系数对实际信号的共轭性,可以给出与输入长度相同的阵列输出。
一般的fft和dft方法将复数向量转化为复系数向量。较早的代码使用双倍数组作为输入和输出,其中复数的实部和虚部交替给定,即一个偶数数组。奇数输入长度发生的情况可能是未记录的行为。
https://stackoverflow.com/questions/21295954
复制相似问题