private void button2_Click(object sender, RoutedEventArgs e)
{
WriteableBitmap writeableBitmap = new WriteableBitmap(bitmapImage);
int startTime = Environment.TickCount;
int width = bitmapImage.PixelWidth;
int height = bitmapImage.PixelHeight;
int stride = width * ((bitmapImage.Format.BitsPerPixel + 7) / 8);
byte[] pixel = new byte[height * stride];
writeableBitmap.CopyPixels(pixel, stride, 0);
Parallel.For(0, height, y =>
{
int x;
for (x = 0; x < stride; x++)
{
pixel[x + y * stride] = (byte)(255 - pixel[x + y * stride]);
}
});
writeableBitmap.WritePixels(new Int32Rect(0, 0, width, height), pixel, stride, 0);
image1.Source = writeableBitmap;
this.Title =(Environment.TickCount - startTime) + " ms";
//CroppedBitmap
}
這是WPF對影像做顏色反轉的程式,使用CopyPixels取得每一點的BGRA的byte array之後,用Parallel.For(平行For)進行反轉RGB顏色,然後用WritePixels把處理完後的BGRA array寫回去,然後使用image1顯示出來。
下圖為使用各種方式對影像進行RGB讀寫並反轉色彩,所消耗的時間測試的結果。
(使用Bitmap類別中的GetPixel與SetPixel方法)
(使用unsafe 指標直接進行讀寫)
(使用Parallel.For搭配unsafe指標進行平行直接讀寫)
(使用WPF的WriteableBitmap類別的CopyPixels與WirtePixels進行讀寫)
※ 在unsafe Parallel.For 與WPF的時間是第二次的結果,第一次的時間跟使用unsafe的結果相去不遠,反而還比較慢,可能是Parallel.for與WPF在第一次使用時初始化的成本比較高所造成的。
文章標籤
全站熱搜

您好: 測試用Source Code下載的下載連結,似乎已經掛了,可不可以請您再上傳一次? 因為需要用unsafe來加快影像處理的速度,想參考您的code,非常感謝!!
您好,連結已更新