Image a way to determine if a bitmap is a black and white image

  • 2020-05-10 18:39:37
  • OfStack

Image pairs: processed bitmaps in the jpg format (headshots)

      algorithm:

      is judged by the RGB value per pixel. As we know, bitmaps are formed by pixels, each pixel has an RBG value, so we can judge whether the image is color by RGB value.

      [RGB] : R for red, G for green, B for blue.

        beginning thoughts:

1, pure color pictures, only to determine whether the pixel color color is black or white, 1 touch non-color color, can be regarded as a color picture.

In grayscale images, it is not possible to judge by whether the pixels are colored or not, but RGB of grayscale pixels has a special feature: (R=G=B)

        algorithm optimization:

      1, pure color, only white and black 2, white RGB [R=G=B=255], black [R=G=B=0];

      2, gray-scale, RGB [R=G=B];

      you can see that both the color scale and the grey scale are RGB [R=G=B]

      encountered problems:

Some of       can be thought of as color pictures, but there is a greenish or reddish-colored situation, which cannot be judged by R=G=B.

     

      although these pictures [R] < > B < > G 】 but color yan roughly 1 is close to gray-scale color pigments, so R G, B difference of this application is not very big, after my test, the invention of the images of color photos of the biased color 】 【 a pixel R, G, absolute maximum B difference does not surpass 50 (R - G R - B G - B), and the color images R B, The difference of G has the maximum absolute value and there are pixels beyond 50.

     

      1, [custom] color offset Diff = Max (| R-G |, | R-B |, | G-B |);

      2. The color picture contains the largest Diff in the picture < 50;

R=G=B, Diff=0.

       


/// <summary>
///  Determine if the picture is color 
/// </summary>
/// <param name="filename"> Image file path </param>
/// <returns></returns>
public bool isBlackWhite(string filename)
{
   Color c = new Color();
   using (Bitmap bmp = new Bitmap(filename))
   {
      // Traverse the pixels of the image 
      for (int y = 0; y < bmp.Height; y++)
      {
         for (int x = 0; x < bmp.Width; x++)
         {
            c = bmp.GetPixel(x, y);
     // Judge the color deviation value of the pixel Diff
            if (GetRGBDiff(c.R, c.G, c.B) > 50)
            {
               return false;
             }
          }
       }
       return true;
    }
}


public int GetRGBDiff(int r,int g,int b)
{
   // Slight, very simple, is to take r-g,r-b,g-b The maximum of the absolute value. 
}


Related articles: