How to convert a color image into grayscale image in C# using Visual Studio

C# Project

In this project we are learning to convert a color image into grayscale image.

Requirement

For this project we will need Microsoft Visual Studio

Introduction

Before we start our grayscale topic lets take a Quick Intro.

A pixel is made up of 4 components
AlphaRedGreenBlue

Alpha determines the transparency while Red, Green and Blue determines the color of the pixel. We can denote these 4 components as
Alpha – A
Red – R
Green – G
Blue – B

Each of these 4 components (ARGB) has a value between 0 to 255.
0 means the component is missing. While 255 means the component is fully present. We can represent the value 0 to 255 using 8 bits. So each component can be represented using 8 bits.

Therefore, we will need 32 bits to represent a pixel.

For a 2D image we will have pixels arranged in rows and columns. Origin (starting pixel) of the image is at the coordinate (0,0).

So, we can denote a pixel (x,y) as Px,y(A,R,G,B)

Where, (x,y) is the co-ordinate of the pixel and A, R, G and B denote the Alpha, Red, Green and Blue value of the pixel respectively.

Where A, R, G and B represents the Alpha, Red, Green and Blue value of the pixel.
Remember! ARGB will have an integer value in the range 0 to 255.
So, to convert the color pixel into grayscale pixel we have to first find the average of R, G and B.
Average, Avg = (R+G+B)/3
i.e., Avg = (100+150+200)/3 = 150
Now we will replace the value of R, G and B with the average value that we calculated for the pixel.
So, the new pixel value will be
A = 255
R = 150
G = 150
B = 150
Note! We don't have to change the alpha value because it only controls the transparency of the pixel.
Hence, for a grayscale image the RED, GREEN and BLUE component of a given pixel is same.