检测明亮和黑暗的图像 [英] Detect bright and dark images

查看:112
本文介绍了检测明亮和黑暗的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有来自stackoverflow的代码来检测明亮和黑暗的图像

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.

例如,如果我打电话

IsDark(bitmap, 40, 0.9); // this always sees the image as bright

从0.1到0.99的任何值都会返回一个明亮的图像和任何高于0.99的其他值将所有图像返回为暗。

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.

即使设置为1到250,公差值似乎也没有效果。

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


推荐答案

好看,看了之后再次,我注意到函数末尾的比较向后看(基于变量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.

这篇关于检测明亮和黑暗的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆