检测图片的“整体平均”颜色

问题描述 投票:45回答:6

我有一个jpg图像。

我需要知道“整体平均”的图像颜色。乍一看,可以使用图像的直方图(通道RGB)。

在工作中我主要使用JavaScript和PHP(一点点Python)因此欢迎这些语言的决定。也许是用于处理解决类似问题的图像的库。

我不需要动态确定图片的颜色。我只需要浏览整个图像阵列并分别确定每种图像的颜色(这些信息我将记住以备将来使用)。

php javascript python image-processing
6个回答
70
投票

您可以使用PHP来获取调色板的数组,如下所示:

<?php 
function colorPalette($imageFile, $numColors, $granularity = 5) 
{ 
   $granularity = max(1, abs((int)$granularity)); 
   $colors = array(); 
   $size = @getimagesize($imageFile); 
   if($size === false) 
   { 
      user_error("Unable to get image size data"); 
      return false; 
   } 
   $img = @imagecreatefromjpeg($imageFile);
   // Andres mentioned in the comments the above line only loads jpegs, 
   // and suggests that to load any file type you can use this:
   // $img = @imagecreatefromstring(file_get_contents($imageFile)); 

   if(!$img) 
   { 
      user_error("Unable to open image file"); 
      return false; 
   } 
   for($x = 0; $x < $size[0]; $x += $granularity) 
   { 
      for($y = 0; $y < $size[1]; $y += $granularity) 
      { 
         $thisColor = imagecolorat($img, $x, $y); 
         $rgb = imagecolorsforindex($img, $thisColor); 
         $red = round(round(($rgb['red'] / 0x33)) * 0x33); 
         $green = round(round(($rgb['green'] / 0x33)) * 0x33); 
         $blue = round(round(($rgb['blue'] / 0x33)) * 0x33); 
         $thisRGB = sprintf('%02X%02X%02X', $red, $green, $blue); 
         if(array_key_exists($thisRGB, $colors)) 
         { 
            $colors[$thisRGB]++; 
         } 
         else 
         { 
            $colors[$thisRGB] = 1; 
         } 
      } 
   } 
   arsort($colors); 
   return array_slice(array_keys($colors), 0, $numColors); 
} 
// sample usage: 
$palette = colorPalette('rmnp8.jpg', 10, 4); 
echo "<table>\n"; 
foreach($palette as $color) 
{ 
   echo "<tr><td style='background-color:#$color;width:2em;'>&nbsp;</td><td>#$color</td></tr>\n"; 
} 
echo "</table>\n";

这为您提供了一个数组,其值越大,使用颜色的频率就越高。

编辑评论者询问如何在目录中的所有文件上使用它,这里是:

    if ($handle = opendir('./path/to/images')) {

        while (false !== ($file = readdir($handle))) {
           $palette = colorPalette($file, 10, 4);
           echo "<table>\n"; 
           foreach($palette as $color) { 
               echo "<tr><td style='background-color:#$color;width:2em;'>&nbsp;</td><td>#$color</td></tr>\n"; 
           } 
           echo "</table>\n";
        }
        closedir($handle);
    }

可能不想在太多文件上执行此操作,但它是您的服务器。

或者,如果您更愿意使用Javascript,那么Lokesh's Color-Theif库正是您正在寻找的。


4
投票

结合JKirchartz和Alexander Hugestrand回答:

 function getAverage($sourceURL){

    $image = imagecreatefromjpeg($sourceURL);
    $scaled = imagescale($image, 1, 1, IMG_BICUBIC); 
    $index = imagecolorat($scaled, 0, 0);
    $rgb = imagecolorsforindex($scaled, $index); 
    $red = round(round(($rgb['red'] / 0x33)) * 0x33); 
    $green = round(round(($rgb['green'] / 0x33)) * 0x33); 
    $blue = round(round(($rgb['blue'] / 0x33)) * 0x33); 
    return sprintf('#%02X%02X%02X', $red, $green, $blue); 
 }

尝试并测试,返回十六进制字符串。


2
投票

对于真彩色图像,更简单的解决方案是将其缩小到1x1像素大小并在该像素处采样颜色:

$ scaled = imagescale($ img,1,1,IMG_BICUBIC); $ meanColor = imagecolorat($ img,0,0);

......但我自己没有测试过。


2
投票
$img = glob('img/*');
foreach ($img as $key => $value) {
    $info = getimagesize($value);
    $mime = $info['mime'];
    switch ($mime) {
        case 'image/jpeg':
            $image_create_func = 'imagecreatefromjpeg';
            break;
        case 'image/png':
            $image_create_func = 'imagecreatefrompng';
            break;
        case 'image/gif':
            $image_create_func = 'imagecreatefromgif';
            break;
    }
    $avg = $image_create_func($value);
    list($width, $height) = getimagesize($value);
    $tmp = imagecreatetruecolor(1, 1);
    imagecopyresampled($tmp, $avg, 0, 0, 0, 0, 1, 1, $width, $height);
    $rgb = imagecolorat($tmp, 0, 0);
    $r = ($rgb >> 16) & 0xFF;
    $g = ($rgb >> 8) & 0xFF;
    $b = $rgb & 0xFF;
    echo '<div style="text-align:center; vertical-align: top; display:inline-block; width:100px; height:150px; margin:5px; padding:5px; background-color:rgb('.$r.','.$g.','.$b.');">';
    echo '<img style="width:auto; max-height:100%; max-width: 100%; vertical-align:middle; height:auto; margin-bottom:5px;" src="'.$value.'">';
    echo '</div>';

您可以使用$ r,$ g和$ b重新取样平均颜色的值,图像比仅缩放它更好!


1
投票

从PIL开始。 http://www.pythonware.com/products/pil/

打开Image对象。使用getdata方法获取所有像素。平均你得到的值。

像这样的东西。

Image color detection using python


0
投票

我创建了一个composer包,它提供了一个库,用于通过路径从给定图像中选择平均颜色。

您可以通过在项目目录中运行以下命令来安装它:

composer require tooleks/php-avg-color-picker

用法示例:

<?php

use Tooleks\Php\AvgColorPicker\Gd\AvgColorPicker;

$imageAvgHexColor = (new AvgColorPicker)->getImageAvgHexByPath('/absolute/path/to/the/image.(jpg|jpeg|png|gif)');

// The `$imageAvgHexColor` variable contains the average color of the given image in HEX format (#fffff).

documentation

© www.soinside.com 2019 - 2024. All rights reserved.