简体   繁体   English

如何旋转矩形形状cv2 python

[英]how to rotate Rectangle shape cv2 python

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()

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 .请注意: drawContours期望点为整数而不是浮点数,因此您需要将数组转换为int

Here the blue rectangle was the original one and the magenta rectangle is the 45 degrees rotated one:这里的蓝色矩形是原始矩形,洋红色矩形是旋转 45 度的矩形:

轮换结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM