All Projects → leimao → Rotated-Rectangle-Crop-OpenCV

leimao / Rotated-Rectangle-Crop-OpenCV

Licence: MIT license
Rotated Rectangle Crop Function for OpenCV

Programming Languages

python
139335 projects - #7 most used programming language

Rotated Rectangle Crop OpenCV

Introduction

In OpenCV, cropping a rectangle from an image is extremely easy. However, it does not provide a function to crop a rotated rectangle. Here I developed an algorithm to crop a rotated rectangle from an image, and implemented it as a python function.

Algorithm

Original image and the rotated rectangle:

Crop a minimal up-right rectangle containing the rotated rectangle:

Rotate the cropped image such that the inner rotated rectangle becomes up-right and centered in the image:

Crop the "rotated rectangle":

Dependencies

  • OpenCV 3.0
  • Python 3.5

Usages

In Python or Jupyter Notebook:

from rotated_rect_crop import crop_rotated_rectangle
# image is the image matrix
# rect is the rotated rect object in OpenCV, i.e. (center (x,y), (width, height), angle of clock-wise rotation)
# center x is regarding to the width
# center y is regarding to the height
# width is the number of the columns of the rectangle.
# height is the number of the rows of the rectangle.
# The angle vector pointing to the "north" is exactly 0 degree
image_cropped = crop_rotated_rectangle(image, rect)

Demo

Generate a random rotated rectangle and crop:

python rotated_rect_crop.py

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].