将8位彩色BMP图像转换为8位灰度BMP



这是我的位图对象

Bitmap b = new Bitmap(columns, rows, PixelFormat.Format8bppIndexed);
BitmapData bmd = b.LockBits(new Rectangle(0, 0, columns, rows), ImageLockMode.ReadWrite, b.PixelFormat);

如何将其转换为8位灰度位图?

是的,不需要改变像素,只是调色板是好的。ColorPalette是一个片状类型,下面的示例代码工作得很好:

        var bmp = Image.FromFile("c:/temp/8bpp.bmp");
        if (bmp.PixelFormat != System.Drawing.Imaging.PixelFormat.Format8bppIndexed) throw new InvalidOperationException();
        var newPalette = bmp.Palette;
        for (int index = 0; index < bmp.Palette.Entries.Length; ++index) {
            var entry = bmp.Palette.Entries[index];
            var gray = (int)(0.30 * entry.R + 0.59 * entry.G + 0.11 * entry.B);
            newPalette.Entries[index] = Color.FromArgb(gray, gray, gray);
        }
        bmp.Palette = newPalette;    // Yes, assignment to self is intended
        if (pictureBox1.Image != null) pictureBox1.Image.Dispose();
        pictureBox1.Image = bmp;

我实际上不建议你使用这个代码,索引像素格式是一个pita处理。在这个答案中,您将找到一个快速且更通用的彩色到灰度转换。

类似于

Bitmap b = new Bitmap(columns, rows, PixelFormat.Format8bppIndexed);
for (int i = 0; i < columns; i++)
{
   for (int x = 0; x < rows; x++)
    {
       Color oc = b.GetPixel(i, x);
        int grayScale = (int)((oc.R * 0.3) + (oc.G * 0.59) + (oc.B * 0.11));
       Color nc = Color.FromArgb(oc.A, grayScale, grayScale, grayScale);
       b.SetPixel(i, x, nc);
  }
}
BitmapData bmd = b.LockBits(new Rectangle(0, 0, columns, rows), ImageLockMode.ReadWrite, b.PixelFormat);

你可以将调色板更改为灰度

,尽管下面的代码是在Vb.net。你可以很容易地把它转换成c#

Private Function GetGrayScalePalette() As ColorPalette  
    Dim bmp As Bitmap = New Bitmap(1, 1, Imaging.PixelFormat.Format8bppIndexed)  
    Dim monoPalette As ColorPalette = bmp.Palette  
    Dim entries() As Color = monoPalette.Entries  
    Dim i As Integer 
    For i = 0 To 256 - 1 Step i + 1  
        entries(i) = Color.FromArgb(i, i, i)  
    Next 
    Return monoPalette  
End Function 

原始来源-> http://social.msdn.microsoft.com/Forums/en-us/vblanguage/thread/500f7827-06cf-4646-a4a1-e075c16bbb38

请注意,如果您想进行与现代高清电视相同的转换,则需要使用Rec. 709系数进行转换。上面提供的。3, .59, .11)(几乎)是Rec. 601(标准def)系数。Rec. 709的系数是灰色= 0.2126 R' + 0.7152 G' + 0.0722 B',其中R', G'和B'是伽马调整后的红色,绿色和蓝色分量。

查看此链接。我们在大学里就这么做过,而且很有效。

最新更新