#! /bin/bash
# Last edited on 2010-08-09 16:08:49 by stolfilocal

# For each image "orig/{NNN}.png", creates a binary mask "pmsk/{NNN}.png" 
# that selects the text and some background around it.  The mask is created by dilating the 
# groundtruth mask "true/{NNN}.png" by some amount.

# Also creates in pext/{NNN}.png" a copy of the "orig" image with the text
# cut out by the created mask.

function extr() {

  inum="$1"; shift;   # Image id-number
  drad="$1"; shift;   # Radius of dilation kernel
  
  # Make sure that the output directories exist:
  mkdir -p pmsk pext
  
  # Input and output files:
  origimg="orig/${inum}.png" # The official version of the image.
  trueimg="true/${inum}.png" # The groundtruth mask image.
  pmskimg="pmsk/${inum}.png" # (OUT) The text extraction mask image.
  pextimg="pext/${inum}.png" # (OUT) The extracted text image.
   
  # Work files:
  temp="/tmp/$$"
  tempimg="${temp}-x.png" # A temporary scratch image.

  # Dilate ${trueimg} and complement it giving ${pmskimg}:
  convert \
    ${trueimg} \
    -alpha Off \
    -type Truecolor \
    -negate \
    -morphology Dilate Disk:"${drad}" \
    -gaussian-blur "1x1" \
    +matte \
    ${pmskimg}
  
  # Extract the text from the "trim" image:
  # echo "extracting text from ${origimg} with ${pmskimg} ..." 1>&2
  # identify ${pmskimg}
  # identify ${origimg}
  convert \
    ${origimg} \
    -alpha Off \
    -type Truecolor \
    ${tempimg} \
  
  composite \
    -compose CopyOpacity \
    ${pmskimg} \
    ${tempimg} \
    ${pextimg}

  # identify ${pextimg}
  display -title "${inum}:%f" -filter Box -resize '200%' ${pextimg} ${trueimg} ${pmskimg}

  rm -f ${tempimg}
}

extr 001 4.3
extr 002 5.3
extr 003 5.3
extr 004 4.3
extr 005 5.3
