Click here to Skip to main content
15,883,705 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I want to extract blue color from image, I wrote code for it. I am using lockbits method in C#.
24 bit image - BGR
[0] = Blue
[1] = Green
[2] = Red
Here is code -
C#
BitmapData bitmapdata = bitmap.LockBits (
                            new Rectangle(
                                0,
                                0,
                                bitmap.Width,
                                bitmap.Height),
                            ImageLockMode.ReadWrite,
                            PixelFormat.Format24bppRgb );
IntPtr                  ptr = bitmapdata.Scan0;
                                     // declare  an array to hold
                                     // the bytes of bitmap
int                     bytes = Math.Abs ( bitmapdata.Stride ) *
                                bitmap.Height;
byte [ ]                values = new byte [ bytes ];

System.Runtime.InteropServices.Marshal.Copy ( ptr, values, 0, bytes );

for ( int i = 0; ( i < values.Length ); i += 3 )
    {
                                     // Comparing blue and green and
                                     // blue and red. if blue is greater
                                     // than both pixel than make it
                                     // more intensive otherwise make white
    if ( ( values [ i ] - values [ i + 1 ] > 9 ) &&
         ( values [ i ] - values [ i + 2 ] > 9 )
        {
        values [ i ] = 255;
        values [ i + 1 ] = 0;
        values [ i + 2 ] = 0;
        }
    else
        {
        values [ i ] =  255;
        values [ i + 1 ] =  255;
        values [ i + 2 ] =   255;
        }
    }
bitmap.Save("bitmap.jpg");

This code is working fine but in one image I got problem, it was extracting red color instead of blue when the image has no color.
This image should be white when I run this code.
I don't want to use getpixel or setpixel method.
Image attached.
Posted
Updated 22-May-15 12:28pm
v2

1 solution

It simply means that one of the images happens to have different pixel format. Different formats makes different memory layouts. You have to read the file and then read the property PixelFormat:
https://msdn.microsoft.com/en-us/library/system.drawing.image.pixelformat(v=vs.110).aspx[^],
https://msdn.microsoft.com/en-us/library/system.drawing.imaging.pixelformat%28v=vs.110%29.aspx[^].

Read the description on the given pixel format and adjust your assumed memory layout.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900