2012-04-24 4 views
20

Dribbble.com에서 수행하는 기능을 이미지의 주 색상을 감지하여 복제하려고합니다. 아래 이미지에서 Dribbble.com의 스크린 샷을 볼 수 있습니다.이 스크린 샷은 왼쪽 이미지의 8 가지 주요 색상을 보여줍니다. 다음은 이미지의 실제 페이지입니다. http://dribbble.com/shots/528033-Fresh-Easy?list=followingPHP로 이미지의 주 색상을 감지합니다.

PHP에서이 작업을 수행 할 수 있어야합니다. 필요한 색상을 얻을 수 있어야 데이터베이스에 저장할 수 있으므로 모든 페이지에서 처리 할 필요가 없습니다. 하중.

이미지에서 이러한 색상을 얻는 방법에 대한 연구가 끝난 후 일부 사람들은 픽셀 단위로 이미지를 검토 한 다음 가장 많이 발생하는 색상을 저장한다고 말했습니다. 다른 사람들은 더 많은 것이 있다고 말합니다. 가장 빈번하게 존재하는 색상을 얻는 것이 원하는 영향을주지는 못합니다. 그들은 당신이 이미지/색상을 Quantize 할 필요가 있다고 말합니다 (나는이 시점에서 길을 잃었습니다). 아래 같은 일을하는 자바 스크립트 라이브러리, 해당 페이지는 내가 quantize.js라는 자바 스크립트 파일이 볼 수있는 페이지의 소스보기 여기 http://lokeshdhakar.com/projects/color-thief/

볼 수있는 드리블 슛 아래 이미지에서

및 결과는 정말 좋습니다. 그래서 나는 PHP와 이미지의 색상을 반환하고 계산합니다이 기능을 발견했다

enter image description here


를 PHP와 자바 스크립트 라이브러리가 있지만, 무엇을 그렇게 할 수 있기를 희망하고 GD/ImageMagick를하고있다 하지만 결과는 위의 자바 스크립트 버전과 다른과 드리블이 사람이 내가 PHP와 같은 작업을 할 수있는 방법을 알고있는 경우

/** 
* Returns the colors of the image in an array, ordered in descending order, where the keys are the colors, and the values are the count of the color. 
* 
* @return array 
*/ 
function Get_Color() 
{ 
    if (isset($this->image)) 
    { 
     $PREVIEW_WIDTH = 150; //WE HAVE TO RESIZE THE IMAGE, BECAUSE WE ONLY NEED THE MOST SIGNIFICANT COLORS. 
     $PREVIEW_HEIGHT = 150; 
     $size = GetImageSize($this->image); 
     $scale=1; 
     if ($size[0]>0) 
     $scale = min($PREVIEW_WIDTH/$size[0], $PREVIEW_HEIGHT/$size[1]); 
     if ($scale < 1) 
     { 
      $width = floor($scale*$size[0]); 
      $height = floor($scale*$size[1]); 
     } 
     else 
     { 
      $width = $size[0]; 
      $height = $size[1]; 
     } 
     $image_resized = imagecreatetruecolor($width, $height); 
     if ($size[2]==1) 
     $image_orig=imagecreatefromgif($this->image); 
     if ($size[2]==2) 
     $image_orig=imagecreatefromjpeg($this->image); 
     if ($size[2]==3) 
     $image_orig=imagecreatefrompng($this->image); 
     imagecopyresampled($image_resized, $image_orig, 0, 0, 0, 0, $width, $height, $size[0], $size[1]); //WE NEED NEAREST NEIGHBOR RESIZING, BECAUSE IT DOESN'T ALTER THE COLORS 
     $im = $image_resized; 
     $imgWidth = imagesx($im); 
     $imgHeight = imagesy($im); 
     for ($y=0; $y < $imgHeight; $y++) 
     { 
      for ($x=0; $x < $imgWidth; $x++) 
      { 
       $index = imagecolorat($im,$x,$y); 
       $Colors = imagecolorsforindex($im,$index); 
       $Colors['red']=intval((($Colors['red'])+15)/32)*32; //ROUND THE COLORS, TO REDUCE THE NUMBER OF COLORS, SO THE WON'T BE ANY NEARLY DUPLICATE COLORS! 
       $Colors['green']=intval((($Colors['green'])+15)/32)*32; 
       $Colors['blue']=intval((($Colors['blue'])+15)/32)*32; 
       if ($Colors['red']>=256) 
       $Colors['red']=240; 
       if ($Colors['green']>=256) 
       $Colors['green']=240; 
       if ($Colors['blue']>=256) 
       $Colors['blue']=240; 
       $hexarray[]=substr("0".dechex($Colors['red']),-2).substr("0".dechex($Colors['green']),-2).substr("0".dechex($Colors['blue']),-2); 
      } 
     } 
     $hexarray=array_count_values($hexarray); 
     natsort($hexarray); 
     $hexarray=array_reverse($hexarray,true); 
     return $hexarray; 

    } 
    else die("You must enter a filename! (\$image parameter)"); 
} 

그래서 내가 부탁하고 결과? 당신이 알고있는 이미 존재하는 어떤 것 또는 나에게 이것에 대한 한 걸음 더 가까이 다가 가기위한 어떤 조언도 인정 될 것입니다.

+0

http://stackoverflow.com/questions/3468500/detect-overall-average-color-of-the-picture –

+0

@aSeptik 이미 게시 한 코드와 동일하게 보이게됩니다. – JasonDavis

+0

시도해 보셨습니까? ''이미지에서 컬러 팔레트 가져 오기 ''를 위해 google 검색 ""나는 많은 결과를 창출했다. 그냥 묻고 ... –

답변

24

당신은 PHP에서 찾고있는 정확히 : https://github.com/thephpleague/color-extractor

예 :이 이미지의 주요 색상을 얻기 위해 내 간단한 방법은

require 'vendor/autoload.php'; 

use League\ColorExtractor\Client as ColorExtractor; 

$client = new ColorExtractor; 

$image = $client->loadPng('./some/image.png'); 

// Get the most used color hexadecimal codes from image.png 
$palette = $image->extract(); 
+0

C에 대한 포트에 대한 좋은 동사 표시처럼 보입니다. – quickshiftin

3

당신이 링크 한 페이지는 GitHub의 소스 코드에 대한 링크를 가지고 있습니다. PHP에서 소스를 복제 할 수 있습니다.

그들이하는 일과 수행하는 방식의 큰 차이점은 클러스터링을 사용하여 색상을 찾는 것입니다. 색상을 저장할 때 색상을 반올림하는 대신 배열에 모든 원시 색상을 저장합니다. 그런 다음 클러스터의 가장 높은 비율의 클러스터가 클러스터의 색상 수와 일치 할 때까지이 배열을 반복합니다. 이것의 중심점이 가장 일반적인 색상입니다. 그런 다음 팔레트는 다음으로 높은 클러스터 세트로 정의되며 클러스터의 거의 완전한 중첩을 방지하는 일부 논리가 있습니다.

다음
5

입니다

<?php 

    $image=imagecreatefromjpeg('image.jpg'); 
    $thumb=imagecreatetruecolor(1,1); imagecopyresampled($thumb,$image,0,0,0,0,1,1,imagesx($image),imagesy($image)); 
    $mainColor=strtoupper(dechex(imagecolorat($thumb,0,0))); 
    echo $mainColor; 

?> 
5

당신에게 사진의 크기를 줄여야하고 사진의 주 색상이 나옵니다. 팔레트에서 4 가지 색상이 필요하면 약 8x8, 6 색상은 12x8 등으로 축소하십시오.축소 이미지

imagecopyresized 다음

<?php 

// EXAMPLE PICTURE 
$url='https://www.nordoff-robbins.org.uk/sites/default/files/google.jpg'; 

//var_dump(getColorPallet($url)); 

echoColors(getColorPallet($url)); 


function echoColors($pallet){ // OUTPUT COLORSBAR 
    foreach ($pallet as $key=>$val) 
     echo '<div style="display:inline-block;width:50px;height:20px;background:#'.$val.'"> </div>'; 
} 

function getColorPallet($imageURL, $palletSize=[16,8]){ // GET PALLET FROM IMAGE PLAY WITH INPUT PALLET SIZE 
    // SIMPLE CHECK INPUT VALUES 
    if(!$imageURL) return false; 

    // IN THIS EXEMPLE WE CREATE PALLET FROM JPG IMAGE 
    $img = imagecreatefromjpeg($imageURL); 

    // SCALE DOWN IMAGE 
    $imgSizes=getimagesize($imageURL); 

    $resizedImg=imagecreatetruecolor($palletSize[0],$palletSize[1]); 

    imagecopyresized($resizedImg, $img , 0, 0 , 0, 0, $palletSize[0], $palletSize[1], $imgSizes[0], $imgSizes[1]); 

    imagedestroy($img); 

    //CHECK IMAGE 
    /*header("Content-type: image/png"); 
    imagepng($resizedImg); 
    die();*/ 

    //GET COLORS IN ARRAY 
    $colors=[]; 

    for($i=0;$i<$palletSize[1];$i++) 
     for($j=0;$j<$palletSize[0];$j++) 
      $colors[]=dechex(imagecolorat($resizedImg,$j,$i)); 

    imagedestroy($resizedImg); 

    //REMOVE DUPLICATES 
    $colors= array_unique($colors); 

    return $colors; 

} 
?> 

나를 위해 완벽한 작품이 밖으로 시도 모든 픽셀을 선택하고 배열 imagecolorat($image,px,py)

에 저장합니다.

+0

이것은 멋진 기능입니다. 경량의 색상 얻기 예제. 최고 사용 색상으로 제한하는 방법이 있습니까? 예를 들어 이미지에서 상위 8 개 색상이 사용 되었습니까? – JasonDavis

0

이 시도 : JPEG 및 PNG와 http://www.coolphptools.com/color_extract

작품.

그리고 작곡가와 최고! : 더 허슬, 단지

require_once 'colorextract/colors.inc.php'; 
$ex=new GetMostCommonColors(); 
$num_results=20; 
$reduce_brightness=1; 
$reduce_gradients=1; 
$delta=24; 
$colors=$ex->Get_Color('image.png', $num_results, $reduce_brightness, $reduce_gradients, $delta); 
print_r($colors); 

require_once를 당신에게 같은 것을 제공 :

배열 ( [3060a8] => 0.55827380952381 [f0a848] => 0.19791666666667 => 0.069642857142857 [483018] => 0.02047619047619 => 0.01827380952381 => 0.01797619047619,515,[4878a8] => 0.016011904761905 [181,800] => 0.015119047619048 [a87830] => 0.014345238095238 [a8c0d8] => 0.011904761904762 [6090c0] => 0.01172619047619 [d89030] => 0.011011904761905 [90a8d8] => 0.0071428571428571 [FFFFFF] => 0.0070238095238095 [604,830] => 0.006547619047619 [f0f0f0] => 0.0063095238095238 [d8d8f0] => 0.005297619047619 [c0d8d8] => 0.0044047619047619 [f0f0ff] => 0.00041666666666667 [181,830] => 0.00011904761904762)

다른 이미지를 사용해 보았는데 믿을만한 것 같습니다.

관련 문제