1.均值滤波
#include <iostream>
#include <vector>
#include <numeric>
class MovingAverageFilter {
public:
MovingAverageFilter(size_t windowSize) : windowSize(windowSize) {}
double filter(double newValue) {
if (values.size() >= windowSize) {
values.erase(values.begin());
}
values.push_back(newValue);
double sum = std::accumulate(values.begin(), values.end(), 0.0);
return sum / values.size();
}
private:
size_t windowSize;
std::vector<double> values;
};
int main() {
MovingAverageFilter filter(5); // 窗口大小为5
double rawData[] = {100, 200, 150, 300, 250, 400, 350, 450};
for (double value : rawData) {
double filteredValue = filter.filter(value);
std::cout << "Filtered Value: " << filteredValue << std::endl;
}
return 0;
}
2.指数平滑滤波
#include <iostream>
#include <vector>
class ExponentialSmoothingFilter {
public:
ExponentialSmoothingFilter(double alpha) : alpha(alpha), smoothedValue(0), initialized(false) {}
double filter(double newValue) {
if (!initialized) {
smoothedValue = newValue;
initialized = true;
}
else {
smoothedValue = alpha * newValue + (1 - alpha) * smoothedValue;
}
return smoothedValue;
}
private:
double alpha; // 平滑因子,0到1之间
double smoothedValue;
bool initialized;
};
int main() {
ExponentialSmoothingFilter filter(1); // 平滑因子为1
std::vector<int> rawData(4096);
int temp1 = 2000;
int temp2 = 4096;
for (size_t i = 0; i < rawData.size(); ++i)
{
if (i < 2000)
{
temp1 = temp1 - 1;
rawData[i] = temp1;
}
else if(i == 2000)
{
temp1 = 0;
rawData[i] = temp1;
}
else
{
temp2 = temp2 - 1;
rawData[i] = temp2;
}
}
for (size_t i = 0; i < rawData.size(); ++i)
{
int filteredValue = filter.filter(rawData[i]);
std::cout << i << "Filtered Value: " << filteredValue << std::endl;
}
return 0;
}
3.卡尔曼滤波
class KalmanFilter {
public:
KalmanFilter(double processNoise, double measurementNoise, double estimationError, double initialValue)
: processNoise(processNoise), measurementNoise(measurementNoise),
estimationError(estimationError), currentEstimate(initialValue) {}
double filter(double measurement) {
// Prediction update
double prioriEstimate = currentEstimate;
double prioriError = estimationError + processNoise;
// Measurement update
double gain = prioriError / (prioriError + measurementNoise);
currentEstimate = prioriEstimate + gain * (measurement - prioriEstimate);
estimationError = (1 - gain) * prioriError;
return currentEstimate;
}
private:
double processNoise;
double measurementNoise;
double estimationError;
double currentEstimate;
};
int main() {
KalmanFilter filter(1, 1, 1, 0); // 过程噪声、测量噪声、估计误差和初始值
double rawData[] = {100, 200, 150, 300, 250, 400, 350, 450};
for (double value : rawData) {
double filteredValue = filter.filter(value);
std::cout << "Filtered Value: " << filteredValue << std::endl;
}
return 0;
}