原文:
Win8 Metro(C#)数字图像处理--2.70修正后的阿尔法滤波器
/// <summary>
/// Alpha filter.
/// </summary>
/// <param name="src">The source image.</param>
/// <param name="tNumber">One parameter set from 0 to 9.</param>
/// <returns></returns>
public static WriteableBitmap AlphaFilterProcess(WriteableBitmap src, int tNumber)修正的阿尔法滤波器
{
if (src != null)
{
int w = src.PixelWidth;
int h = src.PixelHeight;
WriteableBitmap filterImage = new WriteableBitmap(w, h);
byte[] temp = src.PixelBuffer.ToArray();
byte[] tempMask = (byte[])temp.Clone();
double[] Gray = new double[9];
double gray = 255;
int tempr = 0, tempb = 0, tempg = 0;
for (int j = 1; j < h - 1; j++)
{
for (int i = 1; i < w - 1; i++)
{
tempb = 0;
tempg = 0;
tempr = 0;
int[] B = new int[9] { tempMask[i * 4 + j * w * 4], tempMask[(i - 1) * 4 + (j - 1) * w * 4], tempMask[i * 4 + (j - 1) * w * 4], tempMask[(i + 1) * 4 + (j - 1) * w * 4], tempMask[(i - 1) * 4 + j * w * 4], tempMask[(i + 1) * 4 + j * w * 4], tempMask[(i - 1) * 4 + (j + 1) * w * 4], tempMask[i * 4 + (j + 1) * w * 4], tempMask[(i + 1) * 4 + (j + 1) * w * 4] };
int[] G = new int[9] { tempMask[i * 4 + 1 + j * w * 4], tempMask[(i - 1) * 4 + 1 + (j - 1) * w * 4], tempMask[i * 4 + 1 + (j - 1) * w * 4], tempMask[(i + 1) * 4 + 1 + (j - 1) * w * 4], tempMask[(i - 1) * 4 + 1 + j * w * 4], tempMask[(i + 1) * 4 + 1 + j * w * 4], tempMask[(i - 1) * 4 + 1 + (j + 1) * w * 4], tempMask[i * 4 + 1 + (j + 1) * w * 4], tempMask[(i + 1) * 4 + 1 + (j + 1) * w * 4] };
int[] R = new int[9] { tempMask[i * 4 + 2 + j * w * 4], tempMask[(i - 1) * 4 + 2 + (j - 1) * w * 4], tempMask[i * 4 + 2 + (j - 1) * w * 4], tempMask[(i + 1) * 4 + 2 + (j - 1) * w * 4], tempMask[(i - 1) * 4 + 2 + j * w * 4], tempMask[(i + 1) * 4 + 2 + j * w * 4], tempMask[(i - 1) * 4 + 2 + (j + 1) * w * 4], tempMask[i * 4 + 2 + (j + 1) * w * 4], tempMask[(i + 1) * 4 + 2 + (j + 1) * w * 4] };
for (int n = 0; n < 9; n++)
{
Gray[n] = (double)B[n] * 0.114 + (double)G[n] * 0.587 + (double)R[n] * 0.299;
}
for (int x = 0; x < 9; x++)
{
for (int y = x + 1; y < 9; y++)
{
gray = Gray[x];
tempb = B[x];
tempg = G[x];
tempr = R[x];
if (Gray[x] > Gray[y])
{
Gray[x] = Gray[y];
Gray[y] = gray;
B[x] = B[y];
G[x] = G[y];
R[x] = R[y];
B[y] = tempb;
G[y] = tempg;
R[y] = tempr;
}
}
}
if (tNumber < 0 || tNumber > 8) return null;
tNumber = (tNumber % 2 == 0 ? tNumber : tNumber - 1);
for (int m = 0; m < (int)(tNumber / 2); m++)
{
R[m] = 0;
G[m] = 0;
B[m] = 0;
R[8 - m] = 0;
G[8 - m] = 0;
B[8 - m] = 0;
}
temp[i * 4 + j * w * 4] = (byte)(B.Sum() / (9 - tNumber));
temp[i * 4 + 1 + j * w * 4] = (byte)(G.Sum() / (9 - tNumber));
temp[i * 4 + 2 + j * w * 4] = (byte)(R.Sum() / (9 - tNumber));
}
}
Stream sTemp = filterImage.PixelBuffer.AsStream();
sTemp.Seek(0, SeekOrigin.Begin);
sTemp.Write(temp, 0, w * 4 * h);
return filterImage;
}
else
{
return null;
}
}