I have a white background with various colors of Polygons in the foreground.
How can I crop and iterate for each polygon in my image using imagemagick?
You can do that in Imagemagick by thresholding, then use -connected-components to locate the bounding boxes. Then loop over each bounding box and crop using the given bounding box. In connected components, we skip the header lines of the text output, then keep the colors (b/w), then keep the text output. Then we select only white ones, i.e. gray(255), and then print the bounding box coordinates to the terminal and nothing else from the text output.
Input:
bboxArr=(`convert polygons.png -threshold 99% -negate -type bilevel \
-define connected-components:exclude-header=true \
-define connected-components:mean-color=true \
-define connected-components:verbose=true \
-connected-components 8 threshold.png | grep "gray(255)" | awk '{print($2)}'`)
num=${#bboxArr[*]}
for ((i=0; i<num; i++)); do
convert polygons.png -crop "${bboxArr[$i]}" +repage polygon$i.png
done
Polygon 1:
Polygon 2:
Polygon 3: