Using minAreaRect with contour in Python
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 = cv2.cv.BoxPoints(rotrect)
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.
I am not really into the python thing, but what are you doing here?
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 The output of
cv2.minAreaRect()
is((x, y), (w, h), angle)
. Usingcv2.cv.BoxPoints()
is meant to convert this to points.Replace with: box = cv2.cv.BoxPoints(rotrect) to: box = cv2.boxPoints(rotrect)