C#WPF getpixel非常慢 [英] C# WPF getpixel is very slow

查看:225
本文介绍了C#WPF getpixel非常慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨 我想在WPF中处理图像
除了以下内容外,我没有其他方法可以应用getpixel函数:

public Color GetPixel(BitmapSource bitmap, int x, int y)
{
    CroppedBitmap cb = new CroppedBitmap(bitmap, new Int32Rect(x, y, 1, 1));
    byte[] pixel = new byte[bitmap.Format.BitsPerPixel / 8];
    cb.CopyPixels(pixel, bitmap.Format.BitsPerPixel / 8, 0);
    return Color.FromRgb(pixel[2], pixel[1], pixel[0]);
}


但是由于此函数在循环内运行,因此非常慢.

解决方案

我建​​议您采用另一种方法,而不要使用调用函数的循环,每次都在其中复制图片的一部分,因为这有很大的开销.

我建议的方法是,首先将整个数据复制到一个数组中,而不是一次复制一个像素.然后在循环中,索引到数组中以获取颜色.

我建议您不要理h hzawary的解决方案,您将永远使用不安全代码的唯一原因是因为您有一个需要它的第三方库.而且该库的设计也很差,因此您不应该选择以:)开头的库.您会发现一系列文章,展示了如何在不使用GetPixel的情况下直接访问位图数据.


我也非常研究此问题,找到了此链接:
wpf-image-processing

Hi I want to process an image in WPF
I found no way to apply getpixel function except for:

public Color GetPixel(BitmapSource bitmap, int x, int y)
{
    CroppedBitmap cb = new CroppedBitmap(bitmap, new Int32Rect(x, y, 1, 1));
    byte[] pixel = new byte[bitmap.Format.BitsPerPixel / 8];
    cb.CopyPixels(pixel, bitmap.Format.BitsPerPixel / 8, 0);
    return Color.FromRgb(pixel[2], pixel[1], pixel[0]);
}


but since this function is run inside a loop it is very slow.
is there any way to make it fast?

解决方案

I suggest you take another approach instead of having a loop that calls your function, where you each and every time copy the part of your image, as this has a massive overhead.

The approach I would suggest is that you start by copying the entire data to an array, not just one pixel at a time. And then in your loop you index into your array to get the color.

The solution by hzawary I suggest you disregard, the only reason you''ll ever use unsafe code would be because you had a 3rd party library which required it. And that library would then also be poorly designed so you shouldn''t choose it to start with :)


Search the articles for "Image processing for dummies". You''ll find a series of articles that demonstrates how to access the Bitmap data directly, without using GetPixel.


I also very research for this problem that find this link:
wpf-image-processing


这篇关于C#WPF getpixel非常慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆