我尝试使用功能旋转矩形,但框不在正确的位置

I try to rotate rectangle with function but the boxes not in correct position

代码确实按照我输入的角度旋转点,但是框的输出排列不正确..plz检查我的代码错误..我希望每个框按照我输入的角度旋转但相同时间我想要它在正确的行和列中

import cv2
import numpy as np
import math




def rotate( points, angle):
    ANGLE = np.deg2rad(angle)
    ANGLE = np.deg2rad(angle)
    c_x, c_y = np.mean(points, axis=0)

    return np.array(
        [
            [
                c_x  + math.cos(ANGLE) * (pxl - c_x) - math.sin(ANGLE) * (py - c_x),
                c_y + math.sin(ANGLE) * (pxl - c_y) + math.cos(ANGLE) * (py - c_y)
            ]
            for pxl, py in points
        ]
    ).astype(int)




imgc = np.zeros((500, 500, 3), np.uint8)
box = 0
box2 = 0


for i in range(1,10,1):
    box2 = box2 + 25
    box = 0

    for x in range(1, 10, 1):
        p0 = (box, box2)
        p1 = (0 + box, box2 + 20)
        p2 = (20 + box, box2 + 20)
        p3 = (box + 20, box2)

        box = box + 25

        p0, p1, p2, p3 = rotate((p0, p1, p2, p3), 45)
        pp = np.array([p0, p1, p2, p3])
        cv2.drawContours(imgc, [pp], 0, (255, 255, 255), -1, cv2.LINE_AA)



cv2.imshow("image",imgc)

cv2.waitKey()

你以错误的方式移动到中心。

首先从 pxpy 中减去 c_x
第二步,你从 pxpy.

中减去 c_y
... + ... * (pxl - c_x) - ... * (py - c_x),   # only `c_x`
... + ... * (pxl - c_y) - ... * (py - c_y),   # only `c_y`

但是你应该只从 px 中减去 c_x 而不是 py.
而且你应该只从 py 而不是 px.

中减去 c_y
 ... + ... * (px - c_x) - ... * (py - c_y)
 ... + ... * (px - c_x) - ... * (py - c_y)

def rotate(points, angle):
    ANGLE = np.deg2rad(angle)
    SIN = math.sin(ANGLE)
    COS = math.cos(ANGLE)
    
    c_x, c_y = np.mean(points, axis=0)

    return np.array(
        [
            [
                c_x + COS * (px - c_x) - SIN * (py - c_y),
                c_y + SIN * (px - c_x) + COS * (py - c_y),
            ]
            for px, py in points
        ]
    ).astype(int)

轮换前:

旋转后: