0

Based on the answer to the following question Programmatically divide scanned images into separate images right now I able to extract rectangular region.

Is it possible to modify the following ImageMagick script:

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

to be able to extract non-rectangular region that exactly matches the black regions in the tmp.png:

enter image description here

For example, add a transparent background for the rest of the rectangular region of the extracted image that is not related to the black region.

enter image description here

alexanoid
  • 24,051
  • 54
  • 210
  • 410

1 Answers1

1

Yes, my ImageMagick script can be modified as follows:

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

The following results are transparent, so show white for the outside. But if you download them, you will see that the background is transparent.

enter image description here

enter image description here

enter image description here

fmw42
  • 46,825
  • 10
  • 62
  • 80