如何发现图像中的所有像素都是灰度级,或者每个像素的R,G,B值相等

请不要引用此问题如何检查位图的颜色深度? 或如何检查图片是否为灰度

因为即使所有独特颜色都是灰度级或小于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 lstColors = new List(); 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 

其中Rred的位, Ggreen的位, B是蓝色的位。 要将其分开,可以使用按位运算符。

 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