I looked on the forums and found this old topic about how to segment images:
http://imagemagick.org/discourse-server ... =1&t=18683
And Anthony said:
Have any of those plans come to fruition? I haven't seen anything in the help pages.At this time IM is short on built-in segmentation methods. They are planned but there are just not enough programmers willing to get their hands dirty.
If not, I have found a different way to solve a similar (but not identical) problem from that thread. My problem is related to textual OCR. I was wondering if anyone had comments, or a more efficient way to do it.
Code: Select all
#!/bin/sh
#
# Created by nixscripter.
# Released into the public domain, in the hopes that it will be useful.
#
# Objective: segments a monochrome image into individual "shapes" based on shape
# boundaries.
# Input: one monochrome image, white background, black foreground. If you want
# it the other way, remove the negate from the first command, but it has only
# been tried with monochrome.
# Output: a series of images, each of the original canvas size, which has a
# white background, and one of the black shapes on it. Each file will be named
# "outputX,Y.png", where X,Y is one point that is unique to the shape contained
# in that image.
#
ORIGINAL=$1
CONVEX="tmpconvex.png"
#
# First, find all the octagonal convex hulls of the various shapes in the image.
# NOTE: Dialated by one just to cover the "loose ends" of certain shapes which
# occur in the original application.
# NOTE 2: Kudos to Anthony's page on Convex Hull!
#
convert "$ORIGINAL" -negate -morphology Close Diamond:1 -morphology Thicken:-1 ConvexHull -morphology Close Diamond -morphology Dilate Diamond:1 "$CONVEX"
#
# Next, make a list of "corner points" -- a set of points, each of which is in
# the convex hull of one shape. Since the convex hull is octagonal, there ought
# to be exactly one of these in every shape.
#
CORNERS=`convert "$CONVEX" -morphology HMT "3:0,0,0 0,1,1 -,1,-" txt:- | grep white | cut -d: -f1`
#
# For each point:
# Use that point as a point for a flood-fill to find the entire shape
# Use that filled shape as a mask on the whole image.
#
for point in $CORNERS
do
# Create a new image with just this one shape's convex hull
convert "$CONVEX" -fill red -draw "color $point floodfill" -fill white -draw 'color 0,0 replace' -monochrome -negate "tmp${point}.png"
# And mask the image with it -- and get rid of the "excess" with flatten
convert "$ORIGINAL" "tmp${point}.png" -alpha Off -compose CopyOpacity -composite -background white miff:- | convert -background white miff:- -flatten "output${point}.png"
rm -f "tmp${point}.png"
done