且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何确定颜色是否更接近白色或黑色?

更新时间:2023-01-26 21:59:09

我会说,你可以先将颜色转换为灰度,然后检查它是否更接近黑色或白色。

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

首先转换RGB颜色值计算亮度以下公式

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

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

然后检查值是否更接近0或255,并相应地选择黑色或白色

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

color c = Y < 128 ? black : white

请注意,如果颜色空间不是gamma压缩,在计算作为γ扩展的亮度之前添加一个步骤,计算Y,然后执行γ压缩以获得非线性亮度值,然后可以使用该非线性亮度值决定颜色是否更接近黑色或白色。

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.