gpt4 book ai didi

c# - 如何在 C# 中识别黑色或深色图像?

转载 作者:太空宇宙 更新时间:2023-11-03 17:16:27 24 4
gpt4 key购买 nike

如何在 C# 中识别黑色/深色图像。是否有任何 API 可以检查图像可见度或暗度比?在我的应用程序中,在复制图像时,我想检查每个图像并希望丢弃黑色图像。

知道如何实现吗?

最佳答案

// 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;
}

public void Run(Bitmap bitmap) { // Example of use
// some code
bool dark = IsDark(bitmap, 40, 0.9);
// some code
}

关于c# - 如何在 C# 中识别黑色或深色图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1587674/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com