我会使用 ImageMagick 来做到这一点,您可以使用 homebrew 在 macOS 上安装它:
brew install imagemagick
因此,从使用 macOS 预览和带有透明填充的浅绿色注释的图像开始:
然后我会将这个脚本保存在我的 HOME 目录中为analyze:
#!/bin/bash
if [ $# -ne 1 ] ; then
>&2 echo "Usage: analyze IMAGE"
exit 1
fi
image="$1"
# Assume image is annotated in lime green - you can set any RGB colour with syntax like "rgb(10,20,30)"
annocolour="lime"
# Calculate percentage of image inside annotation box, each line corresponds to a line of code:
# - make everything not lime green into black (image is just pure black with green annotation now)
# - add a 1-pixel black border for the floodfill in the next step to flow around
# - floodfill everything outside the annotation box with lime green starting at 0,0 in top-left corner
# - remove 1-pixel border we added above
# - make everything lime green into white (i.e. everything outside the annotation box becomes white)
# - invert the image so the contents of annotation box are white and everything else is black and print image name and mean, which is the percentage white
convert "$image" -fuzz 10% -fill black +opaque "$annocolour" \
-bordercolor black -border 1 \
-fill "$annocolour" -draw "color 0,0 floodfill" \
-shave 1x1 -alpha off \
-fill white -opaque "$annocolour" \
-negate -format "%f,%[fx:mean*100]\n" info:
现在,只需要一次,使该脚本可执行:
chmod +x $HOME/analyze
然后我可以计算任何图像在石灰绿色注释区域内的百分比:
$HOME/analyze grab.png
样本输出
grab.png,2.85734
这意味着 2.8% 的图像在绿色框内。
如果你有 500 张 PNG 图像,你会想要这样的循环:
for f in *.png; do $HOME/analyze "$f" ; done
关键词:annotate、注释区域、图像、图像处理、ImageMagick、macOS