【发布时间】:2021-07-17 19:02:27
【问题描述】:
我将 cv2 矩形用于边界框,我想将它围绕其轴旋转某个角度。因为warpAffine函数是用来旋转图片的,所以这里不能用。
【问题讨论】:
标签: python opencv computer-vision
我将 cv2 矩形用于边界框,我想将它围绕其轴旋转某个角度。因为warpAffine函数是用来旋转图片的,所以这里不能用。
【问题讨论】:
标签: python opencv computer-vision
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)
【讨论】:
我已经有一段时间使用它了,但据我所知,所有这些 ROI 类型都只是普通的 x-y 矩形。没有旋转是可能的(你也可以从构造函数中看到,没有办法定义旋转)。所以它总是沿 x 轴宽,沿 y 轴高。
如果你只想绘制矩形,我建议确定所有四个角点,然后用简单的线条绘制边界框。最终,您可以使用折线在一个命令中完成。
【讨论】:
如果您需要对点而不是整个图像应用仿射变换,可以使用cv.transform。 cv.getRotationMatrix2D 为您提供仿射变换,以围绕任意中心旋转矩形点。
OpenCV 具有RotatedRect 的概念。您可以在给定宽度、高度和角度的情况下轻松构建它们。你不需要知道任何三角学,你根本不需要计算。
RotatedRect::points() 为您提供矩形的角。您可以使用它们将矩形绘制为多边形或“轮廓”。
Python 中的等价物是cv.boxPoints 函数。它采用表示 RotatedRect C++ 结构的 Python 数字元组。
这些函数/方法的文档还引用了包含在 OpenCV 文档中的 tutorial。它使用drawContours 并将四个角点作为一个轮廓传递。
【讨论】: