中值滤波算法 C

中值滤波用于在多组数据中取得平均值,过滤异常数据。

算法如下:

/***********************************************************************************************************************
* Function Name: MidAvg_Filter
* @brief  This function gets the middle average of middle values of the results.  
* @param  buf - the pointer of the conversion result
* @param  num - set the numbers of ad conversion result
* @return average
***********************************************************************************************************************/
uint16_t MidAvg_Filter(uint16_t *buf, uint8_t num)
{
    uint8_t i, j;
    uint16_t tmp;
    uint32_t sum;

    /* sort the value from small to large */
    for(i = 0; i < num; i++)
    {
        for(j = 0; j < ((num - 1) - i); j++)
        {
            if(buf[j] > buf[j + 1])
            {
                tmp = buf[j];
                buf[j] = buf[j + 1];
                buf[j + 1] = tmp;
            }
        }
    }

    /* Remove the smallest and largest values, then take the average */
    sum = 0;
    for(i = 2; i < (num - 2); i++)
    {
        sum += buf[i];
    }
    tmp = (uint16_t) (sum / (num - 4));

    return (tmp);
}

 

posted on 2021-01-15 17:16  Milo_lu  阅读(751)  评论(0编辑  收藏  举报

导航