如何找到图像中的主色? [英] How to find the Dominant color in image?

查看:174
本文介绍了如何找到图像中的主色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到图像中的主色, 我该怎么办?

i want to find the dominant color in image, how can i do it ?

如果我可以用十六进制代码(例如,#eeeeee)得到它,那就太好了

it would be great if i can get this in HEX code (exm: #eeeeee)

推荐答案

要在图像中找到最显性"的颜色,即图像中最普遍的颜色:您需要创建图像的直方图图片.

To find the most "dominant" color in an image, meaning the color that is most prevalent in the image: you'd need to create a histogram of the image.

这是此有关如何在PHP中创建直方图的文章中的代码. (该网站已离线多次)

Here is an the code from this article on how to create a histogram in PHP. (Website has gone off line several times)

<?php
$source_file = "test_image.jpg";

// histogram options

$maxheight = 300;
$barwidth = 2;

$im = ImageCreateFromJpeg($source_file);

$imgw = imagesx($im);
$imgh = imagesy($im);

// n = total number or pixels

$n = $imgw*$imgh;

$histo = array();

for ($i=0; $i<$imgw; $i++)
{
        for ($j=0; $j<$imgh; $j++)
        {

                // get the rgb value for current pixel

                $rgb = ImageColorAt($im, $i, $j);

                // extract each value for r, g, b

                $r = ($rgb >> 16) & 0xFF;
                $g = ($rgb >> 8) & 0xFF;
                $b = $rgb & 0xFF;

                // get the Value from the RGB value

                $V = round(($r + $g + $b) / 3);

                // add the point to the histogram

                $histo[$V] += $V / $n;

        }
}

// find the maximum in the histogram in order to display a normated graph

$max = 0;
for ($i=0; $i<255; $i++)
{
        if ($histo[$i] > $max)
        {
                $max = $histo[$i];
        }
}

echo "<div style='width: ".(256*$barwidth)."px; border: 1px solid'>";
for ($i=0; $i<255; $i++)
{
        $val += $histo[$i];

        $h = ( $histo[$i]/$max )*$maxheight;

        echo "<img src=\"img.gif\" width=\"".$barwidth."\"
height=\"".$h."\" border=\"0\">";
}
echo "</div>";
?> 

在该示例中,$max是您最显眼"的颜色.

In that example $max is your most "dominant" color.

这篇关于如何找到图像中的主色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆