python - 如何找到旋转图像边界框的新坐标以修改其xml文件以进行Tensorflow数据增强?

标签 python opencv tensorflow rotation elementtree

我正在尝试创建更多数据集以在Tensorflow中训练我的模型以进行数据预测。我将边界框的标签添加到原始图像。我想将图像旋转45度,并为新的精确边界框(矩形)修改xml文件以标记新创建的图像。它正在调整大小并提取到窗口以不丢失图像上的任何内容。

让我告诉你我如何尝试:

def rotateImage(mat, angle):
    height, width = mat.shape[:2]
    image_center = (width / 2, height / 2)

    rotation_mat = cv2.getRotationMatrix2D(image_center, angle, 1)

    radians = math.radians(angle)
    sin = math.sin(radians)
    cos = math.cos(radians)
    bound_w = int((height * abs(sin)) + (width * abs(cos)))
    bound_h = int((height * abs(cos)) + (width * abs(sin)))

    rotation_mat[0, 2] += ((bound_w / 2) - image_center[0])
    rotation_mat[1, 2] += ((bound_h / 2) - image_center[1])

    rotated_mat = cv2.warpAffine(mat, rotation_mat, (bound_w, bound_h))
    return rotated_mat


image = cv2.imread("test.jpg")

angle = 45

rotated_45_image = image.copy()

rotated_45_image = rotateImage(rotated_45_image, angle=45)

tree_for_45_rotated = ET.parse(file_name + ".xml")
root = tree_for_xml.getroot()

for object in root.iter("object"):
    xmin = object.find("bndbox").find("xmin")
    ymin = object.find("bndbox").find("ymin")
    xmax = object.find("bndbox").find("xmax")
    ymax = object.find("bndbox").find("ymax")
    print(xmin.text, ymin.text, xmax.text, ymax.text)
    print("new")
    new_xmin = math.cos(angle) * int(xmin.text) - math.sin(angle) * int(ymin.text)
    new_xmax = math.cos(angle) * int(xmax.text) - math.sin(angle) * int(ymin.text)
    new_ymin = math.sin(angle) * int(xmin.text) + math.cos(angle) * int(ymin.text)
    new_ymax = math.sin(angle) * int(xmin.text) + math.cos(angle) * int(ymax.text)
    print(new_xmin, new_ymin, new_xmax, new_ymax)

旋转后,图像如下所示:
Rotated 45

顺便说一句,我正在使用Python和OpenCV。我无法计算出确切的新坐标来标记图像。

谢谢

最佳答案

我无法在上面的帖子中添加评论,对不起。您所需要的只是在转角旋转值之后打印

img = cv2.imread("test.jpg")
rotated, corners = rotateImage(img, 30)
print(corners)

如果您想要特定的值,请使用
print(corners[0])
print(corners[1])
print(corners[2])
print(corners[3])

关于python - 如何找到旋转图像边界框的新坐标以修改其xml文件以进行Tensorflow数据增强?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52594956/

相关文章:

Python 等同于 MATLAB 的 normplot?

python - TensorFlow MLP 不训练 XOR

python-3.x - 获取破坏图像所需的梯度值

python - 如何将变量与文本字符串混合?

python - 如何给一些矩阵着色

python - 从特定目录读取多个图像,并使用python和opencv将它们保存到另一个目录

Opencv 库中的 Python 函数原型(prototype)

opencv - 将 OpenCV 的 Mat 容器与用于矩阵乘法的 blas 接口(interface)

python - assert _backend in {'theano' , 'tensorflow' } AssertionError

python - 如何根据值为 Python Pandas 中的整行着色?