using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 测试Scottplot { /*************************** * Savitzky Golay filter * E-Mail: w@sfox.cn ***************************/ public class SavitzkyGolay { /// /// 滤波系数 /// public double[] Coefficient { get; private set; } /// /// 构造梯度滤波器 /// /// 半步宽(m>0,m越大,平滑度越大) public SavitzkyGolay(int m = 2) { this.SetCoefficient(m); } /// /// 设置滤波系数 /// /// 半步宽(m>0,m越大,平滑度越大) public void SetCoefficient(int m) { List result = new List(); 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(); } /// /// 单点平滑 /// /// 平滑参考点(list.Length 必须等于 this.Coefficient.Length) /// public double Smooth(List list) { double result = 0; for (int i = 0; i < this.Coefficient.Length; i++) { result += this.Coefficient[i] * list[i]; } return result; } /// /// 曲线平滑 /// /// 曲线 /// 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 list = new List();//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; } } }