C#函数代码优化
请问大家,以下这个函数中的unsafe指针处理部分,应该怎样优化,现在这段指针操作耗时9s,速度过慢,请问该如何来缩短耗时!
/// <summary>
/// Mean filter process.
/// </summary>
/// <param name="src">Source image</param>
/// <returns></returns>
public static WriteableBitmap MeanFilterProcess(WriteableBitmap src)////9 均值滤波处理
{
try
{
WriteableBitmap filterImage = new WriteableBitmap(src.PixelWidth, src.PixelHeight);
byte[] temp = src.PixelBuffer.ToArray();
unsafe
{
byte*pDst;
byte r = 0, g = 0, b = 0;
fixed (byte* p = temp)
{
for (int j = 1; j < src.PixelHeight - 1; j++)
{
pDst = p + 4+j*src.PixelWidth*4;
for (int i = 4; i < src.PixelWidth * 4 - 4; i += 4)
{
//pDst
b = (byte)((*(pDst - 4 - src.PixelWidth * 4) + *(pDst - src.PixelWidth * 4) + *(pDst + 4 - src.PixelWidth * 4) +
*(pDst - 4) + *(pDst + 4) + *(pDst - 4 + src.PixelWidth * 4) + *(pDst + src.PixelWidth * 4) + *(pDst + 4 + src.PixelWidth * 4)) / 8);
g = (byte)((*(pDst - 4 - src.PixelWidth * 4 + 1) + *(pDst - src.PixelWidth * 4 + 1) + *(pDst + 4 - src.PixelWidth * 4 + 1) +
*(pDst - 4 + 1) + *(pDst + 4 + 1) + *(pDst - 4 + src.PixelWidth * 4 + 1) + *(pDst + src.PixelWidth * 4 + 1) + *(pDst + 4 + src.PixelWidth * 4 + 1)) / 8);
r = (byte)((*(pDst - 4 - src.PixelWidth * 4 + 2) + *(pDst - src.PixelWidth * 4 + 2) + *(pDst + 4 - src.PixelWidth * 4 + 2) +
*(pDst - 4 + 2) + *(pDst + 4 + 2) + *(pDst - 4 + src.PixelWidth * 4 + 2) + *(pDst + src.PixelWidth * 4 + 2) + *(pDst + 4 + src.PixelWidth * 4 + 2)) / 8);
*(pDst) = b;
*(pDst + 1) = g;
*(pDst + 2) = r;
pDst += 4;
}
}
}
}
Stream sTemp = filterImage.PixelBuffer.AsStream();
sTemp.Seek(0, SeekOrigin.Begin);
sTemp.Write(temp, 0, src.PixelWidth * 4 * src.PixelHeight);
return filterImage;
}
catch (Exception e)
{
throw e;
}
}
}
}