ImageMagick提取具有透明背景的非矩形区域

时间:2018-02-03 19:08:09

标签: image-processing imagemagick

根据以下问题Programmatically divide scanned images into separate images的答案,我现在能够提取矩形区域。

是否可以修改以下ImageMagick脚本:

infile="image.png"
inname=`convert -ping $infile -format "%t" info:`
OLDIFS=$IFS
IFS=$'\n'
arr=(`convert $infile -blur 0x5 -auto-level -threshold 99% -type bilevel +write tmp.png \
-define connected-components:verbose=true \
-connected-components 8 \
null: | tail -n +2 | sed 's/^[ ]*//'`)
num=${#arr[*]}
IFS=$OLDIFS
for ((i=0; i<num; i++)); do
#echo "${arr[$i]}"
color=`echo ${arr[$i]} | cut -d\  -f5`
bbox=`echo ${arr[$i]} | cut -d\  -f2`
echo "color=$color; bbox=$bbox"
if [ "$color" = "gray(0)" ]; then
convert $infile -crop $bbox +repage -fuzz 10% -trim +repage ${inname}_$i.png
fi
done

能够提取与tmp.png中黑色区域完全匹配的非矩形区域:

enter image description here

例如,为提取图像的与黑色区域无关的其余矩形区域添加透明背景。

enter image description here

1 个答案:

答案 0 :(得分:1)

是的,我的ImageMagick脚本可以修改如下:

infile="image.png"
inname=`convert -ping $infile -format "%t" info:`
OLDIFS=$IFS
IFS=$'\n'
arr=(`convert $infile +repage -blur 0x7 -auto-level -negate -threshold 2% -negate -type bilevel +write tmp.png \
-define connected-components:verbose=true \
-connected-components 8 \
null: | tail -n +2 | sed 's/^[ ]*//'`)
num=${#arr[*]}
IFS=$OLDIFS
for ((i=0; i<num; i++)); do
echo "${arr[$i]}"
color=`echo ${arr[$i]} | cut -d\  -f5`
bbox=`echo ${arr[$i]} | cut -d\  -f2`
echo "color=$color; bbox=$bbox"
if [ "$color" = "gray(0)" ]; then
convert tmp.png -crop $bbox +repage -fuzz 10% -trim +repage -alpha copy -channel a -negate +channel ${inname}_$i.png
fi
done

以下结果是透明的,因此外部显示为白色。但是如果你下载它们,你会发现背景是透明的。

enter image description here

enter image description here

enter image description here