Why Is Finding Minimal Bounding Box Using ComponentMeasurements So Slow?

My goal is to find the coordinates of the minimal bounding box for this image.

I am using the following command:

ComponentMeasurements[img, "MinimalBoundingBox"] // AbsoluteTiming


The output is the following:

{5.31663, {1 -> {{338.492, 1064.99}, {156.654,
71.8802}, {1084.66, -98.0355}, {1266.49, 895.079}}}}


Why does this computation take so long? It seems that ImageCrop can perform a similar computation and crop the image but it does so much much faster. Am I just using ComponentMeasurements innapropriately or is there something else I am missing?

• If you can do it with ImageCrop then ComponentMeasurements is overkill, yes. It's doing something like this, to find the components, and that's more complicated than finding max and minimum coordinates of all components combined. Oct 5, 2016 at 20:14
• My problem with ImageCrop is that it doesn't return the coordinates you would use from the original image to give the minimal bounding box. Oct 5, 2016 at 21:22
• ok, it makes more sense now but I just realized that MinimalBoundingBox returns an oriented bounding box, which is another important difference from ImageCrop. If it were just an axes-oriented bounding box then a good start might have been MinMax /@ Transpose[SparseArray[ImageData[img]]["NonzeroPositions"]]. Finding an oriented bounding box is more complicated. Oct 5, 2016 at 22:06
• You could use ComponentMeasurements[img, "BoundingBox"] if you just want the axis-oriented bounding box. That's much faster Oct 6, 2016 at 6:24

ComponentMeasurements[img, "MinimalBoundingBox"] finds the smallest bounding box in any orientation, which is a more complex problem than what ImageCrop solves:

pts = ComponentMeasurements[img, "MinimalBoundingBox"][[1, 2]];
HighlightImage[img, Polygon[pts]]


If that's what you need, you can make it a little faster by passing only the perimeter to ComponentMeasurements, so it has to check fewer pixels:

ComponentMeasurements[
MorphologicalPerimeter@img, "MinimalBoundingBox"]


runs about 20x faster on my PC and gives the same bounding box. (At least unless your objects have holes!)

If you're only interested in the axis-aligned bounding box, use ComponentMeasurements[img, "BoundingBox"] instead:

b = ComponentMeasurements[img, "BoundingBox"][[1, 2]];
HighlightImage[img, Rectangle @@ b]


• Thanks! I should've noticed there was a MinimalBoundingBox and a BoundingBox! This makes more sense. Oct 7, 2016 at 15:58