对picturebox中的图片进行图像滤波和增强
时间: 2024-03-02 10:50:39 浏览: 19
对于picturebox中的图片进行图像滤波和增强,可以采用以下步骤:
1. 将picturebox中的图片转换为Bitmap对象,可以使用以下代码实现:
```
Bitmap bmp = new Bitmap(pictureBox1.Image);
```
2. 进行图像滤波和增强,可以使用各种图像处理库或自定义算法。以下是一些常用的图像滤波和增强方法:
- 均值滤波
```
for (int i = 1; i < bmp.Width - 1; i++)
{
for (int j = 1; j < bmp.Height - 1; j++)
{
Color c1 = bmp.GetPixel(i - 1, j - 1);
Color c2 = bmp.GetPixel(i, j - 1);
Color c3 = bmp.GetPixel(i + 1, j - 1);
Color c4 = bmp.GetPixel(i - 1, j);
Color c5 = bmp.GetPixel(i, j);
Color c6 = bmp.GetPixel(i + 1, j);
Color c7 = bmp.GetPixel(i - 1, j + 1);
Color c8 = bmp.GetPixel(i, j + 1);
Color c9 = bmp.GetPixel(i + 1, j + 1);
int r = (c1.R + c2.R + c3.R + c4.R + c5.R + c6.R + c7.R + c8.R + c9.R) / 9;
int g = (c1.G + c2.G + c3.G + c4.G + c5.G + c6.G + c7.G + c8.G + c9.G) / 9;
int b = (c1.B + c2.B + c3.B + c4.B + c5.B + c6.B + c7.B + c8.B + c9.B) / 9;
bmp.SetPixel(i, j, Color.FromArgb(r, g, b));
}
}
```
- 中值滤波
```
for (int i = 1; i < bmp.Width - 1; i++)
{
for (int j = 1; j < bmp.Height - 1; j++)
{
List<int> rList = new List<int>();
List<int> gList = new List<int>();
List<int> bList = new List<int>();
for (int x = i - 1; x <= i + 1; x++)
{
for (int y = j - 1; y <= j + 1; y++)
{
Color c = bmp.GetPixel(x, y);
rList.Add(c.R);
gList.Add(c.G);
bList.Add(c.B);
}
}
rList.Sort();
gList.Sort();
bList.Sort();
int r = rList[4];
int g = gList[4];
int b = bList[4];
bmp.SetPixel(i, j, Color.FromArgb(r, g, b));
}
}
```
- 灰度化
```
for (int i = 0; i < bmp.Width; i++)
{
for (int j = 0; j < bmp.Height; j++)
{
Color c = bmp.GetPixel(i, j);
int gray = (int)(c.R * 0.3 + c.G * 0.59 + c.B * 0.11);
bmp.SetPixel(i, j, Color.FromArgb(gray, gray, gray));
}
}
```
- 调整亮度和对比度
```
float brightness = 0.5f; // 亮度增量,范围为-1到1
float contrast = 0.5f; // 对比度增量,范围为-1到1
for (int i = 0; i < bmp.Width; i++)
{
for (int j = 0; j < bmp.Height; j++)
{
Color c = bmp.GetPixel(i, j);
float r = (c.R / 255.0f - 0.5f) * contrast + brightness + 0.5f;
float g = (c.G / 255.0f - 0.5f) * contrast + brightness + 0.5f;
float b = (c.B / 255.0f - 0.5f) * contrast + brightness + 0.5f;
r = Math.Max(0, Math.Min(1, r));
g = Math.Max(0, Math.Min(1, g));
b = Math.Max(0, Math.Min(1, b));
bmp.SetPixel(i, j, Color.FromArgb((int)(r * 255), (int)(g * 255), (int)(b * 255)));
}
}
```
3. 将处理后的Bitmap对象重新设置为picturebox的图像,可以使用以下代码实现:
```
pictureBox1.Image = bmp;
```