How can I find new coordinates of boundary box of rotated image to modify its xml file for Tensorflow data augmentation?

本秂侑毒 提交于 2020-01-06 14:49:12

问题


I'm trying to make more dataset to train my model in Tensorflow for data augmantaion. I added the labels of boundary boxes to original image. I want to rotate image 45 degree and modify the xml file for the new exact boundary box(rectangle) to label new created image. It's resizing and fetching to window to not to loose anything on image.

Let me show you how I try:

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)

After rotation the image is like this:

By the way, I'm using Python and OpenCV. I can't calculate the exact new coordinates to label the image.

Thanks


回答1:


I cannot add a comment in the post above, so sorry for the post. All you need is print after rotation values from corners

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

and if you want a specific value just use

print(corners[0])
print(corners[1])
print(corners[2])
print(corners[3])


来源:https://stackoverflow.com/questions/52594956/how-can-i-find-new-coordinates-of-boundary-box-of-rotated-image-to-modify-its-xm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!