繁体   English   中英

如何找到图像中的所有像素都是灰度或每个像素的 R、G、B 值相等

[英]How to find that all pixels in an image are grey scale or has R,G,B equal value for each individual pixel

请不要引用这个如何检查位图的颜色深度? 如何检查图片是否为灰度

因为即使所有唯一颜色都是灰度或小于 256 并且每个像素可以是 24 或 32 位,图像也可以是每像素 24/32 位。

我如何找到图像Bitmap.GetPixel(x, y)中的像素具有相等的 R、G、B 值,以便我可以找出图像中的所有像素是否都在灰度范围内。 因为灰度像素的 R、G、B 值是相同的。 或者有没有更好的方法来确定图像是否为灰度?

我正在编写一个代码来压缩 16/24/32 位图像的大小,这样如果图像有 256 种独特的颜色,则将其更改为 8 位图像并保存。

首先,我计算每像素高于 8 的图像中的独特颜色。

如果图像中的唯一颜色小于或等于 256,则

  1. 如果所有独特的颜色都在灰度范围内,则将其转换为灰度
  2. 否则,如果任何颜色不是灰度,则将图像转换为 8 BPP

uint UniqueColors(Bitmap Bitmap)
{
    try
    {
        List<int> lstColors = new List<int>();

        if (null == Bitmap)
            return 0;

        for (int iCount = 0; iCount < Bitmap.Height; iCount++)
            for (int iCounter = 0; iCounter < Bitmap.Width; iCounter++)
                if (!lstColors.Contains(Bitmap.GetPixel(iCounter, iCount).ToArgb()))
                    lstColors.Add(Bitmap.GetPixel(iCounter, iCount).ToArgb());

        Bitmap.Dispose();

        return Convert.ToUInt32(lstColors.Count);
    }
    catch (Exception)
    {
        Bitmap.Dispose();
        return 0;
    }
}

进而:

if (256 >= UniqueColors(new Bitmap(string ImagePath)))
{
    if (Is_Greyscale(new Bitmap(ImagePath))
        Convert_To_Greyscale(ImagePath);
    else
        Convert_To_8Bits(ImagePath);
}

现在我被困住了,我如何发现图像中的每种独特颜色是否都处于灰色地带。 我的意思是每种独特的颜色都具有相同的 (R, G, B) 值。 比如 R=G=B。 如何在我的代码行中找到它

Bitmap.GetPixel(iCounter, iCount).ToArgb()

Bitmap.GetPixel()返回一个Color结构,该结构具有RGB字段,因此您可以根据需要进行比较。

请注意,使用GetPixel()的速度非常慢,但是如果不需要速度,它将可以。

好的,您需要获取位序列的RGB分量。 可以说该序列为24位,因此您具有以下位序列:

RRRRRRRRGGGGGGGGBBBBBBBB

其中R代表redG代表greenB代表蓝色。 要分开,可以使用按位运算符。

color = Bitmap.GetPixel(iCounter, iCount).ToArgb();
blue  = color & 0xFF;          // Get the 1st 8 bits
green = (color >> 8)  & 0xFF;  // Remove the 1st 8 bits and take the 2n 8 bits
red   = (color >> 16) & 0xFF;  // Remove the 1st 16 bits and take the 3rd 8 bits

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM