Ashot Khanamiryan
Ashot Khanamiryan

Reputation: 1134

I need to leave the biggest object in image

I need to detect the biggest object from image with ImageMagick. It can be bigger or smaller, or can be in other location. It's always black, and background always white. enter image description here

Upvotes: 2

Views: 621

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207345

Like this with Connected Component Analysis

convert objects.png -define connected-components:verbose=true      \
   -define connected-components:area-threshold=100                 \
   -connected-components 8 -auto-level output.png

Objects (id: bounding-box centroid area mean-color):
  0: 595x842+0+0 296.7,420.0 499414 gray(255)
  7: 37x30+342+632 360.0,646.5 1110 gray(0)
  3: 12x15+465+375 470.5,382.0 180 gray(0)
  1: 23x12+439+332 447.9,335.4 150 gray(0)
  6: 13x16+451+425 456.6,430.6 136 gray(0)

The first object listed (the first line) is a white object, because the mean-color is gray(255), and is therefore the background, so I ignore that. The second one is the largest (area=1110) and I can draw a red rectangle around it like this

convert objects.png -stroke red -strokewidth 5 -fill none -draw "rectangle 342,632 379,662" out.png

enter image description here

If you want to mask out all objects outside the bounding box of the largest object, you can do that like this:

convert objects.png -alpha on            \
   \( +clone                             \
      -evaluate set 0                    \
      -fill white                        \
      -draw "rectangle 342,632 379,662"  \
      -alpha off                         \
   \) -compose copy-opacity -composite result.png

Basically the part inside the parentheses copies the original image (+clone), fills it with black (-evaluate set 0), then draws a white box over the bounding box of the biggest shape, then uses that black and white mask to set the opacity of the original image that we started off with. That leaves you with this:

enter image description here

Upvotes: 3

Related Questions