Ask Your Question
6

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

Comments

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
7

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);
cvtColor(mSource_Bgr,mSource_Gray,COLOR_BGR2GRAY);
threshold(mSource_Gray,mThreshold,254,255,THRESH_BINARY_INV);

Mat Points;
findNonZero(mThreshold,Points);
Rect Min_Rect=boundingRect(Points);

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

rectangle(mSource_Bgr,Min_Rect.tl(),Min_Rect.br(),Scalar(0,255,0),2);

imshow("Result",mSource_Bgr);

Source Image

image description

Threshold Mask

image description

Cropped Bounding Rect

image description

edit flag offensive delete link more

Comments

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

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

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

Comments

2

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

Stats

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

Seen: 38,776 times

Last updated: Sep 12 '15