You are on page 1of 10

1/26/13

C# Tutorial - Convert a Color Image to Grayscale | Switch on the Code

Username: Passw ord: Register | Forgot Passw ord

Login

Home

Tutorials

Forums

News & Other Posts

Podcast

About Us

Contact Us

Search SOTC...

C# Tutorial - Convert a Color Image to Grayscale Skill

C# Tutorial - Convert a Color Image to Grayscale


Posted in: Tutorials .NET .NET 2.0 C#

We've done a few tutorials about image editing with C#. We're going to continue the series with a tutorial on how to convert a color image to black and white. This tutorial will show three different ways to convert an image to grayscale - starting with the easiest and slowest. You're probably wondering why you would want to see multiple ways to accomplish the same thing. It's hard to predict what technique will work best for everyone's application, so I've decided to outline several different possibilities. Below is the image I used to test each algorithm and to benchmark their performance. The image can be downloaded free from Gaming Textures. The conversion times listed were obtained using my computer so your times might be different.

Related Posts HTML 5 Canvas Tutorial Converting Images to Grayscale C# Tutorial - Image Editing: Rotate C# Tutorial - Image Editing: Saving, Cropping, and Resizing Creating Duotone Images in Photoshop

adve advertise rtise he here re

Switch On The Code


Like 576

Sponsors

Original color image

Image converted to black and white

1. Slow and Simple


Convert Time: 1,135ms The first method I'm going to show you is by far the easiest to understand and implement. Unfortunately, it's also the slowest. p u b l i cs t a t i cB i t m a pM a k e G r a y s c a l e ( B i t m a po r i g i n a l ) { / / m a k ea ne m p t yb i t m a pt h es a m es i z ea so r i g i n a l B i t m a pn e w B i t m a p=n e wB i t m a p ( o r i g i n a l . W i d t h ,o r i g i n a l . H e i g h t ) ; f o r( i n ti=0 ;i<o r i g i n a l . W i d t h ;i + + ) { f o r( i n tj=0 ;j<o r i g i n a l . H e i g h t ;j + + ) { / / g e tt h ep i x e lf r o mt h eo r i g i n a li m a g e C o l o ro r i g i n a l C o l o r=o r i g i n a l . G e t P i x e l ( i ,j ) ; / / c r e a t et h eg r a y s c a l ev e r s i o no ft h ep i x e l i n tg r a y S c a l e=( i n t ) ( ( o r i g i n a l C o l o r . R*. 3 )+( o r i g i n a l C o l o r . G*. 5 9 ) +( o r i g i n a l C o l o r . B*. 1 1 ) ) ; / / c r e a t et h ec o l o ro b j e c t C o l o rn e w C o l o r= C o l o r . F r o m A r g b ( g r a y S c a l e ,g r a y S c a l e ,g r a y S c a l e ) ; / / s e tt h en e wi m a g e ' sp i x e lt ot h eg r a y s c a l ev e r s i o n n e w B i t m a p . S e t P i x e l ( i ,j ,n e w C o l o r ) ; } } r e t u r nn e w B i t m a p ; } This code looks at every pixel in the original image and sets the same pixel in the new bitmap to a grayscale version. You can probably figure out why this is so slow. If the image is 2048x2048, this code will call G e t P i x e land S e t P i x e lover 4 million times. Those functions aren't the most efficient way to get pixel data from the image. You might be wondering where the numbers .3, .59, and .11 came from. In reality, you could just take the average Recent Posts Node.js Hosting Platform Modulus Goes Public Beta Node.js and Express Basic Authentication Isaac Schlueter, Maintainer of Node.js, Answering Questions on Crowdhall Simple Chat - Node.js + WebSockets A Simple jQuery Plugin Game

www.switchonthecode.com/tutorials/csharp-tutorial-convert-a-color-image-to-grayscale

1/10

1/26/13

C# Tutorial - Convert a Color Image to Grayscale | Switch on the Code


Node.js and Express Setting Content-Type for all Responses Node.js Snippet Checking Version in Code Node.js Hosting Solutions Aug 8th - Node.Cincy Begins! Posting JSON data with Node.js Categories .NET Actionscript Adobe AIR Apple Instruments AutoHotKey Away 3D Blender Blog News Book Reviews Browsers C# C++ CakePHP Cocoa Touch Conferences CSS Drupal Expression Blend Flex HTML In The News Interviews Javascript jQuery JSON LINQ Lua MXML MySQL Neat Software Neat Websites Node.js Objective-C OpenGL ES Photoshop PHP phpMyAdmin Podcast Pygame Python Rants Ruby Silverlight Snippet Tutorials SQL SQLite Tech News Tutorials Tutorials Around The Web Visual Studio WCF WinForms WiX Wordpress WPF XAML Xcode XNA

color by adding up R, G, B and dividing by three. In fact, you'll get a pretty good black and white image by doing that. However, at some point, someone a lot smarter than me figured out that these numbers better approximate the human eye's sensitivity to each of those colors. The Wikipedia article on grayscale has some pretty good information about that. This method will work fine for small images or when you don't really care about how long it takes to convert it to black and white. If you need it done quickly, I would recommend one of the next two methods.

2. Faster and Complicated


Convert Time: 188ms The next technique I'm going to show you is based on the previous one, but much faster. It still iterates through every pixel, but we're going to utilize C#'s u n s a f ekeyword to make getting the pixel data much more efficient. p u b l i cs t a t i cB i t m a pM a k e G r a y s c a l e 2 ( B i t m a po r i g i n a l ) { u n s a f e { / / c r e a t ea ne m p t yb i t m a pt h es a m es i z ea so r i g i n a l B i t m a pn e w B i t m a p=n e wB i t m a p ( o r i g i n a l . W i d t h ,o r i g i n a l . H e i g h t ) ; / / l o c kt h eo r i g i n a lb i t m a pi nm e m o r y B i t m a p D a t ao r i g i n a l D a t a=o r i g i n a l . L o c k B i t s ( n e wR e c t a n g l e ( 0 ,0 ,o r i g i n a l . W i d t h ,o r i g i n a l . H e i g h t ) , I m a g e L o c k M o d e . R e a d O n l y ,P i x e l F o r m a t . F o r m a t 2 4 b p p R g b ) ; / / l o c kt h en e wb i t m a pi nm e m o r y B i t m a p D a t an e w D a t a=n e w B i t m a p . L o c k B i t s ( n e wR e c t a n g l e ( 0 ,0 ,o r i g i n a l . W i d t h ,o r i g i n a l . H e i g h t ) , I m a g e L o c k M o d e . W r i t e O n l y ,P i x e l F o r m a t . F o r m a t 2 4 b p p R g b ) ; / / s e tt h en u m b e ro fb y t e sp e rp i x e l i n tp i x e l S i z e=3 ; f o r( i n ty=0 ;y<o r i g i n a l . H e i g h t ;y + + ) { / / g e tt h ed a t af r o mt h eo r i g i n a li m a g e b y t e *o R o w=( b y t e * ) o r i g i n a l D a t a . S c a n 0+( y*o r i g i n a l D a t a . S t r i d e ) ; / / g e tt h ed a t af r o mt h en e wi m a g e b y t e *n R o w=( b y t e * ) n e w D a t a . S c a n 0+( y*n e w D a t a . S t r i d e ) ; f o r( i n tx=0 ;x<o r i g i n a l . W i d t h ;x + + ) { / / c r e a t et h eg r a y s c a l ev e r s i o n b y t eg r a y S c a l e= ( b y t e ) ( ( o R o w [ x*p i x e l S i z e ]*. 1 1 )+/ / B ( o R o w [ x*p i x e l S i z e+1 ]*. 5 9 )+ / / G ( o R o w [ x*p i x e l S i z e+2 ]*. 3 ) ) ;/ / R / / s e tt h en e wi m a g e ' sp i x e lt ot h eg r a y s c a l ev e r s i o n n R o w [ x*p i x e l S i z e ]=g r a y S c a l e ;/ / B n R o w [ x*p i x e l S i z e+1 ]=g r a y S c a l e ;/ / G n R o w [ x*p i x e l S i z e+2 ]=g r a y S c a l e ;/ / R } } / / u n l o c kt h eb i t m a p s n e w B i t m a p . U n l o c k B i t s ( n e w D a t a ) ; o r i g i n a l . U n l o c k B i t s ( o r i g i n a l D a t a ) ; r e t u r nn e w B i t m a p ; } } There's a lot of code here so let's go through it piece by piece. The first thing we need to do is lock the bits in the Bitmap objects. Locking the bits keeps the .NET runtime from moving them around in memory. This is important because we're going to use a pointer, and if the data is moving around the pointer won't point to the correct thing anymore. You'll need to know the pixel format of the image you're trying to convert. I'm using jpeg's, which are 24 bits per pixel. There is a way to get the pixel format from an image, but that's outside the scope of this tutorial. The integer, p i x e l S i z e , is the number of bytes per pixel in your original image. Since my images were 24 bits per pixel, that translates to 3 bytes per pixel. To get pixel data, I start by getting the address to the first pixel in each row of the image. S c a n 0returns the address of the first pixel in the image. So in order to get the address of the first pixel in the row, we have to add the number of bytes in the row, S t r i d e , multiplied by the row number, y . Below is a diagram that might help you understand this a little better.

www.switchonthecode.com/tutorials/csharp-tutorial-convert-a-color-image-to-grayscale

2/10

1/26/13

C# Tutorial - Convert a Color Image to Grayscale | Switch on the Code

Now we can get color data straight from memory by accessing it like an array. The byte at x * p i x e l S i z ewill be the blue, x * p i x e l S i z e + 1is green, and x * p i x e l S i z e + 2is red. This is why p i x e l S i z eis very important. If the image you provided is not 3 bytes per pixel, you'll be pulling color data from the wrong location in memory. Next, make the grayscale version using the same process as the previous method and set the exact same pixel in the new image. All that's left to do is to unlock the bitmaps and return the new image.

3. Short and Sweet


Convert Time: 62ms The last method is probably the best way. It's faster than the previous two methods and uses much less code. This technique uses a C o l o r M a t r i xto perform the conversion. A C o l o r M a t r i xis a 5x5 matrix that can make just about any modifications to the color of an image. A C o l o r M a t r i xis pretty complicated and deserves a whole tutorial to itself. For now, if you want more information about it, you'll have to do the research yourself. p u b l i cs t a t i cB i t m a pM a k e G r a y s c a l e 3 ( B i t m a po r i g i n a l ) { / / c r e a t eab l a n kb i t m a pt h es a m es i z ea so r i g i n a l B i t m a pn e w B i t m a p=n e wB i t m a p ( o r i g i n a l . W i d t h ,o r i g i n a l . H e i g h t ) ; / / g e tag r a p h i c so b j e c tf r o mt h en e wi m a g e G r a p h i c sg=G r a p h i c s . F r o m I m a g e ( n e w B i t m a p ) ; / / c r e a t et h eg r a y s c a l eC o l o r M a t r i x C o l o r M a t r i xc o l o r M a t r i x=n e wC o l o r M a t r i x ( n e wf l o a t [ ] [ ] { n e wf l o a t [ ]{ . 3 f ,. 3 f ,. 3 f ,0 ,0 } , n e wf l o a t [ ]{ . 5 9 f ,. 5 9 f ,. 5 9 f ,0 ,0 } , n e wf l o a t [ ]{ . 1 1 f ,. 1 1 f ,. 1 1 f ,0 ,0 } , n e wf l o a t [ ]{ 0 ,0 ,0 ,1 ,0 } , n e wf l o a t [ ]{ 0 ,0 ,0 ,0 ,1 } } ) ; / / c r e a t es o m ei m a g ea t t r i b u t e s I m a g e A t t r i b u t e sa t t r i b u t e s=n e wI m a g e A t t r i b u t e s ( ) ; / / s e tt h ec o l o rm a t r i xa t t r i b u t e a t t r i b u t e s . S e t C o l o r M a t r i x ( c o l o r M a t r i x ) ; / / d r a wt h eo r i g i n a li m a g eo nt h en e wi m a g e / / u s i n gt h eg r a y s c a l ec o l o rm a t r i x g . D r a w I m a g e ( o r i g i n a l ,n e wR e c t a n g l e ( 0 ,0 ,o r i g i n a l . W i d t h ,o r i g i n a l . H e i g h t ) , 0 ,0 ,o r i g i n a l . W i d t h ,o r i g i n a l . H e i g h t ,G r a p h i c s U n i t . P i x e l ,a t t r i b u t e s ) ; / / d i s p o s et h eG r a p h i c so b j e c t g . D i s p o s e ( ) ; r e t u r nn e w B i t m a p ; } This time we're going to use GDI to draw the new black and white image. The benefit of this technique over the last one is that we don't need to know any information about the image's pixel format. The code here is pretty straight forward. First create the blank image and get a G r a p h i c sobject from it. Next, create the C o l o r M a t r i xthat will convert the original image to grayscale. Declare an I m a g e A t t r i b u t e sobject that will use the C o l o r M a t r i xand use it to draw the new image using D r a w I m a g e . That's it for converting an image to grayscale using C# and .NET. Hopefully one of the above techniques will work for your application. Leave us a comment if you've got questions or anything else to say. Related Posts HTML 5 Canvas Tutorial - Converting Images to Grayscale C# Tutorial - Image Editing: Rotate C# Tutorial - Image Editing: Saving, Cropping, and Resizing Creating Duotone Images in Photoshop References Wikipedia on Grayscale MSDN on ColorMatrix

Source Files No files attached.

Delicious

Tweet This!

76 comments Anil Madamala


11/14/2007 - 16:57

Hi this is pretty useful, in my case I am processing a large image, the conversion from color to black and white itself taking much time. Thanks reply

Hnminh
12/03/2007 - 21:43

So cool! Your article help me so much with my project at school. Thanks! But, how about images which are 32bpp? reply

Rodrigo Silva

Very good article. Your research about human eye's sensitivity to build the entire

www.switchonthecode.com/tutorials/csharp-tutorial-convert-a-color-image-to-grayscale

3/10

1/26/13
12/28/2007 - 13:20

C# Tutorial - Convert a Color Image to Grayscale | Switch on the Code


algorithm was very usefull for future implementations! I'm looking forward to tutorials about croping and rotating images as well! Cheers! reply

Nishith
03/05/2008 - 07:37

Great, can we also convert 32/24 bpp to 8bpp in similar fashion? reply Thanx alot. reply Can this be made to work in reverse? I have a black and white line art image saved as a grayscale TIFF that I need to take and apply preset CMYK values to the black area only. The CMYK values would be assigned dynamically.

Mehboob
03/10/2008 - 01:51

Dennis
03/12/2008 - 10:23

reply

Coolgeek1998
04/11/2008 - 10:03

Hi Interesting tutorial! Glad to c tutorial set dedicated to image processing in C#. Right now a group of my friends and I are taking the very first steps in creating a rather wacky new face recognition technique we got in our heads...... But first things first... c how we can manipulate and extract info on images in the computer... so this is great.. thanks.

reply

Tom
05/13/2008 - 20:40

I'm new to C#. I come from JAVA where I do command-line image processing. This is a nice tutorial to observe the C# way. How is Bitmap type setup? I can't get the algorithm to work with C# console application. I will need to put a "using" at the top, but the IDE helper does not offer System.Drawing, it has System.(other stuff) but not Drawing. So I assume I can't do these things in console app environment in C#? I'm using C#2008 express. Thanks for your time. reply

The Reddest
05/14/2008 - 09:27

Before you can add a 'using' statement, you'll first have to make sure your project has a reference to the System.Drawing assembly. Using the Solution Explorer, expand the 'References' folder under your project. If System.Drawing doesn't exist there, right-mouse click on the folder and selected 'Add Reference'. When the dialog appears, select the .NET tab, scroll down to System.Drawing, and add it. Now you should be able to include it into your source.

reply

Anonymous
03/11/2011 - 16:55

Thank you MAN! reply it is very good.as it is easy to understand reply i want to identify a circel in a image reply Nice piece of code (#3) but you forgot to listen the needed references, even though they are quite easy to figure out: using System.Drawing; using System.Drawing.Imaging;

Usman
05/21/2008 - 07:21

Maninder
09/24/2008 - 11:12

Gustav
09/27/2008 - 15:59

reply

Ihteshamq
10/27/2008 - 04:43

How did you find the matrix values. It looks good though reply

The Reddest
10/27/2008 - 07:08

I explain that a little up in the "Slow and Simple" portion of this tutorial, however those values came from the Wikipedia article on Grayscale.

reply

Ihteshamq
10/27/2008 - 07:26

Thanks for letting me know. How /where can i find the matrix values for CMYK.

reply

The Reddest
10/27/2008 - 08:09

The ColorMatrix class only works in the RGBA space. You'd have to find something that converts CMYK to RGB.

reply

David
11/23/2008 - 13:23

Nice thanks! :) reply How would one handle .gifs and .png with transpareny? reply Me again Answered my own Q? :) If you want to grayscale a .gif or .png with transparency colors.... Just save the grayscaled image as Format.Png and not as Format.Gif. ps.Also change the file extension to .png. Hope this saves somebody some time. reply

David
11/24/2008 - 08:45

David
11/25/2008 - 00:45

Angel Jimenez
12/01/2008 - 09:14

i tried to compile your routine in compaq visual fortran, that must compile c# programs, but i had a lot of errors.

www.switchonthecode.com/tutorials/csharp-tutorial-convert-a-color-image-to-grayscale

4/10

1/26/13

C# Tutorial - Convert a Color Image to Grayscale | Switch on the Code


reply The Reddest
12/01/2008 - 10:49

Ive compiled the code using Microsofts C# compiler and Monos compiler without issues. Ive never used the Visual Fortran compiler.

reply

Angel Jimenez
12/01/2008 - 09:37

i have sea surface temperature jpg images and i want to get the (lat,lon,temp) data of each pixel. have you some software to do this? reply

The Reddest
12/01/2008 - 10:49

We dont have any software to read the data youre looking for. The code in this post does allow you to look at the information inside each pixel (RGB values), and Im sure you can expand it into something you want.

reply

Tomas Matejka
12/19/2008 - 04:30

Thanks a lot. This is one of the best :-) reply Hi I have a problem. I cannot find information, that if we can use "if" statemant somehow when using color matrix, in the way, that for example color matrix will not affect yellow colors. I suppose i can use a method with locking bits, but color matrix is much more nice. Please help me, if you can, give a sample of code, or refer me to a website. I was googling, and couldn't find nothing :/

Gercios
01/08/2009 - 10:18

reply

s.a.pishvaie
03/21/2009 - 10:17

it is so great and so sweet with best regards

reply

Anonymous
03/22/2009 - 21:19

HELP!. how do i input the image i want converted for method 3? how do i set 'original'?. THANKS A LOT reply

chithu
04/15/2009 - 00:21

how can i merge one image to another thanks in adv. reply Hello! Could you give me some help and advice please? I would like to know how the grayscale code can be applyed to a button in a menu like in the other projects, near rotate,crop,etc. Thank you! andrei

Andrei
05/12/2009 - 08:20

reply

aman sandha
06/28/2009 - 05:50

you can do it on any event just on button click also thnx reply

madd
05/20/2009 - 06:13

hi, thanks for the code, it helped me a lot. reply Thank you very much - works a treat! reply its very nice solution reply Thanks alot reply Hello! How to check image is RGB? reply

OtherworldBob
05/20/2009 - 11:57

aman sandha
06/28/2009 - 05:49

GHolamreza
07/18/2009 - 12:16

Fernando
09/16/2009 - 20:31

Anonymous
11/03/2009 - 07:33

You can increase the performance of the "Fast and Complicated" method much by not multiplying so much and by caching values as the original. Width in local variables. Much time to salvage there. reply

Irfan
11/16/2009 - 11:54

I am talking about 3rd way. It is awesome. But we only work 1 byte and we can do calculation between that byte red blue green integer values.Can i do calculation between 2 byte using third way. Thank you reply

Dan Dan
11/17/2009 - 19:03

Hi There Wonderful article. I was owndering that when i save the new grayscale image to disk the size actually increases. I am using the bmp.Save() method. Why would that be? I would expect that the file size would decrese.

www.switchonthecode.com/tutorials/csharp-tutorial-convert-a-color-image-to-grayscale

5/10

1/26/13
Cheers Dan

C# Tutorial - Convert a Color Image to Grayscale | Switch on the Code


Am i missing something?

reply

Dimple
11/19/2009 - 00:44

Can any one tell me how to convert a grayscale or a multi color image to mono color gif image... selection of color is done by user dynamically at run time

reply

Prashanth
02/23/2010 - 22:20

Hi, Very nice article.. Really helpful.. However I ve one doubt.. When using the byte* pointers logic, the pixel format of the grayscale image is still 24bpprgb right? But in general, grayscale images are in 8bbpindexed format. How can this pixelformat conversion be obtained?

reply

Abdulellah
03/06/2010 - 13:27

Thanks for this explained codes ,but I want know how merge an image with digtil signature in E-card.

reply

JALAL
03/10/2010 - 16:21

Thank you very much reply I am new to C# image processing. Is it possible to change the portion of original image into grayscale value and save it back to the original image itself.

Irene
04/15/2010 - 03:46

reply

FasterThanYou
05/10/2010 - 19:31

You missed the fastest method of all: Doing floating-point arithmetic is sloooow, computationally speaking. Doing it for an array of pixels is doubly slow. Solution: Use your "2. Faster and Complicated", but use pre-calculated lookup tables. I have 3 arrays (R, G, B), each with values from 0 - 254, precalculated with the values you are multiplying above. I processed the same image using that, and it took me 16ms. MUCH faster. Even your third method, while cool, still is performing many floating-point calculations (=slow). The arrays I am using: p r i v a t es t a t i ci n t [ ]R G B R=n e wi n t [ ]{0 ,0 ,0 ,1 ,1 ,1 ,1 ,1 , 2 ,2 ,2 ,2 ,3 ,3 ,3 ,3 ,3 ,4 ,4 ,4 ,4 ,4 ,5 ,5 ,5 ,5 ,6 ,6 ,6 , 6 ,6 ,7 ,7 ,7 ,7 ,7 ,8 ,8 ,8 ,8 ,9 ,9 ,9 ,9 ,9 ,1 0 ,1 0 ,1 0 ,1 0 , 1 0 ,1 1 ,1 1 ,1 1 ,1 1 ,1 1 ,1 2 ,1 2 ,1 2 ,1 2 ,1 3 ,1 3 ,1 3 ,1 3 ,1 3 ,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1 7 ,1 7 ,1 7 ,1 7 ,1 7 ,1 7 ,1 7 ,1 7 ,1 7 ,1 7 ,1 8 ,1 8 , 1 8 ,1 8 ,1 8 ,1 8 ,1 8 ,1 8 ,1 8 ,1 8 ,1 8 ,1 8 ,1 8} ; reply

www.switchonthecode.com/tutorials/csharp-tutorial-convert-a-color-image-to-grayscale

6/10

1/26/13
yosra
10/16/2010 - 00:29

C# Tutorial - Convert a Color Image to Grayscale | Switch on the Code


Hi,can you pls, tell me is that array data's is for a real image and how you do it. Cheers, reply

MarkG
07/29/2010 - 11:17

Hi, I am trying to use your last method to change the brightness of a VERY large image ( 14770x22392 ~ 350MB), and it's not working, I think because the NewBitmaps needs the width and height as a int. What can I do? reply

mpistare
01/30/2011 - 19:51

I can help you, the answer is CUDA. I have experience in the field. mpistare@fceia.unr.edu.ar

reply

yosra
10/16/2010 - 00:31

very importnt information it help me mo,thanks alot reply thank you! reply Hello @FasterThankyou please you explaine your method... reply thank you so much! reply Thank you. Help me out. reply Is is possible to convert a tif to gray and ccitt 4 by 1 bit level? I just want to resize a 32bit color image to a small size image.

Anonymous
11/12/2010 - 00:51

Genious
12/24/2010 - 15:50

Bernard
01/12/2011 - 03:39

Chuck
02/15/2011 - 21:53

Hungry
03/11/2011 - 03:54

reply

Hungry
03/11/2011 - 04:01

Bitmap bmpCanvas = new Bitmap(maxSize.Width, maxSize.Height); Graphics g = Graphics.FromImage(bmpCanvas); System.Drawing.Image img = System.Drawing.Image.FromFile("test.tif", true); g.DrawImage(img, 0, 0); sFileName = string.Format("{0}\\{1}.tif", path, Guid.NewGuid().ToString()); ImageCodecInfo codecInfo = GetEncoderInfo("image/tiff"); EncoderParameters iparams = new EncoderParameters(1); Encoder iparam = Encoder.Compression; EncoderParameter iparamPara = new EncoderParameter(iparam, (long) (EncoderValue.CompressionCCITT4)); iparams.Param[0] = iparamPara; bmpCanvas = MakeGrayscale3(bmpCanvas); bmpCanvas.Save(sFileName, codecInfo, iparams); // CompressionCCITT4 is case parameter error, but CompressionLZW is success. What's wrong?

reply

Seyi
03/16/2011 - 03:50

@FasterThanYou, can you please post the full source code for this conversion and perhaps also explain?

reply

Gihan Perera
04/10/2011 - 07:05

public void Convert2GrayScaleFast(Bitmap bmp) { BitmapData bmData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); unsafe { byte* p = (byte*)(void*)bmData.Scan0.ToPointer(); int stopAddress = (int)p + bmData.Stride * bmData.Height; while ((int)p != stopAddress) { p[0] = (byte)(.299 * p[2] + .587 * p[1] + .114 * p[0]); p[1] = p[0]; p[2] = p[0]; p += 3; } } bmp.UnlockBits(bmData); } im using this code for gray scale ..but it gives "Attempted to read or write protected memory. This is often an indication that other memory is corrupt." Can somes one please help me to get through this... thanks. reply

Anonymous
05/11/2011 - 14:53

Stride is rounded up to 4 bytes. For example a 330 pixel width at 24 bits has a stride of 992, not 990. Your loop needs to skip those bytes and not overflow the bitmap memory space

reply

Anonymous
08/07/2012 - 09:58

You need to put your code (all of it) inside an unsafe bracket ex: unsafe { // your code goes here! }

www.switchonthecode.com/tutorials/csharp-tutorial-convert-a-color-image-to-grayscale

7/10

1/26/13

C# Tutorial - Convert a Color Image to Grayscale | Switch on the Code


reply

js
04/15/2011 - 22:11

thanks.. thanks a lot... reply Include the fucking part of the code wehre it says "Using ...", so we can see what the fuck to include to be able to do this shit, since the microsoft documentation is the most retarded documentation in the world, and the language is so retarded, that it fucking doesn't even find the fucking shit that you fucking need to include, because of some fucking fucked up setting that fucking is something I as a programmer shouldn't fucking have to fucking ever fucking worry about.

Anonymous
05/24/2011 - 16:46

reply

The Reddest
05/25/2011 - 10:05

Pro tip: put your cursor at the end of the type and hit Shift+Alt+F10. Visual Studio will popup the include you need. P.S. I think your "fuck" key is stuck. reply

rc
06/15/2011 - 15:21

Just wanted to say thanks for your article; it was a nice starting off point for getting into image manipulation. There's one improvement, though, that will easily make your second method faster than your third: Create a local variable to hold the width and height of the original image. Surprisingly, .Width and .Height are relatively expensive GDI calls that end up being evaluated for every pixel in the condition of the for loops. Changing these to a local variable reduces the run time from ~80ms to ~4ms on my machine with the flower test image you used(the matrix method takes ~20ms in comparison). You can further optimize by creating local variables to hold the stride width, the starting byte address of the images, and changing how the current rows are computed, and use a precomputed lookup array, but obviously you won't see the same sort of performance gain as removing .Width and .Height calls. If you need to process thousands of larger images though, it can definitely be worth it. Lastly, I started using FasterThanYou's lookup table but it looks like the values used to compute it were slightly different than the standards I've seen, so I rebuilt a table using R * .299, G * .587, and B *.114. TO use the table, use the original value of the rgb elements as indexes in the tables and add the returned values, ie: b y t eg r a y B y t e=( b y t e )( R G B B [ o R o w [ x*p i x e l S i z e ] ] +R G B G [ o R o w [ x*p i x e l S i z e+1 ] ] +R G B R [ o R o w [ x*p i x e l S i z e+2 ] ] ) ; And here are my modified tables using the above values if anyone is interested: p r i v a t es t a t i ci n t [ ]R G B R=n e wi n t [ ]{0 ,0 ,1 ,1 ,1 ,1 ,2 ,2 , 2 ,3 ,3 ,3 ,4 ,4 ,4 ,4 ,5 ,5 ,5 ,6 ,6 ,6 ,7 ,7 ,7 ,7 ,8 ,8 ,8 , 9 ,9 ,9 ,1 0 ,1 0 ,1 0 ,1 0 ,1 1 ,1 1 ,1 1 ,1 2 ,1 2 ,1 2 ,1 3 ,1 3 ,1 3 , 1 3 ,1 4 ,1 4 ,1 4 ,1 5 ,1 5 ,1 5 ,1 6 ,1 6 ,1 6 ,1 6 ,1 7 ,1 7 ,1 7 ,1 8 ,1 8 , 1 8 ,1 9 ,1 9 ,1 9 ,1 9 ,2 0 ,2 0 ,2 0 ,2 1 ,2 1 ,2 1 ,2 2 ,2 2 ,2 2 ,2 2 ,2 3 , 2 3 ,2 3 ,2 4 ,2 4 ,2 4 ,2 5 ,2 5 ,2 5 ,2 5 ,2 6 ,2 6 ,2 6 ,2 7 ,2 7 ,2 7 ,2 8 , 2 8 ,2 8 ,2 8 ,2 9 ,2 9 ,2 9 ,3 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 , 2 8 ,2 9 ,2 9 ,2 9 ,2 9 ,2 9} ;

reply

Jaffer Mumtaz
12/05/2011 - 02:40

Hi, Can you guide me on how to do the same function but from grayscale image to color. My input will be a raw colorless image and as output I want colored image. Any pointers will be helpful. Thanks, Jaffer Mumtaz reply

mustafa
07/05/2011 - 04:27

hi, can anybody help me about plate recognition C# algorithm reply I am getting GDI+ error using the algorithm3. can anyone help. i am using it in a windows service.

umer draz
07/28/2011 - 13:50

reply

Anonymous
08/22/2011 - 06:15

I just modified the function, so that it can convert to 8-bit format. Use this color pallette: Bitmap bmp = new Bitmap(1, 1, PixelFormat.Format8bppIndexed); ColorPalette monoPalette = bmp.Palette; for (int i = 0; i < 256; i++) { monoPalette.Entries[i] = Color.FromArgb(i, i, i); } b8.Palette = monoPalette; private static Bitmap Make8bitGrayscale(Bitmap original) { unsafe { //create an empty bitmap the same size as original Bitmap newBitmap = new Bitmap(original.Width, original.Height, PixelFormat.Format8bppIndexed); //lock the original bitmap in memory BitmapData originalData = original.LockBits( new Rectangle(0, 0, original.Width, original.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); //lock the new bitmap in memory BitmapData newData = newBitmap.LockBits( new Rectangle(0, 0, original.Width, original.Height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed); //number of bytes per pixel in original image int pixelSize = 3; for (int y = 0; y < original.Height; y++) { //get the data from the original image byte* oRow = (byte*)originalData.Scan0 + (y * originalData.Stride); //get the data from the new image byte* nRow = (byte*)newData.Scan0 + (y * newData.Stride); for (int x = 0; x < original.Width; x++) { //create the grayscale version /*byte grayScale = // Color image as source (byte)((oRow[x * pixelSize] * .11) + //B (oRow[x * pixelSize + 1] * .59) + //G (oRow[x * pixelSize + 2] * .3)); //R*/ byte grayScale = oRow[x * pixelSize]; // Greyscale //set the new image's pixel to the grayscale version nRow[x] = grayScale; // only one byte per pixel in greyscale format //nRow[x * pixelSize] = grayScale; //B //nRow[x * pixelSize + 1] = grayScale; //G //nRow[x * pixelSize + 2] = grayScale; //R } } //unlock the bitmaps newBitmap.UnlockBits(newData); original.UnlockBits(originalData); return newBitmap; } }

reply

Anonymous
10/09/2011 - 14:58

can you send me the project with .sln ?? reply Hello, i have a problem with displaying the grayescle image...I do: d.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes); do i need in de form designer some event?

smoli
10/11/2011 - 10:32

www.switchonthecode.com/tutorials/csharp-tutorial-convert-a-color-image-to-grayscale

9/10

1/26/13

C# Tutorial - Convert a Color Image to Grayscale | Switch on the Code


reply

Anonymous
01/16/2012 - 06:09

i want morphology codes like dilation erosion for processing RGB images can anyone help me.

reply

Joe Finsterwald
03/08/2012 - 01:33

Thanks for this! You saved me a ton of time!!! Hopefully one day I can return the favor!

reply

Raki Saionji
03/09/2012 - 04:35

I have use your third solution: << 3. Short and Sweet >> My program is written in VB so I have converted your code into VB using my hands (Tools always give bad codes). It works great. Thank you very much.

reply

Raki Saionji
03/09/2012 - 04:37

Here is it: P u b l i cS h a r e dF u n c t i o nM a k e G r a y s c a l e I m a g e ( o r i g i n a lA s B i t m a p )A sB i t m a p D i mn e w B i t m a pA sN e wB i t m a p ( o r i g i n a l . W i d t h , o r i g i n a l . H e i g h t ) D i mgA sG r a p h i c s= G r a p h i c s . F r o m I m a g e ( n e w B i t m a p ) D i ma=N e wS i n g l e ( 4 ) ( ){ } a ( 0 )={ 0 . 3 F ,0 . 3 F ,0 . 3 F ,0 ,0 } a ( 1 )={ 0 . 5 9 F ,0 . 5 9 F ,0 . 5 9 F ,0 ,0 } a ( 2 )={ 0 . 1 1 F ,0 . 1 1 F ,0 . 1 1 F ,0 ,0 } a ( 3 )={ 0 ,0 ,0 ,1 ,0 } a ( 4 )={ 0 ,0 ,0 ,0 ,1 } D i mcA sI m a g i n g . C o l o r M a t r i x c=N e wI m a g i n g . C o l o r M a t r i x ( a ) D i ma t t r i b u t e sA sN e wI m a g i n g . I m a g e A t t r i b u t e s a t t r i b u t e s . S e t C o l o r M a t r i x ( c ) g . D r a w I m a g e ( o r i g i n a l ,N e wR e c t a n g l e ( 0 ,0 , o r i g i n a l . W i d t h ,o r i g i n a l . H e i g h t ) , 0 ,0 ,o r i g i n a l . W i d t h ,o r i g i n a l . H e i g h t , G r a p h i c s U n i t . P i x e l ,a t t r i b u t e s ) g . D i s p o s e ( ) R e t u r nn e w B i t m a p E n dF u n c t i o n reply

Anonymous
10/15/2012 - 09:33

Hi! Is there a way to achieve this conversion in Windows Store Apps? WinRT doesn't support many imaging classes.

reply

Anonymous
10/23/2012 - 08:19

Hi!i have need raster image to vector image(wmf) conversion . please guide me.Thanks

reply

Valentino
01/21/2013 - 22:11

Hi!, my project is to design a program to tell me the color of the pixel where the cursor points in a live cam/video. How should I make use of the lockbits method to get the pixel HSL values? I'm new in video processing. Please guide me. Thanks alot

reply

Add Comment Your name:

Anonymous
Put code snippets inside language tags: [language] [/language] Examples: [javascript] [/javascript] [actionscript] [/actionscript] [csharp] [/csharp] See here for supported languages. Jav ascript must be enabled to submit anonymous comments - or you can login.

Save
CAPTCHA This question is for testing whether you are a human visitor and to prevent automated spam submissions. What is the first word in the phrase "zewuj amaj aqif xak"?: *

Copyright 2006-2013 Paranoid Ferret Productions. All rights reserved.

Forums | Categories | Podcast | About Us | Contact Us | Code License | Subscribe (RSS) | Advertise
www.switchonthecode.com/tutorials/csharp-tutorial-convert-a-color-image-to-grayscale 10/10

You might also like