【问题标题】:How to determine if a bitmap is bright or dark?如何判断位图是亮还是暗?
【发布时间】:2013-10-23 09:08:09
【问题描述】:

我想知道位图是亮还是暗。我意识到“相当亮或暗”并不是一个非常精确的定义,但我只需要想出一些非常简单的东西。

我的想法是将位图转换为单色位图,然后将白色像素的数量与黑色像素的数量进行比较。

这是我的 C# 代码:

private bool IsDark(Bitmap bitmap)
    {
        if (bitmap == null)
            return true;

        var countWhite = 0;
        var countBlack = 0;

        // Convert bitmap to black and white (monchrome)
        var bwBitmap = bitmap.Clone(new Rectangle(0, 0, bitmap.Width, bitmap.Height), PixelFormat.Format1bppIndexed);

        for (int x = 0; x < bwBitmap.Width - 1; x++)
        {
            for (int y = 0; y < bwBitmap.Height - 1; y++)
            {
                var color = bwBitmap.GetPixel(x, y);
                if (color.A == 255)
                    countWhite++;
                else
                    countBlack++;
            }
        }

        return countBlack > countWhite;
    }

我不明白的是:无论我使用什么位图,黑色像素的数量始终为 0。

我错过了什么?

另外:我很确定有更有效的方法来解决这个任务。但是此时我只想明白上面的代码为什么会失败……

谢谢各位! 英格玛

【问题讨论】:

  • color.A代表Alpha通道,与黑白无关。
  • 您的主要调整点现在位于bitmap.Clone() 内部,您几乎无法控制它。您还可以扫描位图并添加 R、G、B 值以获得每像素 0..765 的值。然后你可以平均或计数阈值。
  • (at)Alessandro,就是这样。当然,在运行我的代码时,我也检查了其他属性(例如 R、G、B、Name),但它们总是指向 White。我不知道为什么我最终检查了 Alpha 通道。无论如何,这是一个愚蠢的想法。我现在正在检查 color.Name == "ffffffff",现在它可以工作了。
  • (at)Ratna 和 Henk:谢谢,但对我的目的而言,这有点复杂。

标签: c# image-processing bitmap


【解决方案1】:

首先,您可以尝试以下方法:

if (color.R == 0 && color.G == 0 && color.B == 0)
{
    // black
    countBlack++;
}
else if (color.R == 255 && color.G == 255 && color.B == 255)
{
    // white
    countWhite++;
}
else
{
    // neither black or white
}

附注GetPixel(x, y) 很慢,看看Bitmap.LockBits

【讨论】:

  • (at)Alessandro:是的,这很好用。谢谢!感谢您提出召集 Bitmap.LockBits 的建议。我知道这一点,但正如我在原始帖子中所写,此时我只想了解我的代码出了什么问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-16
  • 2011-01-31
  • 2014-05-06
  • 1970-01-01
相关资源
最近更新 更多