Savitzky-Golay滤波算法

 //Savitzky-Golay滤波算法纯C#的实现,本人写的代码,不简洁你来打我

SavitzkyGolay sg = new SavitzkyGolay(3);

//单点平滑/实时平滑

double result = sg.Smooth(doublelist);//count==this.Coefficient.Length

//曲线平滑

double[] result = sg.Smooth(double[]);

/***************************
* Savitzky Golay filter 
* E-Mail: w@sfox.cn
***************************/


using System;
using System.Collections.Generic;

public class SavitzkyGolay
{

    /// <summary>
    /// 滤波系数
    /// </summary>
    public double[] Coefficient { get; private set; }
    /// <summary>
    /// 构造梯度滤波器
    /// </summary>
    /// <param name="m">半步宽(m>0,m越大,平滑度越大)</param>
    public SavitzkyGolay(int m = 2)
    {
        this.SetCoefficient(m);
    }
    /// <summary>
    /// 设置滤波系数
    /// </summary>
    /// <param name="m">半步宽(m>0,m越大,平滑度越大)</param>
    public void SetCoefficient(int m)
    {
        List<double> result = new List<double>();
        int w = m * 2 + 1;
        double W2 = Math.Pow(w, 2);
        double a1 = 15 / (W2 - 4);
        double a2 = (W2 - 1) / 12;
        for (int j = -m; j <= m; j++)
        {
            result.Add((1 + a1 * (a2 - Math.Pow(j, 2))) / w);
        }
        //var ss = result.Select(x1 => x1.ToString()).Aggregate((a, b) => a + " " + b);
        this.Coefficient = result.ToArray();
    }

    /// <summary>
    /// 单点平滑
    /// </summary>
    /// <param name="list">平滑参考点(list.Length 必须等于 this.Coefficient.Length)</param>
    /// <returns></returns>
    public double Smooth(List<double> list)
    {
        double result = 0;
        for (int i = 0; i < this.Coefficient.Length; i++)
        {
            result += this.Coefficient[i] * list[i];
        }
        return result;
    }

    /// <summary>
    /// 曲线平滑
    /// </summary>
    /// <param name="curve">曲线</param>
    /// <returns></returns>
    public double[] Smoothes(double[] curve)
    {

        int length = curve.Length;
        double[] result = new double[length];//Result cache
        int k = this.Coefficient.Length / 2;
        //this.SetCoefficient(w);//Savitzky Golay Filter Coefficient
        Array.Copy(curve, result, k);//Fill head

        for (int i = k; i < length - k; i++)
        {
            List<double> list = new List<double>();//Smooth list
            for (int j = i - k; j <= i + k; j++)
            {
                list.Add(curve[j]);
            }
            result[i] = this.Smooth(list);//Single point smooth
        }

        Array.Copy(curve, length - k, result, length - k, k);//Fill Tail
        return result;
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值