繁体   English   中英

如何更改 cv2 矩形的角度?

[英]How do I change the angle of a cv2 rectangle?

我使用 cv2 矩形作为边界框,我想将它绕其轴旋转某个角度。 由于warpAffine 函数是用来旋转图片的,所以这里无法使用。

我已经有一段时间使用它了,但据我所知,所有这些 ROI 类型都只是简单的 xy 矩形。 没有旋转是可能的(您也可以从构造函数中看到,无法定义旋转)。 所以它总是沿 x 轴宽,沿 y 轴高。

如果你只想画矩形,我建议只确定所有四个角点,然后通过简单的线条绘制边界框。 最终,您可以使用折线在一个命令中完成。

cv2没有内置函数可以做到这cv2 您可以通过确定旋转矩形的四个角的坐标来解决这个问题,使用cv2.polylines绘制它。

这是一个完全这样做的函数,可以用作cv2.rectangle的插入式替换 - 唯一的附加参数是rotation (应该以度为单位):

import numpy as np
from numpy import cos, sin

def rotated_rectangle(image, start_point, end_point, color, thickness, rotation=0):
    center_point = [(start_point[0]+end_point[0])//2, (start_point[1]+end_point[1])//2]
    height = end_point[1] - start_point[1]
    width = end_point[0] - start_point[0]
    angle = np.radians(rotation)
    
    # Determine the coordinates of the 4 corner points
    rotated_rect_points = []
    x = center_point[0] + ((width / 2) * cos(angle)) - ((height / 2) * sin(angle))
    y = center_point[1] + ((width / 2) * sin(angle)) + ((height / 2) * cos(angle))
    rotated_rect_points.append([x,y])
    x = center_point[0] - ((width / 2) * cos(angle)) - ((height / 2) * sin(angle))
    y = center_point[1] - ((width / 2) * sin(angle)) + ((height / 2) * cos(angle))
    rotated_rect_points.append([x,y])
    x = center_point[0] - ((width / 2) * cos(angle)) + ((height / 2) * sin(angle))
    y = center_point[1]- ((width / 2) * sin(angle)) - ((height / 2) * cos(angle))
    rotated_rect_points.append([x,y])
    x = center_point[0] + ((width / 2) * cos(angle)) + ((height / 2) * sin(angle))
    y = center_point[1] + ((width / 2) * sin(angle)) - ((height / 2) * cos(angle))
    rotated_rect_points.append([x,y])
    cv2.polylines(image, np.array([rotated_rect_points], np.int32), True, color, thickness)

如果您需要对点而不是整个图像应用仿射变换,则可以使用cv.transform cv.getRotationMatrix2D您提供仿射变换以围绕任意中心旋转矩形点。

OpenCV 有一个RotatedRect的概念。 给定宽度、高度和角度,您可以轻松构建它们。 你不需要知道任何三角学,你根本不需要计算。

RotatedRect::points()为您提供矩形的角。 您可以使用它们将矩形绘制为多边形或“轮廓”。

Python 中的等价物是cv.boxPoints函数。 它采用表示 RotatedRect C++ 结构的 Python 数字元组。

这些函数/方法的文档还参考了 OpenCV 文档中包含的教程 它使用drawContours并将四个角点作为一个轮廓传递。

暂无
暂无

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

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