振荡和频谱通过傅立叶变换
问题描述:
我试图找到表示像素的图像中的运动数据的矢量产生的波形的振荡和频谱频率。振荡和频谱通过傅立叶变换
的数据被存储在文本文件,如下所示:
75.000000
60.000000
52.000000
61.000000
66.000000
78.000000
86.000000
74.000000
59.000000
47.000000
58.000000
60.000000
81.000000
85.000000
81.000000
70.000000
58.000000
59.000000
56.000000
61.000000
77.000000
88.000000
82.000000
79.000000
75.000000
75.000000
75.000000
75.000000
76.000000
82.000000
82.000000
的想法是找到振荡(赫兹)和从数据中获得的曲线图的频谱(振幅)的频率,图表的一个例子如下所示。
我已阅读并谈了很多关于使用fftw3库的傅立叶分析,我是新来使用C++和更该库。
我希望你能帮助我的代码或想法来解决我的问题。
非常感谢您的帮助。
我与Microsoft Visual C++ 2010(win32)中工作
代码:
#include "StdAfx.h"
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <fftw3.h>
#include <iostream>
#include <cmath>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
int i;
const int N=100;//Number of points acquired inside the window
double Fs=200;//sampling frequency
double dF=Fs/N;
double T=1/Fs;//sample time
double f=86;//frequency
double *in;
fftw_complex *out;
double ff[N];
fftw_plan plan_forward;
in = (double*) fftw_malloc(sizeof(double) * N);
out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N);
std::ifstream myfile ("Vetor_Oscilacao2.txt");
if (myfile.is_open())
{
std::vector<double> in;
std::string line;
while (std::getline(myfile, line))
{
double value = std::stod(line);
std::cout << value << '\n';
in.push_back(value);
}
myfile.close();
}
else
std::cout << "Unable to open file";
std::cin.get();
for (int i=0; i<= ((N/2)-1);i++)
{
ff[i]=Fs*i/N;
}
plan_forward = fftw_plan_dft_r2c_1d (N, in, out, FFTW_ESTIMATE);
fftw_execute (plan_forward);
double v[N];
for (int i = 0; i<= ((N/2)-1); i++)
{
v[i]=(10*log(sqrt(out[i][0]*out[i][0]+ out[i][1]*out[i][1])))/N; //Here I have calculated the y axis of the spectrum in dB
}
fstream fichero;
fichero.open("example2.txt",fstream::out);
fichero << "plot '-' using 1:2" << std::endl;
for(i = 0;i< ((N/2)-1); i++)
{
fichero << ff[i]<< " " << v[i]<< std::endl;
}
fichero.close();
fftw_destroy_plan (plan_forward);
fftw_free (in);
fftw_free (out);
return 0;
}
答
与您的代码的主要问题是,当你离开的范围变量std::vector<double> in
将被销毁有条件的:if (myfile.is_open())
。
此外,代码没有以任何方式使用代表输入文件中曲线的值,因此如果给出当前布局的代码,代码无法找到振荡频率。
+0
我是新的c + +和fft,抱歉,如果我做一个废话,但我需要做这些数据的变换....可以帮助我一个更简单的解释或想法来完成我所需要的。再次,非常感谢。 –
欢迎使用stackoverflow。这里的想法是,你在问之前努力尝试。那么,到目前为止您尝试过哪些方法?卡住了哪些方面? – Walter
尽量让我的第一次逼近中提供的信息: https://stackoverflow.com/questions/32276728/plotting-frequency-spectrum-with-c 我已经编辑附上到目前为止生成的代码的问题。 我认为输出V [I]的表示是在对数,一些想法,以便它可以被线性地表示? 我不知道如果我在正确的轨道上,我很抱歉,如果我的问题很愚蠢,但我是新的C++。 非常感谢。 –