JavaScript-PHP或JS:将图像转换为黑白时,调整颜色通道级别

我正在寻求有关如何调整黑白(或灰度)图像的颜色通道级别的帮助.在Photoshop中,此功能称为“黑白”滤镜.

下面的示例演示了我的过程.最终图像中的红色衬衫(是理想的中灰色)为黑色.

原始图片

将色相更改为绿色

最终图像现在为黑白(中灰/红色衬衫为黑色)

解决方法:

使用Imagemagick,您可以使用-level运算符来调整黑色和黑色.白色端点,然后可以将其应用于特定的颜色channel.

例:

 convert source.png -level 45%,80% out.png

对于PHP的Imagick library,您将使用Imagick::levelImage方法.

$img = new Imagick('source.png');
$quantum = $img->getQuantumRange()['quantumRangeLong'];
$img->levelImage(0.45 * $quantum, 1.0, 0.80 * $quantum, Imagick::CHANNEL_ALL);

更新资料

要生成中间图像(绿色衬衫),您可以对-modulate使用“红色->绿色”色调调制.Hue Modulation文档中的示例.

convert source.jpg -modulate 100,100,166.6 green.png
// or in PHP
Imagick::modulateImage ( float $brightness , float $saturation , float $hue )

现在将颜色换成黑色,只需使用-fuzz-opaque.但是,老实说,所有绿色都会使我想起Chroma Key,它被定义为…

隔离遮罩后,交换颜色,背景或更复杂的图像非常简单.

convert green.png -fx '1 * b - 1 * g + 1' mask.png

遮罩方法的主要好处是颜色细节(阴影,高光和线条)将保留在最终图像中.在PHP中将所有这些组合在一起:

$img = new Imagick("source.jpg");
$org = clone $img; // Copy source for final composite
$img->modulateImage(100,100,166.6); // Convert hues from red to green
/*
 Apply fx operations. Remember: K0, K1, & K2 are constants
 that need to be adjusted to match the chroma-key that you
 want to knockout.
 */
$mask = $img->fxImage('1.35 * b - 0.95 * g + 1');
// Copy the mask as the new alpha channel
$org->compositeImage($mask, Imagick::COMPOSITE_COPYOPACITY, 0, 0, Imagick::CHANNEL_ALPHA);

用于填充80%黑色(或20%灰色)的衬衫.在仅彩色图像上构图新图像,然后降至灰度.

$fin = new Imagick();
$fin->setSize($org->width, $org->height);
$fin->readImage("xc:gray20");
$fin->compositeImage($org, Imagick::COMPOSITE_DEFAULT, 0, 0);
$fin->setImageColorspace(Imagick::COLORSPACE_GRAY);
$fin->writeImage('fin.jpg');

这是用图案填充衬衫的示例.

$pattern = new Imagick();
$pattern->setSize($org->width, $org->height);
$pattern->readImage("pattern:VERTICALSAW");
$pattern->negateImage(false);
$pattern->compositeImage($org, Imagick::COMPOSITE_DEFAULT, 0, 0);
$pattern->setImageColorspace(Imagick::COLORSPACE_GRAY);
$pattern->writeImage('pattern.jpg');

同样,如果要保留细节,这是理想的选择.如果您要进行完整的剔除(例如,绿色到黑色的比例均为80%),则只需使用-fill-opaque-fuzz.

例:

convert green.png  -fill gray20 -fuzz 30% -opaque hsl\(33%,100%,50%\) black80.png
convert black80.png -colorspace Gray bw_shirt.png
上一篇:php-蒙太奇或拼贴与GD库


下一篇:php-imagestring()函数中的utf-8字符