I have this code from stackoverflow answers to detect bright and dark images
The problem is that it does not work and I don't know why.
for example if I call
IsDark(bitmap, 40, 0.9); // this always sees the image as bright
any value from 0.1 to 0.99 returns a bright image and any other value above 0.99 returns all the images as dark.
the tolerance value seems to have no effect even if set from 1 to 250.
// For fast access to pixels
public static unsafe byte[] BitmapToByteArray(Bitmap bitmap)
{
BitmapData bmd = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly,
PixelFormat.Format32bppArgb);
byte[] bytes = new byte[bmd.Height * bmd.Stride];
byte* pnt = (byte*)bmd.Scan0;
Marshal.Copy((IntPtr)pnt, bytes, 0, bmd.Height * bmd.Stride);
bitmap.UnlockBits(bmd);
return bytes;
}
public bool IsDark(Bitmap bitmap, byte tolerance, double darkProcent)
{
byte[] bytes = BitmapToByteArray(bitmap);
int count = 0, all = bitmap.Width * bitmap.Height;
for (int i = 0; i < bytes.Length; i += 4)
{
byte r = bytes[i + 2], g = bytes[i + 1], b = bytes[i];
byte brightness = (byte)Math.Round((0.299 * r + 0.5876 * g + 0.114 * b));
if (brightness <= tolerance)
count++;
}
return (1d * count / all) <= darkProcent;
}
OK, after looking at it again, I notice that the comparison at the end of the function looks backwards (based on the name of the variable "darkProcent"). I think the comparison operator should be >=, not <=.
That got me the answers I was expecting with my test images.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With