title: ImageMagick exract non-rectangular region with transparent background
body: <p>Based on the answer to the following question <a href="https://stackoverflow.com/questions/48557612/programmatically-divide-scanned-images-into-separate-images">Programmatically divide scanned images into separate images</a> right now I able to extract rectangular region.</p>
  
  <p>Is it possible to modify the following ImageMagick script:</p>
  
  <pre><code>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&lt;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
  </code></pre>
  
  <p>to be able to extract non-rectangular region that exactly matches the black regions in the tmp.png:</p>
  
  <p><a href="https://i.stack.imgur.com/s6mkj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/s6mkj.png" alt="enter image description here"></a></p>
  
  <p>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.</p>
  
  <p><a href="https://i.stack.imgur.com/NF1YR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NF1YR.png" alt="enter image description here"></a></p>