I need the explanation on boundingRect of OpenCV. I have used it, it works great. Is there any reference where this function is fully explained please?
Asked
Active
Viewed 9.8k times
26
-
4Have you seen [THIS DOC](http://docs.opencv.org/3.1.0/dd/d49/tutorial_py_contour_features.html) – Jeru Luke Feb 25 '17 at 08:44
-
@JeruLuke : Yes, I did went through it several times. But i need more information about how it works in the background. – vashish doolooa Feb 26 '17 at 11:40
-
It gets the min and max locations of the contour in both x and y. Those define the bounding box. left=min_x, top=min_y, width=(max_x-min_x), height=(max_y-min_y) – fmw42 Nov 10 '22 at 20:23
2 Answers
31
The cv2.boundingRect()
function of OpenCV is used to draw an approximate rectangle around the binary image. This function is used mainly to highlight the region of interest after obtaining contours from an image.
As per the documentation there are two types of bounding rectangles:
- Straight Bounding Rectangle
Here a simple rectangle is drawn around the contour (ROI). As you can see in the documentation, a green rectangle is drawn around the ROI. Corresponding rectangle coordinates are obtained such that a rectangle completely encloses the contour.
- Rotated Rectangle
- In this case
cv2.minAreaRect()
function is used to highlight the minimum rectangular area enclosing a contour. cv2.boxPoints()
obtains the 4 corner points of the obtained rectangle.np.int0()
is done to convert the corrdinates fromfloat
tointeger
format.- These points are then used to draw the rectangle. This is depicted by the red rectangle in the documentation.

Sabito stands with Ukraine
- 4,271
- 8
- 34
- 56

Jeru Luke
- 20,118
- 13
- 80
- 87
-
2"draw" and "highlight" would be inaccurate, as those funcions only return objects, but don't draw in the image (you can use them to do that with other functions, though). – alx - recommends codidact Mar 04 '20 at 10:51
-
I found [this](https://stackoverflow.com/a/54823710/11573842) answer to be useful. You can refer to it. It demonstrates what Jeru describes here. – Sabito stands with Ukraine Sep 27 '20 at 07:46
0
just find min_x , min_y , max_x, max_y
by looping over the points in the contour, and calculate the width max_x - min_x
and height max_y - min_y

yazan sayed
- 777
- 7
- 24