C#函数代码优化

Trent1985
博客专家认证
2012-07-02 01:41:01
请问大家,以下这个函数中的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;
}
}
}
}
...全文
331 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
足球中国 2013-01-24
  • 打赏
  • 举报
回复
byte[] temp = src.PixelBuffer.ToArray(); 这句会不会慢。慢的时候打个stopwatch看看哪个地方慢的优化哪个地方。 一直用xp没用更高版本。不清楚这些个东西。
Trent1985 2012-07-03
  • 打赏
  • 举报
回复
在次求高手阿!!!!
Trent1985 2012-07-03
  • 打赏
  • 举报
回复
求高手阿!!!!!!!
Trent1985 2012-07-02
  • 打赏
  • 举报
回复
中间的不重复吧?是分别计算的R,G,B分量值,还有个A通道没有计算,直接隔过去了
__天涯寻梦 2012-07-02
  • 打赏
  • 举报
回复
中间那一大段的加减乘除有很多重复计算,首先就该优化它们
Trent1985 2012-07-02
  • 打赏
  • 举报
回复
o,BitmapData那个我知道,现在这个是Win8metro上的,没有BitmapData了
Ki1381 2012-07-02
  • 打赏
  • 举报
回复
只用过BitmapData。。。
Trent1985 2012-07-02
  • 打赏
  • 举报
回复
怎么没有人回答哦......
Trent1985 2012-07-02
  • 打赏
  • 举报
回复
此函数实现均值滤波功能,r,g,b的值分别为3*3窗口中除中心象素之外的其他象素和的均值!

110,567

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧