简体   繁体   中英

PerlMagick: Use QueryColorname() from Histogram() output

I want to get histogram of unique color in an image with color names or their Hex code.

I am unable to convert histogram method output value into color name or Hex code using QueryColorname method; It always returns black and does not return Hex code.

It is possibly due to (0 ... 65535) result range from histogram() method which I am not able to convert into (0 .. 255), an acceptable range for Querycolorname() method.

#!/usr/bin/perl
use Image::Magick;

$image=Image::Magick->new();
$image->ReadImage('Sun.jpeg'); 

my @histogram = $image->Histogram();
print "Red\tGreen\tBlue\tOpacity\tCount\tName\n";
for(my $i=0; $i<=29; $i++){ #Get 5 unique colors
   print "$histogram[$i]\t";
   if (($i+1)%5 == 0){ #Array elements of unique color
      my $name = $image->QueryColorname('rgb16($histogram[$i-4],$histogram[$i-3],$histogram[$i-    2],$histogram[$i-1])');
      print "$name\n";
   }
}

Result looks like,

Red Green Blue Opacity Count Name
0 0 0 0 16134 black
257 257 257 0 27 black
0 257 0 0 303 black
257 0 0 0 286 black
257 257 0 0 8 black
71 0 0 0 82 black

Method descriptions at http://www.imagemagick.org/script/perl-magick.php

First of all: as you are using single quotes around variables they don't get expanded. QueryColorname sees a string that it possibly converts to zero's. That's why all colors are "black".

Second: I don't see rgb16 in the docu and I suppose it does not do what you want. Instead, you have to scale down to 8 Bit

Putting both together I propose something like this for the inner if-Block:

my $colVec = "rgb(";
$colVec .= int($histogram[$i-4]/65535*256) . ",";
$colVec .= int($histogram[$i-3]/65535*256) . ",";
$colVec .= int($histogram[$i-2]/65535*256) . ",";
$colVec .= $histogram[$i-1] . ")";
print $image->QueryColorname($colVec) . "\n";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM