C語言簡易均值濾波器

均值濾波器就是取多個連續的數據,進行算術平均運算,得出輸出數據;

爲了簡化運算,本文演示代碼使用2的整數次冪進行算術平均運算,因爲這種情況可以通過移位的方式來代替除法。

以下是濾波器定義的頭文件:

#ifndef __FILTER_H
#define __FILTER_H

struct filter
{
    int buff[32]; //最大支持32級均值,可根據需要改爲更大的值。
    int order;
    int shift;
    int sum;
    int index;
};

typedef struct filter filter_t;

//初始化濾波器,order指定濾波常數,必須是2的N次方(1,2,4,8,16...)
void filter_init(filter_t *flt, int order);

//濾波函數,value輸入待濾波的數據,返回濾波後的數據
int  filter_input(filter_t *flt, int value);

//復位濾波器
void filter_reset(filter_t *flt);

#endif

 

以下是源文件:

/*
* 均值濾波器
* 蔣曉崗<[email protected]>
*/
#include <string.h>
#include "filter.h"

//均值濾波器
int filter_input(filter_t *flt, int value)
{
    flt->sum += value;
    flt->sum -= flt->buff[flt->index];
    flt->buff[flt->index] = value;
    flt->index = (flt->index + 1) & (flt->order - 1);
    return (flt->sum >> flt->shift);
}

//均值濾波器
void filter_init(filter_t *flt, int order)
{
    flt->index = 0;
    flt->sum   = 0;
    flt->order = order;
    flt->shift = 0;
    while(order > 1)
    {
        flt->shift++;
        order >>= 1;
    }
}

//復位
void filter_reset(filter_t *flt)
{
    flt->index = 0;
    flt->sum   = 0;
    memset(flt->buff, 0, sizeof(flt->buff));
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章