#!/bin/sh
#
# segment_via_svg  input_image   multiple_output_image
#
# Attempt to segment an image using SVG (raster to vector tracing converter)
# It is not exact.   However the concept of doing this was found in a
# scanned text line segmentation algorithm that was discovered on
#     http://www.balisage.net/Proceedings/html/2008/Cayless01/
#
# For example the original image...
#   wget  http://www.imagemagick.org/Usage/images/segment.png
#   convert segment.png show:
#
# Converted to a SVG form of the image...
#   convert autotrace:segment.png show:
#
# The SVG segmented form...
#   segment_via_svg segment.png miff:- | gif_anim_montage 4x0 -
#
# The (slow) flood-fill segmented image...
#   segment_image segment.png miff:- | gif_anim_montage 4x0 -
#
# From this we can see that autotrace is itself segmenting the image in
# exactly the same way, and in the same order as our 'flood-fill' version,
# so that it can then trace out the paths of each colored object in the image.
#
####
#
# Anthony Thyssen    9  July 2009      <A.Thyssen@griffith.edu.au>
#

# Seperate each 'object path' in the autotrace SVG output to a sepate image.
convert "$1" svg:- |\
  sed '# Convert the SVG into a "convert" command to draw each path found
      /<?xml.*/{        s//convert \\/;n }
      /.*width="\([0-9]*\)" height="\([0-9]*\)".*/{
                        s//  -size \1x\2 xc:none \\/;n }
      /<\/svg>/{        s//  -delete 0  "'"$2"'"\n/;n }

      /<path /! d  # rest is limited to just <path ..>

      s/<path style="fill:/  -fill "/
      s/; stroke:none;" d="M/" \\\n  \\( -clone 0 -draw '\''path "@/
      s/M/z" '\'' \\) \\\n  \\( -clone 0 -draw '\''path "@/g
      s/z"\/>/z" '\'' \\) \\/
      s/@/M/g
    ' | sh


