将位图转换为8bpp灰度图在C#中输出的结果是8bpp彩色索引。

3
我正在尝试使用下面的代码将位图转换为8bpp灰度图:
private Bitmap ConvertPixelformat(ref Bitmap Bmp)
{
       Bitmap myBitmap = new Bitmap(Bmp);
        // Clone a portion of the Bitmap object.
        Rectangle cloneRect = new Rectangle(0, 0, Bmp.Width, Bmp.Height);
        PixelFormat format = PixelFormat.Format8bppIndexed;
        Bitmap cloneBitmap = myBitmap.Clone(cloneRect, format);
        var pal = cloneBitmap.Palette;

        for (i = 0; i < cloneBitmap.Palette.Entries.Length; ++i)
        {
            var entry = cloneBitmap.Palette.Entries[i];
            var gray = (int)(0.30 * entry.R + 0.59 * entry.G + 0.11 * entry.B);
            pal.Entries[i] = Color.FromArgb(gray, gray, gray);
        }
        cloneBitmap.Palette = pal;
        cloneBitmap.SetResolution(500.0F, 500.0F);
        return cloneBitmap;
}

检查位图图像的属性,发现位深度正确设置为8bpp,但不是灰度而是彩色索引8bpp。请指导如何处理。


1
看起来对吗?不确定你的调色板创建方式是否正确。一个普通的灰度调色板将拥有所有值。如果Clone要有任何机会捕捉到调色板,它必须首先存在。也许你需要DrawImage,但我不太确定。 - TaW
@TaW 是的,需要修改代码以输出灰度8bpp位图。 - hopeforall
1个回答

7

请查看以下代码:

    public static unsafe Bitmap ToGrayscale(Bitmap colorBitmap)
    {
        int Width = colorBitmap.Width;
        int Height = colorBitmap.Height;

        Bitmap grayscaleBitmap = new Bitmap(Width, Height, PixelFormat.Format8bppIndexed);

        grayscaleBitmap.SetResolution(colorBitmap.HorizontalResolution,
                             colorBitmap.VerticalResolution);

        ///////////////////////////////////////
        // Set grayscale palette
        ///////////////////////////////////////
        ColorPalette colorPalette = grayscaleBitmap.Palette;
        for (int i = 0; i < colorPalette.Entries.Length; i++)
        {
            colorPalette.Entries[i] = Color.FromArgb(i, i, i);
        }
        grayscaleBitmap.Palette = colorPalette;
        ///////////////////////////////////////
        // Set grayscale palette
        ///////////////////////////////////////
        BitmapData bitmapData = grayscaleBitmap.LockBits(
            new Rectangle(Point.Empty, grayscaleBitmap.Size),
            ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);

        Byte* pPixel = (Byte*)bitmapData.Scan0;

        for (int y = 0; y < Height; y++)
        {
            for (int x = 0; x < Width; x++)
            {
                Color clr = colorBitmap.GetPixel(x, y);

                Byte byPixel = (byte)((30 * clr.R + 59 * clr.G + 11 * clr.B) / 100);

                pPixel[x] = byPixel;
            }

            pPixel += bitmapData.Stride;
        }

        grayscaleBitmap.UnlockBits(bitmapData);

        return grayscaleBitmap;
    }

这段代码将彩色图像转换为灰度图像。


8bpp可以完美地非灰度化...实际上,在System.Drawing中并没有特定的类型用于“灰度8bpp”。这完全取决于颜色调色板,而您的代码特别设置为灰色。 - Nyerguds
@Nyerguds,请向我展示如何创建一张 Lena 的 8bpp 彩色图像。 - user366312
唯一需要注意的是得到一个好的调色板,通常使用K-means聚类方法完成(这是我最想研究但一直没有时间去做的事情。不过有很多其他方法可供选择)。一旦你得到了它,你只需要使用笛卡尔距离将图像像素匹配到其最近的调色板匹配即可。这并不难。 - Nyerguds

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接