Ask Your Question

Using minAreaRect with contour in Python

asked 2015-07-27 12:15:55 -0600

thomasfedb gravatar image

updated 2015-07-27 12:17:29 -0600

I'm attempting to use OpenCV to identify and extract a fairly obvious region from an image. So far, by using a threshold and a series of dilations and erosions, I can successfully find the contour for the area I require.

However, my attempts to use minAreaRect as a precursor to rotation and cropping are failing to generate a rectangle that contains the input contour.

contours, hierarchy = cv2.findContours(morph.copy() ,cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contour = contours[0]

draw = cv2.cvtColor(morph, cv2.COLOR_GRAY2BGR)
cv2.drawContours(draw, [contour], 0, (0,255,0), 2)

rotrect = cv2.minAreaRect(contour)
box =
box = numpy.int0(box)
cv2.drawContours(draw, [box], 0, (0,0,255), 2)

cv2.imshow('image', draw); cv2.waitKey(0)

Here's and example of the output:


Where the red stroke is the rect and the green is the contour. I would have expected the red stroke to encompass the green stroke.

Unfortunately I'm unable to provide the input image.

edit retag flag offensive close merge delete


I am not really into the python thing, but what are you doing here?

box =
box = numpy.int0(box)

Is your final goal to make the tilted rectangle horizontal and cropped? If so I can provide code for that in C++ that you will need to translate.

StevenPuttemans gravatar imageStevenPuttemans ( 2015-07-28 03:58:13 -0600 )edit

@StevenPuttemans The output of cv2.minAreaRect() is ((x, y), (w, h), angle). Using is meant to convert this to points.

thomasfedb gravatar imagethomasfedb ( 2015-07-28 05:48:02 -0600 )edit

Replace with: box = to: box = cv2.boxPoints(rotrect)

supra56 gravatar imagesupra56 ( 2017-09-01 16:07:35 -0600 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2017-08-29 20:06:33 -0600

this post is marked as community wiki

This post is a wiki. Anyone with karma >50 is welcome to improve it.

You may try to replace cv2.RETR_TREE with cv2.RETR_EXTERNAL, which returns only exterior contours.

edit flag offensive delete link more



@Shu-Yen Wan thanks for your answer. but sometimes answering for an old question like this one is waste of the time . we will appreciate your contributions by answering new questions

sturkmen gravatar imagesturkmen ( 2017-08-29 21:44:16 -0600 )edit

No they are not a waste of time as the purpose of this website is to publicly document all possible problems users might face.

Mehdi gravatar imageMehdi ( 2018-09-05 07:35:07 -0600 )edit

Question Tools

1 follower


Asked: 2015-07-27 12:15:55 -0600

Seen: 26,583 times

Last updated: Aug 29 '17