简体   繁体   中英

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

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: 旋转45

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

Thanks

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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