Search code examples
pythonimageopencvimage-processing

Crop Rectangle returned by minAreaRect OpenCV [Python]


minAreaRect in OpenCV returns a rotated rectangle. How do I crop this part of the image which is inside the rectangle?

boxPoints returns the co-ordinates of the corner points of the rotated rectangle so one can access the pixels by looping through the points inside the box, but is there a faster way to crop in Python?

EDIT

See code in my answer below.


Solution

  • You have not given sample code, so I am answering without code also. You could proceed as follows:

    1. From corners of rectangle, determine angle alpha of rotation against horizontal axis.
    2. Rotate image by alpha so that cropped rectangle is parallel to image borders. Make sure that the temporary image is larger in size so that no information gets lost (cf: Rotate image without cropping OpenCV)
    3. Crop image using numpy slicing (cf: How to crop an image in OpenCV using Python)
    4. Rotate image back by -alpha.