IMagick 检查亮度图像

IMagick check lightness image

我需要能够在图像中自动写入一些文本。根据图像亮度,脚本必须用白色或黑色书写。

那么如何使用 Imagick 检查图像的 lightness/darkness?

你可以这样做:

// Load the image
$imagick = new Imagick("image.jpg");
// convert to HSL - Hue, Saturation and LIGHTNESS
$imagick->transformImageColorspace(imagick::COLORSPACE_HSL);
// Get statistics for the LIGHTNESS
$Lchannel = $imagick->getImageChannelMean(imagick::CHANNEL_BLUE);
$meanLightness = $Lchannel['mean']/65535;
printf("Mean lightness: %f",$meanLightness);

如果您想根据 Fred 的建议制作底色文本,您可以在 PHP 中使用:

$image = new Imagick("image.jpg");
$draw  = new ImagickDraw();
$draw->setFillColor('#ffffff');
$draw->setFontSize(24);
$draw->setTextUnderColor('#ff000080');
$image->annotateImage($draw,30,50,0,"Undercoloured Text");
$image->writeImage('result.jpg');

您也可以只在某种背景颜色上创建文本图像并将其覆盖在图像上。或者将 -undercolor 与 -draw 或 -annotate 一起使用。这样,您就不必担心图像的颜色。或者您可以指定要在其上书写文本的区域,然后获取该区域的平均亮度。然后测试该区域是否比 mid-gray 更亮或更暗。如果更亮,则创建具有透明背景的相同大小的文本图像并使用黑色文本颜色。同样,如果较暗,请使用白色文本颜色。所以在 ImageMagick 命令行中,这些将是:

输入:

粉色底色:

convert logo.png \
\( -size 110x -background pink -font ubuntu-bold -fill $textcolor label:"Testng" \) \
-gravity northwest -geometry +395+400 -compose over -composite result3.png

测试(暗区)- Unix 语法:

test=`convert logo.png -crop 110x36+395+400 +repage -colorspace gray -format "%[fx:(mean>0.5)?1:0]" info:`
if [ $test -eq 1 ]; then
    textcolor="black"
else
    textcolor="white"
fi
convert logo.png \
\( -size 110x -background none -font ubuntu-bold -fill $textcolor label:"Testng" \) \
-gravity northwest -geometry +395+400 -compose over -composite result1.png

测试(亮区):

test=`convert logo.png -crop 110x36+100+400 +repage -colorspace gray -format "%[fx:(mean>0.5)?1:0]" info:`
if [ $test -eq 1 ]; then
    textcolor="black"
else
    textcolor="white"
fi
convert logo.png \
\( -size 110x -background none -font ubuntu-bold -fill $textcolor label:"Testng" \) \
-gravity northwest -geometry +100+400 -compose over -composite result2.png

抱歉,我不知道 Imagick。所以其他人可能需要帮助。