zHs*_*zHs 1 .net c# image-processing
如何识别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
}
Run Code Online (Sandbox Code Playgroud)
获得图像暗度/亮度的想法可以是:
Bitmap bitmap = // the bitmap
var colors = new List<Color>();
for (int x = 0; x < bitmap.Size.Width; x++)
{
for (int y = 0; y < bitmap.Size.Height; y++)
{
colors.Add(bitmap.GetPixel(x, y));
}
}
float imageBrightness = colors.Average(color => color.GetBrightness());
Run Code Online (Sandbox Code Playgroud)
也许将暗图像视为亮度小于0.1(或任何其他相关值)的图像