Convert 8-bit color image bmp to 8-bit grayscale bmp

This is my raster object.

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

How do I convert this to an 8 bit bitmap?

+4
source share
5 answers

hi, you can change the color palette to shades of gray

although the following code is in Vb.net. You can easily convert it to 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 

Source Source β†’ http://social.msdn.microsoft.com/Forums/en-us/vblanguage/thread/500f7827-06cf-4646-a4a1-e075c16bbb38

+2
source

Yes, no need to change pixels, just the palette is fine. ColorPalette is a broken type, this code sample worked well:

  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; 

I really do not recommend you use this code, indexed pixel formats are lavash. You will find a faster and more general conversion of color to shades of gray in this answer .

+5
source

Sort of:

 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); 
+3
source

Note that if you want to do the same conversion as modern HDTVs, you will want to use Rec. 709 conversion factors. The above (.3, .59, .11) are (almost) Rec. 601 (standard def). Rec. 709 are gray = 0.2126 R '+ 0.7152 G' + 0.0722 B ', where R', G 'and B' are gamma-corrected red, green and blue components.

+2
source

Mark the link . We did it at the university, and it works.

That is all you need for input and output.

0
source

Source: https://habr.com/ru/post/1386953/


All Articles