Skip to content

Instantly share code, notes, and snippets.

@mckelvin
Created February 22, 2013 05:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mckelvin/5011025 to your computer and use it in GitHub Desktop.
Save mckelvin/5011025 to your computer and use it in GitHub Desktop.
// 中值滤波优化理
// 仅对灰度处于dgGrayValue~dgGrayValue2的点进行处
public static Bitmap medianFilter(Bitmap bmp, int dgGrayValue, int dgGrayValue2)
{
Bitmap bmpobj = new Bitmap(bmp);
int x, y;
byte[] p = new byte[9]; //最小处理窗口3*3
byte s;
int i, j;
for (y = 1; y < bmpobj.Height - 1; y++) //排除边框
{
for (x = 1; x < bmpobj.Width - 1; x++)
{
if (!(bmpobj.GetPixel(x, y).R >= dgGrayValue && bmpobj.GetPixel(x, y).R <= dgGrayValue2))
continue;
//取9个点的值
p[0] = bmpobj.GetPixel(x - 1, y - 1).R;
p[1][1] = bmpobj.GetPixel(x, y - 1).R;
p[2][2] = bmpobj.GetPixel(x + 1, y - 1).R;
p[3] = bmpobj.GetPixel(x - 1, y).R;
p[4] = bmpobj.GetPixel(x, y).R;
p[5] = bmpobj.GetPixel(x + 1, y).R;
p[6] = bmpobj.GetPixel(x - 1, y + 1).R;
p[7] = bmpobj.GetPixel(x, y + 1).R;
p[8] = bmpobj.GetPixel(x + 1, y + 1).R;
//计算中值
for (j = 0; j < 5; j++)
{
for (i = j + 1; i < 9; i++)
{
if (p[j] > p[i])
{
s = p[j];
p[j] = p[i];
p[i] = s;
}
}
}
bmpobj.SetPixel(x, y, Color.FromArgb(p[4], p[4], p[4])); //中值 p4
}
}
return bmpobj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment