我從這個代碼從stackoverflow答案來檢測明亮和黑暗的圖像檢測明亮和黑暗的圖像
問題是,它不起作用,我不知道爲什麼。
例如,如果我打電話
IsDark(bitmap, 40, 0.9); // this always sees the image as bright
從0.1到0.99的回報明亮的圖像和在0.99以上的回報的所有圖像作爲暗的任何其他值的任何值。
公差值似乎有即使設置爲1到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;
}
是不是'0.9'的百分比?我會嘗試傳入更高的'darkPercent' ..而不是更高的'容差'。 –
發佈示例代碼的用戶寫道,它應該使用0.9的百分比和40的容差值。 我已經嘗試過從1到100的任何其他值,百分比仍然是相同的結果。 –