Ask Your Question

What is the best way to find bounding box for binary mask?

asked 2012-11-14 08:29:34 -0600

wl2776 gravatar image

updated 2020-11-30 01:01:39 -0600

I have a binary mask of an object and want to get its bounding rectangle. Function cv::boundingRect wants a vector of cv::Point, while I have a matrix.

I've written my own function, which reduces the binary mask with CV_REDUCE_MAX first to a column then to a row and finds leftmost and rightmost and topmost and bottommost non-zero elements.

The mask is strictly binary (0 and 1).

Is there any better way?

edit retag flag offensive close merge delete


When don't you put some index of max_x and max_y when you create the mask?

Can you describe how you create the mask?

Tran Thu Do gravatar imageTran Thu Do ( 2012-11-14 09:08:40 -0600 )edit

I don't create a mask, it is given to my code from outside. I don't know, how it is created. Probably, by hands.

wl2776 gravatar imagewl2776 ( 2012-11-16 02:31:33 -0600 )edit

2 answers

Sort by ยป oldest newest most voted

answered 2015-09-12 07:50:31 -0600

updated 2015-09-12 14:01:30 -0600

Hi If you are having multiple objects or otherwise multiple contours in your image & you simply want the Bounding box of the overall mask you can easily find the Bounding box as follows!

Mat mSource_Bgr,mSource_Gray,mThreshold;
mSource_Bgr= imread(List_Files[i],1);

Mat Points;
Rect Min_Rect=boundingRect(Points);

//Here you can also use minAreaRect() also to find Rotated Rect.



Source Image

image description

Threshold Mask

image description

Cropped Bounding Rect

image description

edit flag offensive delete link more


How to get individual boxes around each object? something like Floodfill? Thanks

Intoxica gravatar imageIntoxica ( 2017-10-02 17:04:36 -0600 )edit

answered 2012-11-14 21:33:08 -0600

Gianluigi gravatar image

Try to use findContours then pass the findContours result into boundingRect

edit flag offensive delete link more



I was thinking about it. Are you sure, it is a better way? I'll have to create a copy of the mask since findContours changes the image. Then, in case of a complex object, vector size and creation time will be significant.

wl2776 gravatar imagewl2776 ( 2012-11-16 02:34:35 -0600 )edit

Question Tools


Asked: 2012-11-14 08:29:34 -0600

Seen: 37,566 times

Last updated: Sep 12 '15