Reputation: 4235
I am loading an image inside a Console application using Image.FromFile
.
After that, I am casting it to a Bitmap
to be able to use the Bitmap.GetPixel()
method.
Surprisingly, while looping through all the pixels, all what I am getting from the GetPixel
is 0,0,0 for R,G,B.
To make sure that the image is well read from the file, I added a reference to System.Windows.Forms
and I loaded the image inside a PictureBox
to see the result, and the image is well seen.
Original Image:
Here's how I am loading the image and showing it into a PictureBox
:
Bitmap img = (Bitmap)Image.FromFile("image.png");
PictureBox pb = new PictureBox
{
Image = img
};
Form frm = new Form
{
Controls = { pb }
};
frm.ShowDialog();
Which shows the image as it is:
And after that, I am getting the pixels like:
byte[] input = new byte[784];
for (int x = 0; x < 28; x++)
{
for (int y = 0; y < 28; y++)
{
Color color = img.GetPixel(x, y);
byte r = color.R;
byte g = color.G;
byte b = color.B;
Console.Write($"{color.R},{color.G},{color.B}|||");
input[x * 28 + y] = (byte)((((r + g + b) / 3)));
}
Console.WriteLine();
}
Note that the image size is 28x28px, and I have tried other images and I've got the same result.
What I expected that the results shows the real color values since I've used that method before and it worked perfectly, but now all the results printed to the console are zeros which I am finding it difficult to understand.
Since the PictureBox
is showing the real image representation, I tried to get the pixels from the PictureBox.Image
like:
Color color = ((Bitmap)pb.Image).GetPixel(x, y);
This also didn't work and the results came back as zeros.
What could be the reason behind this and how to fix it?
Upvotes: 1
Views: 558
Reputation: 54453
In your image all color channels of all pixels are 0
, so you code actually works fine.
And most of the pixels also have an alpha
of 0
, so they are transparent. Some are semi-transparent, anti-aliased pixels and a few are fully opaque.
Where transparent or semi-transprent pixels are, the backcolor will shine through.
If you want to recognize the really, non-transparent black pixels you need to test the alpha channel as well.
Here is a function that will create a composite color of a pixel's color and a given background color..:
Color Composite(Color color, Color backcolor)
{
byte r = (byte)(((255 - color.A) * backcolor.R + color.R * color.A) / 256);
byte g = (byte)(((255 - color.A) * backcolor.G + color.G * color.A) / 256);
byte b = (byte)(((255 - color.A) * backcolor.B + color.B * color.A) / 256);
Color c2 = Color.FromArgb(255, r, g, b);
return c2;
}
If you want the brightness of one of your pixels you could create a composite of its color with white. But, given the image you have, you could just as well use color.A
directly..
Upvotes: 1