【问题标题】:Is this possible to detect a colour is a light or dark colour?这是否可以检测颜色是浅色还是深色?
【发布时间】:2014-05-01 11:05:09
【问题描述】:

考虑这两个粉红色的正方形:

还有这个:

您可能知道,一种颜色较浅,一种颜色较深或更锐利。 问题是,我可以用肉眼来判断,但这是否可以使用系统方式或程序方式来检测这些信息?至少,这是否可能有一个值告诉我颜色更像白色或颜色不像白色? (假设我得到了该颜色的 RGB 代码。)谢谢。

【问题讨论】:

标签: javascript php colors comparison


【解决方案1】:

以下是确定浅色或深色的 Python 代码。该配方基于 HSP 值。 HSP(Highly Sensitive Poo)方程来自http://alienryderflex.com/hsp.html,用于判断颜色是浅色还是深色。

import math
def isLightOrDark(rgbColor=[0,128,255]):
    [r,g,b]=rgbColor
    hsp = math.sqrt(0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b))
    if (hsp>127.5):
        return 'light'
    else:
        return 'dark'

【讨论】:

  • 只是一个小的优化:在hsp计算中不用平方根,你可以将非平方根的结果与当前常数的平方值进行比较:127.5 * 127.5 = @987654324 @ 或 16256,取决于你想要的精确度。
【解决方案2】:

由于您没有指定任何特定的语言/脚本来检测较暗/较亮的十六进制,我想为此贡献一个 PHP 解决方案

Demo

$color_one = "FAE7E6"; //State the hex without #
$color_two = "EE7AB7";

function conversion($hex) {
    $r = hexdec(substr($hex,0,2)); //Converting to rgb
    $g = hexdec(substr($hex,2,2));
    $b = hexdec(substr($hex,4,2));

    return $r + $g + $b; //Adding up the rgb values
}

echo (conversion($color_one) > conversion($color_two)) ? 'Color 1 Is Lighter' : 'Color 1 Is Darker';
//Comparing the two converted rgb, the greater one is darker

正如@Some Guy 所指出的,我已经修改了我的函数以获得更好/更准确的结果... (增加亮度)

function conversion($hex) {
    $r = 0.2126*hexdec(substr($hex,0,2)); //Converting to rgb and multiplying luminance
    $g = 0.7152*hexdec(substr($hex,2,2));
    $b = 0.0722*hexdec(substr($hex,4,2));

    return $r + $g + $b;
}

Demo 2

【讨论】:

猜你喜欢
  • 2021-09-11
  • 1970-01-01
  • 2014-08-07
  • 2015-04-12
  • 1970-01-01
  • 2014-10-15
  • 2020-12-21
  • 2016-07-01
  • 2011-11-28
相关资源
最近更新 更多