C# Tutorial: How To Convert a Color Image To Grayscale


Andraz Krzisnik
C# Tutorial: How To Convert a Color Image To...

Grayscale images are basically black and white images. These images are good for programming, since their pixels hold only intensity values or in other words, shades of gray, they use up less information to process (8-bits per pixel, to be exact).

How many shades of grey are there?

For an 8-bit grayscale image, a pixel can have 255 different shades of gray, including black and white. A shade of gray is created when RGB values of a pixel are the same. These values will go from 0 to 255, which means if a pixel holds 0 for red, green and blue, it will show as a complete black color. And if it will hold 255 for all three, you will see it as a white color. Everything in between will appear as a shade of gray.

Converting a image to grayscale

When converting an image, intensity of a pixel is fractioned for each color (Red, Green, Blue). All fractioned numbers sum up to 1 (more or less).

Equation for converting pixel colors to grayscale follows

?(?,?) = 0,21 ∙ ?(?,?) + 0,71 ∙ ?(?,?) + 0,071 ∙ ?(?,?)

When calculated, RGB values in a pixel are replaced by Y.

The largest fraction is assigned to green color, because human eyes are most sensitive to green and the lowest fraction is assigned to blue color, because … you guessed it, human vision is least sensitive to blue.

GetPixel Method

for (int i = 0; i < bmp.Width; i++)
{
    for (int j = 0; j < bmp.Height; j++)
    {
         Color c = bmp.GetPixel(i, j);

         //Apply conversion equation
         byte gray = (byte)(.21 * c.R + .71 * c.G + .071 * c.B);

         //Set the color of this pixel
         bmp.SetPixel(i, j, Color.FromArgb(gray, gray, gray));
    }
}

LockBits Method

//Lock bitmap's bits to system memory
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, bmp.PixelFormat);

//Scan for the first line
IntPtr ptr = bmpData.Scan0;

//Declare an array in which your RGB values will be stored
int bytes = Math.Abs(bmpData.Stride) * bmp.Height;
byte[] rgbValues = new byte[bytes];

//Copy RGB values in that array
Marshal.Copy(ptr, rgbValues, 0, bytes);

for (int i = 0; i < rgbValues.Length; i += 3)
{
    //Set RGB values in a Array where all RGB values are stored
    byte gray = (byte)(rgbValues[i] * .21 + rgbValues[i + 1] * .71 + rgbValues[i + 2] * .071);
    rgbValues[i] = rgbValues[i + 1] = rgbValues[i + 2] = gray;
}

//Copy changed RGB values back to bitmap
Marshal.Copy(rgbValues, 0, ptr, bytes);

//Unlock the bits
bmp.UnlockBits(bmpData);

The GetPixel method converts pixel colors directly in a bitmap form, which takes longer time to convert an entire image as it would take with LockBits method, which only changes array values.

Speaking of downsides, LockBits on the other hand needs a filter for each image format, because some formats (.PNG for example) will store 4 values instead of 3 (they include alpha channel for transparency).

In this particular program there is no filter applied, so images will have to be of format that carry only RGB values, like .JPG.

Complete project is available here (made with Visual Studio 2015)

Show Comments (24)

Comments

  • 98Lonna

    I must say you have hi quality articles
    here. Your website can go viral. You need initial traffic only.
    How to get it? Search for: Etorofer’s strategies

    • Article Author
  • network marketing

    Its like you read my mind! You appear to know a lot about this, like you wrote the book in it or something. I think that you could do with some pics to drive the message home a bit, but instead of that, this is great blog. An excellent read. I will definitely be back.

    • Article Author
  • small business services

    I seriously love your site.. Great colors & theme. Did you make this web site yourself? Please reply back as I’m hoping to create my own site and want to find out where you got this from or what the theme is named. Thank you!

    • Article Author
  • financial plan

    Can I just say what a comfort to find somebody that really understands what they’re talking about online. You certainly understand how to bring a problem to light and make it important. More and more people should look at this and understand this side of your story. I was surprised that you are not more popular because you definitely possess the gift.

    • Article Author
  • http://www.dreamingson.com/r/soccerlive996240

    https://epochabuse.com is very informative, bookmarked

    • Article Author
  • ow.ly

    GB

    • Article Author
  • Chin Ogami

    “Great Blogpost! I couldn’t refrain from commenting. _Perfectly written!”

    • Article Author
  • Learn colors

    The student who can see you requires to describe how his or her companion should really colour in the
    grid by naming colors and numbers.

    • Article Author
  • why not find out more

    Use the hyperlink in the e mail to opt out of future communications.

    • Article Author
  • MayNickerson

    I see your site needs some fresh content.

    Writing manually is time consuming, but there is solution for this hard task.
    Just search for: Miftolo’s tools rewriter

    • Article Author
  • camel toe

    It’s actually a great and useful piece of information. I’m glad that you just shared this helpful information with us.
    Please keep us up to date like this. Thank you for
    sharing.

    • Article Author
  • Daphine Gunterman

    as girls wearing these hats that are made to appear like animal heads: not at all.|A desire to rebel against such a buttoned-up ethos leaves the white girl desperate for an identity

    • Article Author
  • Azucena Croke

    {In my years of professional research” I can say, with calculated proof, that twerk dancing originated in dance establishments recognized

    • Article Author
  • stan smith bold all white

    I抦 not that much of a internet reader to be honest but your blogs really nice, keep it up! I’ll go ahead and bookmark your website to come back down the road. All the best

    • Article Author
  • chaussure adidas nmd rose

    Hey! Would you mind if I share your blog with my facebook group? There’s a lot of folks that I think would really appreciate your content. Please let me know. Many thanks

    • Article Author
  • seahawks jersey salute to service

    “He [Klopp] wanted us to get up to the ball more – more pressure, more counter-pressing.”

    • Article Author
  • adidas superstar 8

    Hey there! I just wanted to ask if you ever have any issues with hackers? My last blog (wordpress) was hacked and I ended up losing months of hard work due to no data backup. Do you have any solutions to protect against hackers?

    • Article Author
  • larry fitzgerald replica jersey

    Whats up this is kinda of off topic but I was wanting to know if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding know-how so I wanted to get guidance from someone with experience. Any help would be greatly appreciated!

    • Article Author
  • stan smith jw

    I absolutely love your blog and find many of your post’s to be exactly what I’m looking for. Does one offer guest writers to write content to suit your needs? I wouldn’t mind writing a post or elaborating on most of the subjects you write about here. Again, awesome weblog!

    • Article Author
  • adidas yeezy triple white v2

    Does your site have a contact page? I’m having problems locating it but, I’d like to send you an e-mail. I’ve got some suggestions for your blog you might be interested in hearing. Either way, great site and I look forward to seeing it improve over time.

    • Article Author
  • adidas technology

    Have you ever thought about publishing an e-book or guest authoring on other blogs? I have a blog centered on the same subjects you discuss and would really like to have you share some stories/information. I know my readers would appreciate your work. If you’re even remotely interested, feel free to shoot me an e mail.

    • Article Author
  • 96 jersey

    Hi would you mind sharing which blog platform you’re using? I’m looking to start my own blog in the near future but I’m having a hard time deciding between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design seems different then most blogs and I’m looking for something unique. P.S Sorry for getting off-topic but I had to ask!

    • Article Author
  • stan smith high black

    Hi there! Quick question that’s entirely off topic. Do you know how to make your site mobile friendly? My site looks weird when browsing from my iphone. I’m trying to find a template or plugin that might be able to fix this problem. If you have any recommendations, please share. Appreciate it!

    • Article Author
  • green bay packers hoodie jacket

    Hey there I am so glad I found your weblog, I really found you by mistake, while I was browsing on Aol for something else, Nonetheless I am here now and would just like to say cheers for a tremendous post and a all round enjoyable blog (I also love the theme/design), I don’t have time to look over it all at the minute but I have bookmarked it and also added in your RSS feeds, so when I have time I will be back to read much more, Please do keep up the fantastic job.

    • Article Author

Related Articles

Morphological Reconstruction

How To Make Geodesic Dilation And Erosion In Morphology

Geodesic dilation and erosion are fundamental morphological reconstruction algorithms which yield the same result if left to converge.

Posted on by Andraz Krzisnik
Grayscale Morphology

How To Make Granulometry Work With C#

Granulometry is a grayscale morphological operation in image processing for estimating distribution of different sized particles.

Posted on by Andraz Krzisnik