按给定角度旋转一个边界框
创始人
2024-10-14 08:30:29
0

下面是一个示例代码,用于按给定角度旋转一个边界框:

import cv2
import numpy as np

def rotate_bbox(bbox, angle, image_shape):
    # 计算边界框的中心点坐标
    center_x = (bbox[0] + bbox[2]) // 2
    center_y = (bbox[1] + bbox[3]) // 2

    # 计算边界框的宽度和高度
    width = bbox[2] - bbox[0]
    height = bbox[3] - bbox[1]

    # 创建旋转矩阵
    rotation_matrix = cv2.getRotationMatrix2D((center_x, center_y), angle, 1)

    # 将旋转矩阵应用于边界框的四个角点
    corners = np.array([[bbox[0], bbox[1]],
                       [bbox[2], bbox[1]],
                       [bbox[2], bbox[3]],
                       [bbox[0], bbox[3]]], dtype=np.float32)
    rotated_corners = cv2.transform(np.array([corners]), rotation_matrix)[0]

    # 计算旋转后的边界框的新边界
    min_x = int(min(rotated_corners[:, 0]))
    max_x = int(max(rotated_corners[:, 0]))
    min_y = int(min(rotated_corners[:, 1]))
    max_y = int(max(rotated_corners[:, 1]))

    # 确保边界框不超出图像范围
    min_x = max(0, min_x)
    max_x = min(image_shape[1], max_x)
    min_y = max(0, min_y)
    max_y = min(image_shape[0], max_y)

    return [min_x, min_y, max_x, max_y]

# 示例用法
bbox = [100, 100, 200, 200]  # 边界框的坐标:[x_min, y_min, x_max, y_max]
angle = 45  # 旋转角度
image_shape = (512, 512)  # 图像尺寸:(height, width)

rotated_bbox = rotate_bbox(bbox, angle, image_shape)
print("旋转后的边界框:", rotated_bbox)

上述代码使用OpenCV库来实现边界框的旋转。首先,计算边界框的中心点坐标,然后创建一个旋转矩阵,并将其应用于边界框的四个角点。最后,计算旋转后的边界框的新边界,并确保边界框不超出图像范围。运行示例代码后,将打印出旋转后的边界框坐标。

相关内容

热门资讯

安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
避免在粘贴双引号时向VS 20... 在粘贴双引号时向VS 2022添加反斜杠的问题通常是由于编辑器的自动转义功能引起的。为了避免这个问题...
Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
omi系统和安卓系统哪个好,揭... OMI系统和安卓系统哪个好?这个问题就像是在问“苹果和橘子哪个更甜”,每个人都有自己的答案。今天,我...
原生ios和安卓系统,原生对比... 亲爱的读者们,你是否曾好奇过,为什么你的iPhone和安卓手机在操作体验上有着天壤之别?今天,就让我...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...
Alertmanager在pr... 首先,在Prometheus配置文件中,确保Alertmanager URL已正确配置。例如:ale...