How do I determine if a color is closer to white or black?

前端 未结 4 1597
别那么骄傲
别那么骄傲 2021-02-01 07:26

I am dealing with images and would like to determine if a set of pixels are closer to white or black.

So given a set of colors/pixles, how does one det

相关标签:
4条回答
  • 2021-02-01 07:30
    • Convert the colour to grayscale (a grayscale colour has all 3 RGB components equal, see convert color image to grayscale).

    • Check if grayscale is closer to black (0) or white (255)

    0 讨论(0)
  • 2021-02-01 07:38

    I would say that you can first convert the color to gray scale and then check if it's nearer to black or white.

    First convert the RGB color value to compute luminance by the following formula

    Y = 0.2126*R + 0.7152*G + 0.0722*B
    

    Then check if the value is nearer to 0 or to 255 and choose black or white accordingly

    color c = Y < 128 ? black : white
    

    Mind that this works well if the color space is not gamma compressed, otherwise you will have to add a step before calculating the luminance which is a gamma expansion, compute Y, then perform a gamma compression to obtain a non-linear luminance value that you can then use to decide if color is nearer to black or white.

    0 讨论(0)
  • 2021-02-01 07:40

    There are two potential meanings of white and black:

    • Colour spectrum of visible light
    • Human skin tones as determined by race, amount of tan etc.

    The former is easy: convert to greyscale range 0-255. 127 or less is closer to black (0), 128 or above is closer to white (255).

    I use the following function to convert to greyscale using luminance values (assuming an int ARGB format for input colour):

    public static int getLuminance(int argb) {
        int lum= (   77  * ((argb>>16)&255) 
                   + 150 * ((argb>>8)&255) 
                   + 29  * ((argb)&255))>>8;
        return lum;
    }
    

    The latter definition (human skin tones) is impossible to do with a simple algorithm as it depends on light condition, camera settings, exposure etc. An RGB vlaue of (190,115,60) is probably approximately the midpoint in typical conditions

    0 讨论(0)
  • 2021-02-01 07:54

    Take a look at YCbCr. Since Java and most computer processes colors in RGB format, you will need to do some conversion from RGB to YCbCr. There are many formulas to convert RGB to YCbCr.

    Once you get the YCbCr value, you can check the luminance value (the value Y in YCbCr).

    0 讨论(0)
提交回复
热议问题