CSHARP生成一个带噪声的实时正弦信号使用Drawing绘制折线图,并使用S-G滤波进行实时处理,处理后的数据使用Drawing绘制折线图
时间: 2023-06-15 16:03:42 浏览: 157
产生正弦波、均匀白噪声、高斯白噪声图形。并分别将 两种噪声叠加在正弦波图形上,绘图
以下是一个C#的示例代码,用于生成带噪声的正弦信号,并用S-G滤波进行实时处理,并使用Drawing绘制折线图。
```csharp
using System;
using System.Drawing;
using System.Windows.Forms;
namespace SGFilterDemo
{
public partial class Form1 : Form
{
private const int N = 200; // 采样点数
private const int M = 5; // S-G滤波器的阶数
private const int L = 21; // S-G滤波器的窗口长度
private double[] x = new double[N]; // 原始信号
private double[] y = new double[N]; // 滤波后的信号
public Form1()
{
InitializeComponent();
// 生成带噪声的正弦信号
Random rand = new Random();
for (int i = 0; i < N; i++)
{
double noise = rand.NextDouble() * 0.1 - 0.05; // 噪声范围在[-0.05, 0.05]
x[i] = Math.Sin(i * Math.PI / 20) + noise;
}
// S-G滤波
double[] c = SGFilter.GetCoefficients(M, L); // 获取滤波器系数
for (int i = L / 2; i < N - L / 2; i++)
{
double sum = 0;
for (int j = 0; j < L; j++)
{
sum += c[j] * x[i - L / 2 + j];
}
y[i] = sum;
}
// 显示原始信号和滤波后的信号
Bitmap bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.White);
Pen pen1 = new Pen(Color.Blue, 1);
Pen pen2 = new Pen(Color.Red, 1);
for (int i = 0; i < N - 1; i++)
{
int x1 = i * pictureBox1.Width / N;
int y1 = pictureBox1.Height / 2 - (int)(x[i] * pictureBox1.Height / 2);
int x2 = (i + 1) * pictureBox1.Width / N;
int y2 = pictureBox1.Height / 2 - (int)(x[i + 1] * pictureBox1.Height / 2);
g.DrawLine(pen1, x1, y1, x2, y2);
y1 = pictureBox1.Height / 2 - (int)(y[i] * pictureBox1.Height / 2);
y2 = pictureBox1.Height / 2 - (int)(y[i + 1] * pictureBox1.Height / 2);
g.DrawLine(pen2, x1, y1, x2, y2);
}
pictureBox1.Image = bmp;
}
}
// S-G滤波器类
public static class SGFilter
{
// 获取S-G滤波器的系数
public static double[] GetCoefficients(int m, int l)
{
double[] c = new double[l];
double[] s = new double[l];
double sum;
int i, j, k;
if (l < m + 1)
{
throw new ArgumentException("窗口长度应大于阶数");
}
for (i = 0; i < l; i++)
{
c[i] = 0;
s[i] = 1;
}
for (i = 0; i <= m; i++)
{
sum = s[0];
for (j = 1; j < l; j++)
{
s[j] = s[j - 1] * (i - m + j) / j;
sum += s[j];
}
k = (int)Math.Round((double)(m - i + (l - 1) / 2));
c[k] = s[l - 1] / sum;
}
return c;
}
}
}
```
在窗体上添加一个`PictureBox`控件,并将其大小设置为适当的大小,运行程序即可看到绘制的折线图。
阅读全文