Search code examples
imagegraphicsimagemagickgimp

Split image into parts


Is there anything in imagemagick or gimp or other linux compatible tool what can automatically detect individual objects on image and either return some location of object or store each object as separate image?

I have image like this one:

enter image description here

For other images where objects are located on a grid, I have successfully used crop operator in imagemagick, e.g. for 3x3 grid:

convert -crop 3x3@ in-image.jpg  out-image-%d.jpg

I cannot use crop when there is no rectangular grid, but I thought that white color should be enough for objects separation.


Solution

  • It can be done with ImageMagick in multiple steps. The orignal image is named meat.jpg:

    convert meat.jpg -threshold 98% -morphology Dilate Octagon meat_0.png
    

    meat_0.png

    convert meat_0.png text: | grep -m 1 black
    

    This gives you a pixel location in the area of the first part of meat:

    131,11: (  0,  0,  0)  #000000  black
    

    We'll use this to color the first piece in red, separate the red channel and then create and apply the mask for the first piece:

     convert meat_0.png -fill red -bordercolor white \
             -draw 'color 131,11 filltoborder' meat_1_red.png
     convert meat_1_red.png -channel R -separate meat_1.png
     convert meat_1_red.png meat_1.png -compose subtract \
             -threshold 50% -composite -morphology Dilate Octagon \
             -negate meat_1_mask.png
     convert meat_1_mask.png meat.jpg -compose Screen -composite \
             -trim meat_1.jpg
    

    The resulting meat_1.jpg is already trimmed. You can then proceed the same way with meat_1.png in stead of meat_0.png, generating meat_2.png as the basis for successive iterations on the fly. Maybe this can be further simplified and wrapped in a shell script.

    meat_1.jpg