dvy*_*yio 5 php colors imagemagick imagick imagemagick-convert
我正在尝试根据图像的"饱和度"为图像赋值,以查看图像是黑白还是彩色.我正在使用Imagick,并且发现了似乎是命令行的完美代码,并尝试使用PHP库复制它.
我想我理解这个概念:
convert '$image_path' -colorspace HSL -channel g -separate +channel -format '%[fx:mean]' info:
Run Code Online (Sandbox Code Playgroud)
$imagick = new Imagick($image_path);
$imagick->setColorspace(imagick::COLORSPACE_HSL);
print_r($imagick->getImageChannelMean(imagick::CHANNEL_GREEN));
Run Code Online (Sandbox Code Playgroud)
但是,我的PHP代码不会输出与命令行代码相同的值.例如,灰度图像提供0
命令行代码,但PHP代码给出[mean] => 10845.392051182 [standardDeviation] => 7367.5888849872
.
同样,另一灰度图像给出了0
对[mean] => 31380.528443457 [standardDeviation] => 19703.501101904
.
彩色图像给出了0.565309
对比[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]');
Run Code Online (Sandbox Code Playgroud)
但是Unable to set format
当我尝试设置格式时出现错误.我也试过setFormat('%[fx:mean] info:')
,setFormat('%[mean]')
,setFormat('%mean')
,等.
感谢@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;
Run Code Online (Sandbox Code Playgroud)
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";
}
Run Code Online (Sandbox Code Playgroud)
如果您的图像具有同样透明的颜色区域,那么这可能是合适的 - 因此理论上它们具有颜色,但不可见。
或者,如果您只关心图像是否是灰度格式:
$imageType = $imagick->getImageType();
if ($imageType === \Imagick::IMGTYPE_GRAYSCALE ||
$imageType === Imagick::IMGTYPE_GRAYSCALEMATTE) {
//This is grayscale
}
Run Code Online (Sandbox Code Playgroud)