查找BitmapImage的特定像素颜色

And*_*erd 42 wpf bitmap image-processing

我有一个WPF BitmapImage,我从.JPG文件加载,如下所示:

this.m_image1.Source = new BitmapImage(new Uri(path));
Run Code Online (Sandbox Code Playgroud)

我想查询特定点的颜色.例如,像素(65,32)处的RGB值是多少?

我该怎么做?我采取这种方法:

ImageSource ims = m_image1.Source;
BitmapImage bitmapImage = (BitmapImage)ims;
int height = bitmapImage.PixelHeight;
int width = bitmapImage.PixelWidth;
int nStride = (bitmapImage.PixelWidth * bitmapImage.Format.BitsPerPixel + 7) / 8;
byte[] pixelByteArray = new byte[bitmapImage.PixelHeight * nStride];
bitmapImage.CopyPixels(pixelByteArray, nStride, 0);
Run Code Online (Sandbox Code Playgroud)

虽然我会承认有一些猴子看到,猴子继续这个代码.无论如何,是否有一种直接的方法来处理这个字节数组转换为RGB值?

Ray*_*rns 56

以下是我如何使用多维数组操作C#中的像素:

[StructLayout(LayoutKind.Sequential)]
public struct PixelColor
{
  public byte Blue;
  public byte Green;
  public byte Red;
  public byte Alpha;
}

public PixelColor[,] GetPixels(BitmapSource source)
{
  if(source.Format!=PixelFormats.Bgra32)
    source = new FormatConvertedBitmap(source, PixelFormats.Bgra32, null, 0);

  int width = source.PixelWidth;
  int height = source.PixelHeight;
  PixelColor[,] result = new PixelColor[width, height];

  source.CopyPixels(result, width * 4, 0);
  return result;
}
Run Code Online (Sandbox Code Playgroud)

用法:

var pixels = GetPixels(image);
if(pixels[7, 3].Red > 4)
  ...
Run Code Online (Sandbox Code Playgroud)

如果你想更新像素,非常相似的代码可以工作,除非你要创建一个WritableBitmap,并使用它:

public void PutPixels(WritableBitmap bitmap, PixelColor[,] pixels, int x, int y)
{
  int width = pixels.GetLength(0);
  int height = pixels.GetLength(1);
  bitmap.WritePixels(new Int32Rect(0, 0, width, height), pixels, width*4, x, y);
}
Run Code Online (Sandbox Code Playgroud)

正是如此:

var pixels = new PixelColor[4, 3];
pixel[2,2] = new PixelColor { Red=128, Blue=0, Green=255, Alpha=255 };

PutPixels(bitmap, pixels, 7, 7);
Run Code Online (Sandbox Code Playgroud)

请注意,如果位图以不同的格式到达,则此代码会将位图转换为Bgra32.这通常很快,但在某些情况下可能是性能瓶颈,在这种情况下,将修改此技术以更密切地匹配基础输入格式.

更新

由于BitmapSource.CopyPixels不接受二维数组,因此有必要在一维和二维之间转换数组.以下扩展方法应该可以解决这个问题:

public static class BitmapSourceHelper
{
#if UNSAFE
  public unsafe static void CopyPixels(this BitmapSource source, PixelColor[,] pixels, int stride, int offset)
  {
    fixed(PixelColor* buffer = &pixels[0, 0])
      source.CopyPixels(
        new Int32Rect(0, 0, source.PixelWidth, source.PixelHeight),
        (IntPtr)(buffer + offset),
        pixels.GetLength(0) * pixels.GetLength(1) * sizeof(PixelColor),
        stride);
  }
#else
  public static void CopyPixels(this BitmapSource source, PixelColor[,] pixels, int stride, int offset)
  {
    var height = source.PixelHeight;
    var width = source.PixelWidth;
    var pixelBytes = new byte[height * width * 4];
    source.CopyPixels(pixelBytes, stride, 0);
    int y0 = offset / width;
    int x0 = offset - width * y0;
    for(int y=0; y<height; y++)
      for(int x=0; x<width; x++)
        pixels[x+x0, y+y0] = new PixelColor
        {
          Blue  = pixelBytes[(y*width + x) * 4 + 0],
          Green = pixelBytes[(y*width + x) * 4 + 1],
          Red   = pixelBytes[(y*width + x) * 4 + 2],
          Alpha = pixelBytes[(y*width + x) * 4 + 3],
        };
  }
#endif
}
Run Code Online (Sandbox Code Playgroud)

这里有两个实现:第一个是快速但使用不安全的代码将IntPtr获取到数组(必须使用/ unsafe选项编译).第二个是较慢但不需要不安全的代码.我在我的代码中使用了不安全的版本.

WritePixels接受二维数组,因此不需要扩展方法.

  • 微软开发人员注意:我们不应该只是为了读取WPF中位图文件中像素的值而跳过这么多箍... (7认同)
  • 当我尝试这个时,我得到"输入数组不是有效等级".有任何想法吗? (2认同)

Hab*_*nte 17

我想补充一下Ray的答案,你也可以将PixelColor结构声明为一个联合:

[StructLayout(LayoutKind.Explicit)]
public struct PixelColor
{
    // 32 bit BGRA 
    [FieldOffset(0)] public UInt32 ColorBGRA;
    // 8 bit components
    [FieldOffset(0)] public byte Blue;
    [FieldOffset(1)] public byte Green;
    [FieldOffset(2)] public byte Red;
    [FieldOffset(3)] public byte Alpha;
}
Run Code Online (Sandbox Code Playgroud)

这样,除了单个字节组件外,您还可以访问UInit32 BGRA(用于快速像素访问或复制).


Mic*_*key 14

结果字节数组的解释取决于源位图的像素格式,但在最简单的32位ARGB图像的情况下,每个像素将由字节数组中的四个字节组成.因此将解释第一个像素:

alpha = pixelByteArray[0];
red   = pixelByteArray[1];
green = pixelByteArray[2];
blue  = pixelByteArray[3];
Run Code Online (Sandbox Code Playgroud)

要处理图像中的每个像素,您可能希望创建嵌套循环来遍历行和列,将索引变量递增每个像素中的字节数.

一些位图类型将多个像素组合成单个字节.例如,单色图像将8个像素打包到每个字节中.如果你需要处理每像素24/32位以外的图像(简单的图像),那么我建议找一本涵盖位图二进制结构的好书.

  • 我不同意.在我看来,对于90%的图像处理需求,C#是比C++更好的选择.C#语言比C++有许多优点,它的"不安全"和"固定"关键字使您可以在需要时直接访问C++位.在大多数情况下,图像处理算法的C#实现速度与C++的速度非常相似,但偶尔会慢得多.我只会在少数情况下使用C++,因为JIT编译器错过了优化,C#的性能很差. (11认同)
  • 谢谢,但是...我觉得.NET框架应该有一些接口可以抽象出所有的编码复杂性.显然,System.Windows.Media库知道如何解码位图,因为它将它呈现给屏幕.我为什么要知道所有的实现细节?我不能利用已经以某种方式实现的渲染逻辑吗? (5认同)
  • 我感觉到你的痛苦.在Windows窗体中,Bitmap类具有GetPixel和SetPixel方法来检索和设置各个像素的值,但这些方法非常慢,除了非常简单的情况外几乎没用.您可以使用RenderTargetBitmap和其他更高级别的对象来创建和合成位图,但在我看来,图像处理最好保留在C++的域中,直接访问位是更合适的.当然,你可以在C#/ .NET中进行图像处理,但根据我的经验,总是感觉就像试图通过一个圆孔放一个方形钉. (2认同)

Bre*_*ent 6

我想改进雷的回答——没有足够的代表来发表评论。>:( 这个版本具有安全/托管的优点,以及不安全版本的效率。另外,我已经取消了传递步幅,因为 CopyPixels 的 .Net 文档说它是位图的步幅,而不是缓冲区的值。这是误导性的,无论如何都可以在函数内部计算。由于 PixelColor 数组必须与位图的步长相同(以便能够作为单个复制调用来完成),因此创建一个新的值是有意义的函数中也包含数组,简单易行。

    public static PixelColor[,] CopyPixels(this BitmapSource source)
    {
        if (source.Format != PixelFormats.Bgra32)
            source = new FormatConvertedBitmap(source, PixelFormats.Bgra32, null, 0);
        PixelColor[,] pixels = new PixelColor[source.PixelWidth, source.PixelHeight];
        int stride = source.PixelWidth * ((source.Format.BitsPerPixel + 7) / 8);
        GCHandle pinnedPixels = GCHandle.Alloc(pixels, GCHandleType.Pinned);
        source.CopyPixels(
          new Int32Rect(0, 0, source.PixelWidth, source.PixelHeight),
          pinnedPixels.AddrOfPinnedObject(),
          pixels.GetLength(0) * pixels.GetLength(1) * 4,
              stride);
        pinnedPixels.Free();
        return pixels;
    }
Run Code Online (Sandbox Code Playgroud)


G.Y*_*G.Y 5

我采用了所有示例并创建了一个稍微好一点的示例 - 也对其进行了测试
(唯一的缺陷是神奇的 96 作为 DPI,这真的让我感到烦恼)

我还比较了这种 WPF 策略与:

  • 使用图形的 GDI (system.drawing)
  • 通过直接从 GDI32.Dll 调用 GetPixel 进行互操作

令我惊讶的是,
这比 GDI 快 10 倍,比 Interop 快 15 倍左右。
因此,如果您使用 WPF - 更好地使用它来获得您的像素颜色。

public static class GraphicsHelpers
{
    public static readonly float DpiX;
    public static readonly float DpiY;

    static GraphicsHelpers()
    {
        using (var g = Graphics.FromHwnd(IntPtr.Zero))
        {
            DpiX = g.DpiX;
            DpiY = g.DpiY;
        }
    }

    public static Color WpfGetPixel(double x, double y, FrameworkElement AssociatedObject)
    {
        var renderTargetBitmap = new RenderTargetBitmap(
            (int)AssociatedObject.ActualWidth,
            (int)AssociatedObject.ActualHeight,
            DpiX, DpiY, PixelFormats.Default);
        renderTargetBitmap.Render(AssociatedObject);

        if (x <= renderTargetBitmap.PixelWidth && y <= renderTargetBitmap.PixelHeight)
        {
            var croppedBitmap = new CroppedBitmap(
                renderTargetBitmap, new Int32Rect((int)x, (int)y, 1, 1));
            var pixels = new byte[4];
            croppedBitmap.CopyPixels(pixels, 4, 0);
            return Color.FromArgb(pixels[3], pixels[2], pixels[1], pixels[0]);
        }
        return Colors.Transparent;
    }
}
Run Code Online (Sandbox Code Playgroud)