将html十六进制颜色分类为几个简单字符串值的函数


PHP: Function to classify html hex colours into a couple of simple string values

是否可以将html十六进制颜色分类为简单的字符串值?

例如,颜色#CC3333,它不是完全红色的,但作为人类,我们可以假设它是红色的。颜色#CCCCCC可以被归类为白色,因为我不想让黑色或灰色参与进来。

可能的简单值至少包括:

    红色
  • 白色
  • 绿色

更多的分类更好,但我至少想要这些颜色。

可以做到吗?

可选信息:

我正在创建一个网络应用程序,通过网络摄像头捕捉图片。用户可以将一张白色或红色的纸放在摄像头前,应用程序就会检测图像的主色调。然后,用户将根据颜色被重定向到不同的选项。我已经完成了颜色检测,但我只想把它分为几种颜色,红色,白色和绿色。

这是一个有点主观的问题,因为是的,这是可以做到的,但确切地说,你将如何做到这一点取决于你的具体应用-颜色本身是非常主观的,因为它是由个人观察的方式。

你需要先把字符串分成红、绿、蓝三个部分:

$colourId = 'CC3333';
list($red, $green, $blue) = str_split($colourId, 2);

那么,将它们转换为整数可能是个好主意:

$red = hexdec($red);
$green = hexdec($green);
$blue = hexdec($blue);

然后您需要对它应用某种逻辑来确定它属于哪个类。怎么做完全取决于你,但也许你可以这样做:

if (max($red, $green, $blue) - min($red, $green, $blue) < 10) {
  // If the values are all within a range of 10, we'll call it white
  $class = 'white'; 
} else if (max($red, $green, $blue) == $red) {
  // If red is the strongest, call it red
  $class = 'red'; 
} else if (max($red, $green, $blue) == $green) {
  // If green is the strongest, call it green
  $class = 'green'; 
} else if (max($red, $green, $blue) == $blue) {
  // If blue is the strongest, call it blue
  $class = 'blue'; 
}

在RGB模型中很难对颜色进行分类,最好将颜色转换为HSL或HSV模型,然后您可以对颜色进行分类。更多信息请访问:http://en.wikipedia.org/wiki/Color_model

首先需要将十六进制格式转换为rgb值。一个简单的谷歌搜索出现了这个页面。我还没有测试过,但如果它不能正常工作,那么我相信你可以找到一个不同的。

一旦你有了rgb值,你需要定义你的颜色范围。以下代码以63.75为间隔创建颜色范围(即每种颜色有4个范围,因此4*4*4 = 64个总范围):

function findColorRange($colorArray){
    //assume $colorArray has the format [r,g,b], where r, g, and b are numbers in the range 0 - 255
    for($i = 0; $i < 256; $i += 51){ //find red range first
        if($colorArray[0] <= $i + 51/2 && $colorArray[0] >= $i - 51/2){
            for($n = 51; $n < 256; $n += 51){ //green
                if($colorArray[1] <= $n + 51/2 && $colorArray[1] >= $n - 51/2){
                    for($z = 51; $z < 256; $z += 51){ //blue
                        if($colorArray[2] <= $z + 51/2 && $colorArray[2] >= $z - 51/2){
                            return array($i,$n,$z);
                        }
                    }
                }
            }
        }
    }
}

上面的函数将返回一个数组,该数组定义所讨论颜色的颜色范围。从那里,您可以将可能的范围映射到您想要的任何字符串。这可能最容易通过创建一个关联数组来实现,其中键是r、g、b的值,值是字符串。例如:

$colorMap = array(
    '0,0,0' => 'white',
    '51,0,0' => 'light gray'
)