Detect if image is grayscale or color using Imagick

I'm trying to assign a value to an image based on its “saturation level” to see if the image is black and white or color. I use Imagick and found what seems like perfect command-line code, and try to replicate it using the PHP library.

I think I understand the concept:

  • Convert image to HSL.
  • Extract the channel 'g' (which is the S-channel in the HSL).
  • Calculate the average value of this channel.


Command line code

convert '$image_path' -colorspace HSL -channel g -separate +channel -format '%[fx:mean]' info:


My php code

$imagick = new Imagick($image_path);
$imagick->setColorspace(imagick::COLORSPACE_HSL);
print_r($imagick->getImageChannelMean(imagick::CHANNEL_GREEN));


Output

My PHP code does not output the same values, such as command line code. For example, a grayscale image gives 0for command line code, but PHP code gives [mean] => 10845.392051182 [standardDeviation] => 7367.5888849872.

, 0 vs. [mean] => 31380.528443457 [standardDeviation] => 19703.501101904.

0.565309 vs. [mean] => 33991.552881892 [standardDeviation] => 16254.018540044.


, - . - ?

.


, PHP-

$imagick = new Imagick($image_path);
$imagick->setColorspace(imagick::COLORSPACE_HSL);
$imagick->separateImageChannel(imagick::CHANNEL_GREEN);
$imagick->setFormat('%[fx:mean]');

Unable to set format . setFormat('%[fx:mean] info:'), setFormat('%[mean]'), setFormat('%mean') ..



- FIXED!

@danack , transformImageColorspace(), setColorspace(). .

$imagick = new Imagick($image_path);
$imagick->transformImageColorspace(imagick::COLORSPACE_HSL);
$saturation_channel = $imagick->getImageChannelMean(imagick::CHANNEL_GREEN);
$saturation_level = $saturation_channel['mean']/65535;
+4
3

setFormat -format - , Imagick , png, jpg .. info - , Imagick $imagick->identifyImage(true) .

- transformImageColorspace, setColorSpace. , getImageChannelMean.

, . - , :

$imagick = new Imagick($image_path);
$imagickGrey = clone $imagick;
$imagickGrey->setimagetype(\Imagick::IMGTYPE_GRAYSCALE);

$differenceInfo = $imagick->compareimages($imagickGrey, \Imagick::METRIC_MEANABSOLUTEERROR);

if ($differenceInfo['mean'] <= 0.0000001) {
    echo "Grey enough";
}

, , , , , , .

, :

$imageType = $imagick->getImageType();
if ($imageType === \Imagick::IMGTYPE_GRAYSCALE || 
    $imageType === Imagick::IMGTYPE_GRAYSCALEMATTE) {
     //This is grayscale
}
+2

. (, ), , . normalizeImage(imagick::CHANNEL_ALL) . separateImageChannel()

enter image description here

0

:

convert image.png -colorspace HSL -channel g -separate +channel -format "%[fx:mean]" info:

0 1, .

0

Source: https://habr.com/ru/post/1542397/


All Articles