Finding Ratio of Background Color in an image

Bitmap class: it is a very useful and rich class for handling basic functionality of an image like reading pixel and its attributes, get height and width of image, create icon from image and etc.

Load an image: To load an image into memory to we can use constructor of this class, like

C#:      Bitmap b = new Bitmap(@”c:\water.jpg”);

This will load an image into ‘b’, a Bitmap instance, where image placed at root directory of C drive with name ‘water.jpg’.

To find the ratio of a predefine background color does not require any complex algorithm. It can simply achieve by counting pixel with background color and then divide by total number of pixel.

To read the color of a pixel we use GetPixel() method. It returns the different properties of pixel at x,y (where x and y are coordinates of image).

C#:           Color c = GetPixel(i,j)

Here Color is a structure represents ARGB color. Here RGB is for Red, Green and Blue … where A is not color but Alpha property…. that represents transparency factor. For a a pixel of white it color it will return ‘ffffffff’. Here A = 100%,(255) R=100%, R=100%, G=1005(255) and B=100%(255).  Now you can get it value by Name property or individual properties of A,R,G and B. Like c.A, c.R, c.G and c.B where c.Name will give a string like ‘ffffffff’.

Code for finding ratio:

double getRatio(String filename, Color bgColor)
            Bitmap b = new Bitmap(filename); // open bitmap/jpeg file
            int count = 0;     // initialize counter
            for (int i = 0; i < b.Width; i++)     
                for (int j = 0; j < b.Height; j++)
// read each pixel and compare it with backgroup color, if it matche then increment count’s value
                    if (CompareColor(bgColor, b.GetPixel(i, j)))
          // calculate ratio and return
            double imgSize = b.Width*b.Height ;
            return ((count / imgSize ) * 100);

        bool CompareColor(Color x,Color y)
          // compare two Color structure whether they represent same                color or not
            if (x.A == y.A && x.B == y.B && x.G == y.G && x.R == y.R)
                return true; // if both having same color values
            return false; // if not then it will return false

Well back draw of this method is that it will require more process time as it size image increases. I tested it for 200px X 200px image… and it run smoothly … but .. I am sure not for 640 X 480 … for that … it will require a bit Algorithm techniques to run within acceptable time.


Popular posts from this blog


Khuda Karay K Meri Arz -e- Pak Par Utray

کولہوں کے بیل