没有GetPixel的索引8bpp图像和像素阵列

时间:2018-07-11 06:07:38

标签: c# alpha getpixel indexed

我需要获取调色板中位图每个像素的索引(我有一个索引的8bpp图像)。现在,我使用以下方式:

List<byte> data = new List<byte>(); // indexes
List<Color> pixels = bitmap.Palette.Entries.ToList(); // palette

for (int i = 0; i <bitmap.Height; i++)
    for (int j = 0; j < bitmap.Width; j++)
        data.Add((byte)pixels[k].IndexOf(bitmap.GetPixel(j, i)));

但是这种方式非常缓慢,因为我使用了几张高分辨率图像。

我的问题是:

1)有没有一种方法可以加快循环过程以获得每个像素的RGBA值?

2)也许有一种更优化的方法来获取调色板中图像的颜色索引?

已解决: 参见TheGeneral的帖子。

2 个答案:

答案 0 :(得分:3)

也许这样会更快。 GetbitsSetbits的推理非常慢,每个内部调用锁位来锁定内部存储器。最好一次完成所有操作

使用LockBitsunsafefixedDictionary

为了测试结果,我使用了这张图片

来自

我根据原始版本测试了结果,并且结果相同

基准

----------------------------------------------------------------------------
Mode             : Release (64Bit)
Test Framework   : .NET Framework 4.7.1 (CLR 4.0.30319.42000)
----------------------------------------------------------------------------
Operating System : Microsoft Windows 10 Pro
Version          : 10.0.17134
----------------------------------------------------------------------------
CPU Name         : Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz
Description      : Intel64 Family 6 Model 42 Stepping 7
Cores (Threads)  : 4 (8)      : Architecture  : x64
Clock Speed      : 3401 MHz   : Bus Speed     : 100 MHz
L2Cache          : 1 MB       : L3Cache       : 8 MB
----------------------------------------------------------------------------

测试1

--- Random Set ------------------------------------------------------------
| Value    |   Average |   Fastest |    Cycles | Garbage | Test |    Gain |
--- Scale 1 ------------------------------------------------ Time 8.894 ---
| Mine1    |  5.211 ms |  4.913 ms |  17.713 M | 0.000 B | Pass | 93.50 % |
| Original | 80.107 ms | 75.131 ms | 272.423 M | 0.000 B | Base |  0.00 % |
---------------------------------------------------------------------------

完整代码

public unsafe byte[] Convert(string input)
{
   using (var bmp = new Bitmap(input))
   {
      var pixels = bmp.Palette.Entries.Select((color, i) => new {x = color,i})
                                      .ToDictionary(arg => arg.x.ToArgb(), x => x.i);

      // lock the image data for direct access
      var bits = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppPArgb);


      // create array as we know the size
      var data = new byte[bmp.Height * bmp.Width];

      // pin the data array
      fixed (byte* pData = data)
      {
         // just getting a pointer we can increment
         var d = pData;

         // store the max length so we don't have to recalculate it
         var length = (int*)bits.Scan0 + bmp.Height * bmp.Width;

         // Iterate through the scanlines of the image as contiguous memory by pointer 
         for (var p = (int*)bits.Scan0; p < length; p++, d++)

            //the magic, get the pixel, lookup the Dict, assign the values
            *d = (byte)pixels[*p];
      }

      // unlock the bitmap
      bmp.UnlockBits(bits);
      return data;
   }
}

摘要

无论如何我都不是图像专家,如果这不起作用,可能是您不理解的索引图像有所不同

更新

要检查像素格式以及是否有调色板,可以使用以下

bmp.PixelFormat
bmp.Palette.Entries.Any()

Update2

Vlad i Slav 的工作解决方案如下

  

我需要将PixelFormat.Format32bppPArgb替换为Format32bppArgb并替换为   添加此检查

if (pixels.ContainsKey(*p)) 
   *d = (byte)pixels[*p];
else 
   *d = 0;. 
  

还需要从调色板中获取不同的值,因为我一直   在此处给出一些错误。

答案 1 :(得分:1)

如果您预先检查pixelformat并确定它是PixelFormat.Format8bppIndexed,则可以在bmp.PixelFormat调用中使用LockBits,并获得 real 像素值直接。如果调色板包含重复的颜色,这也可以避免获得错误的索引。

不过,您确实要大步向前; .Net中图像中每行的字节长度为rounded up to the next multiple of 4 bytes。因此,在宽度为386(例如your penguin)的图像上,实际数据为每行 388 个字节。这就是他们所说的“大步前进”。为避免出现此问题,而是获取完全紧凑的数据,请每行复制输入数据,并以实际使用的行数据长度的块为单位,同时将读取的 pointer 向前移动BitmapData对象给出的完整步幅。

最小步长通常计算为(bpp * width + 7) / 8。当然,对于8位图像,这将仅等于宽度,因为它是每个像素1字节,但是我为其编写的函数支持任何位深度,甚至低于8bpp,因此为什么要进行该计算。

完整功能:

/// <summary>
/// Gets the raw bytes from an image.
/// </summary>
/// <param name="sourceImage">The image to get the bytes from.</param>
/// <param name="stride">Stride of the retrieved image data.</param>
/// <param name="collapseStride">Collapse the stride to the minimum required for the image data.</param>
/// <returns>The raw bytes of the image.</returns>
public static Byte[] GetImageData(Bitmap sourceImage, out Int32 stride, Boolean collapseStride)
{
    if (sourceImage == null)
        throw new ArgumentNullException("sourceImage", "Source image is null!");
    Int32 width = sourceImage.Width;
    Int32 height = sourceImage.Height;
    BitmapData sourceData = sourceImage.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, sourceImage.PixelFormat);
    stride = sourceData.Stride;
    Byte[] data;
    if (collapseStride)
    {
        Int32 actualDataWidth = ((Image.GetPixelFormatSize(sourceImage.PixelFormat) * width) + 7) / 8;
        Int64 sourcePos = sourceData.Scan0.ToInt64();
        Int32 destPos = 0;
        data = new Byte[actualDataWidth * height];
        for (Int32 y = 0; y < height; ++y)
        {
            Marshal.Copy(new IntPtr(sourcePos), data, destPos, actualDataWidth);
            sourcePos += stride;
            destPos += actualDataWidth;
        }
        stride = actualDataWidth;
    }
    else
    {
        data = new Byte[stride * height];
        Marshal.Copy(sourceData.Scan0, data, 0, data.Length);
    }
    sourceImage.UnlockBits(sourceData);
    return data;
}

在您的情况下,可以这样简单地称呼它:

if (image.PixelFormat == PixelFormat.Format8bppIndexed)
{
    Int32 stride;
    Byte[] rawData = GetImageData(image, out stride, image.PixelFormat, true);
    // ... do whatever you want with that image data.
}

请注意,正如我在对另一个答案的评论中所说,.Net框架有一个错误,该错误会阻止将包含调色板透明度信息的8位PNG图像正确地加载为8位。要解决该问题,请查看以下答案:

A: How to read 8-bit PNG image as 8-bit PNG image only?