Detect if image is grayscale or color using Imagick

天涯浪子 提交于 2019-12-04 07:31:36

setFormat doesn't replicate the command line option -format - the one in Imagick tries to set the image format, which should be png, jpg etc. The one in the command line is setting the format for info - the closest match for which in Imagick is calling $imagick->identifyImage(true) and parsing the results of that.

Also you're just calling the wrong function - it should be transformImageColorspace not setColorSpace. If you use that you can use the statistics from getImageChannelMean.

There are other ways to test for greyness which may be more appropriate under certain circumstances. The first is to convert the a clone of the image to grayscale, and then compare it to the original image:

$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";
}

That would probably be appropriate if you image had areas of color that were also transparent - so they theoretically have color, but not visibly.

Or if you only care about whether the image is of a grayscale format:

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

I found a command line here:

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

It prints a number between 0 and 1, where zero means grayscale.

If your images have tint. (from scanner as example) you should do auto color for them before detecting gray scale. You should normalizeImage(imagick::CHANNEL_ALL) for all separate channels of image. separateImageChannel()

But

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!