滑动平均滤波器在工程中十分常见,这里用C语言设计一个灵活的滑动滤波器库函数,十分简单易用,并且滤波器不使用for循环,大大减少了代码运行时间。 并且滤波器可以使用malloc自动申请内存,也可以不使用malloc函数,然后自己添加数据cache. 在长度为10000的幅值为1的正弦波上叠加幅值为1均值为0的噪声,滑动窗口为100,效果如下:
代码如下: h文件: #ifndef _SLIDING_AVERAGE_FILTER_H
#define _SLIDING_AVERAGE_FILTER_H
#define SLIDING_AVERAGE_FILTER_USEING_STDLIB 1
typedef struct _sliding_average_filter
{
int w_size;
int head;
float sum;
float *cache;
} SlidAveFilterObj;
void sliding_average_filter_init(SlidAveFilterObj *filter, int w_size);
float sliding_average_filter(SlidAveFilterObj *filter, float k);
int sliding_average_filter_cache_add(SlidAveFilterObj *filter, float *cache, int w_size);
#endif
#include "sliding_average_filter.h"
#ifdef SLIDING_AVERAGE_FILTER_USEING_STDLIB
#include <stdlib.h>
#include <string.h>
#endif
void sliding_average_filter_init(SlidAveFilterObj *filter, int w_size)
{
#ifdef SLIDING_AVERAGE_FILTER_USEING_STDLIB
filter->cache = (float*)malloc(sizeof(float) * w_size);
memset(filter->cache, 0, sizeof(float) * w_size);
#endif
filter->w_size = w_size;
filter->sum = 0;
filter->head = 0;
}
float sliding_average_filter(SlidAveFilterObj *filter, float k)
{
filter->cache[filter->head] = k;
filter->head = (filter->head + 1) % filter->w_size;
filter->sum = filter->sum + k - filter->cache[filter->head];
return (filter->sum / (float)filter->w_size);
}
int sliding_average_filter_cache_add(SlidAveFilterObj *filter, float *cache, int w_size)
{
filter->cache = cache;
filter->w_size = w_size;
return 0;
}
|