Reputation: 57
I have simple rectangle I just want to rotate this rectangle in any input angle my code is:
import cv2
import numpy as np
imgc = np.zeros((500, 500, 3), np.uint8)
p0 = (100, 100)
p1 = (100 , 150)
p2 = (150, 150)
p3 = (150, 100)
pp = np.array([p0, p1, p2, p3])
cv2.drawContours(imgc, [pp], 0, (155, 155, 155), -1, cv2.LINE_AA)
cv2.imshow("image",imgc)
cv2.waitKey()
Upvotes: 2
Views: 5621
Reputation: 2399
What you need is Rotation Matrices. But you need to remember this rotating a point with a given angle (in radians) around the ORIGIN.
You need to move your points to the origin rotate them and move them back same amount.
Here what is would look line when you break down all dot production steps into one equation:
def rotate(points, angle):
ANGLE = np.deg2rad(angle)
c_x, c_y = np.mean(points, axis=0)
return np.array(
[
[
c_x + np.cos(ANGLE) * (px - c_x) - np.sin(ANGLE) * (py - c_x),
c_y + np.sin(ANGLE) * (px - c_y) + np.cos(ANGLE) * (py - c_y)
]
for px, py in points
]
).astype(int)
Please notice: drawContours
expects points as integers not floats so you need to convert your arrays to int
.
Here the blue rectangle was the original one and the magenta rectangle is the 45 degrees rotated one:
Upvotes: 3