Search code examples
linuxshellimagemagick

Imagemagick crop non-white Polygon Linux


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?


Solution

  • 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:

    enter image description here

    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:

    enter image description here

    Polygon 2:

    enter image description here

    Polygon 3:

    enter image description here