user1367465
user1367465

Reputation: 1

Rotating contour in OpenCV

I got the contours of source image. I have drawn 4 lines to approximate these contours:

  1. from minimum width to minimum height of contour.
  2. from minimum width to maximum height of contour.
  3. from maximum width to minimum height of contour.
  4. from maximum width to maximum height of contour.

I'd like to rotate this rectangle such that it is aligned to width (i.e. x-coordinate of image).

Upvotes: 0

Views: 7458

Answers (1)

M.Ali El-Sayed
M.Ali El-Sayed

Reputation: 1779

This may help you

rect = cv2.minAreaRect(yourcontour)
angle = rect[2]

if angle < -45:
    angle = (90 + angle)

# otherwise, just take the inverse of the angle to make
# it positive
else:
    angle = -angle  

# rotate the image to deskew it
(h, w) = img.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(img, M, (w, h),
    flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE) 

Upvotes: 2

Related Questions