ina
ina

Reputation: 19534

ImageMagick - Trim / Crop to contiguous objects

How do you do the equivalent of this step in Photoshop.

https://gyazo.com/180a507c0f3c9b342fe33ce218cd512e

Supposed there are two contiguous objects in an image, and you want to create exact sized crops around each one and output as two files. (Generalize to N files)

Upvotes: 1

Views: 270

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 208077

You can do that with "Connected Component Analysis" to find the contiguous blobs.

Start Image

enter image description here

convert shapes.png -colorspace gray -negate -threshold 10%  \
   -define connected-components:verbose=true                \
   -connected-components 8 -normalize output.png

Sample Output

Objects (id: bounding-box centroid area mean-color):
  0: 416x310+0+0 212.3,145.2 76702 srgb(0,0,0)
  1: 141x215+20+31 90.0,146.2 26129 srgb(255,255,255)
  2: 141x215+241+75 311.0,190.2 26129 srgb(255,255,255)

Notice how each blob, or contiguous object, is "labelled" or identified with its own unique colour (shade of grey).

enter image description here

So there is a header line telling you what the fields are followed by 3 blobs, i.e. one per line of output. The first line is the entire image and not much use. The second one is 141 px wide and 215 px tall starting at +20+31 from the top-left corner. The third one is the same size (because I copied the shape) and starts as +241+75 from the top-left corner.

Now stroke red around the final indicated rectangle - bearing in mind that rectangle takes top-left and bottom-right corners rather than top-left corner plus width and height.

convert shapes.png -stroke red -fill none -draw "rectangle 241,75 382,290" z.png

And crop it:

convert shapes.png -crop 141x215+241+75 z.png

enter image description here

And here is the extracted part:

enter image description here


If you want to generalise, you can just pipe the ImageMagick output into awk and pick out the geometry field:

convert shapes.png -colorspace gray -negate -threshold 10%  -define connected-components:verbose=true  -connected-components 8 -normalize output.png | awk 'NR>2{print $2}'

Sample Output

141x215+20+31
141x215+241+75

Upvotes: 3

Related Questions