用PIL画旋转的GT

在数据集上画GT

所用标签格式

robndbox 中的中心点坐标和框的宽高以及旋转角度
用PIL画旋转的GT_第1张图片

转换代码

def rota(center_x1, center_y1, x, y, w, h, a):  # 旋转中心点,旋转中心点,框的w,h,旋转角

    # a = (math.pi * a) / 180  # 角度转弧度
    x1, y1 = x - w / 2, y - h / 2  # 旋转前左上
    x2, y2 = x + w / 2, y - h / 2  # 旋转前右上
    x3, y3 = x + w / 2, y + h / 2  # 旋转前右下
    x4, y4 = x - w / 2, y + h / 2  # 旋转前左下

    px1 = (x1 - center_x1) * math.cos(a) - (y1 - center_y1) * math.sin(a) + center_x1  # 旋转后左上
    py1 = (x1 - center_x1) * math.sin(a) + (y1 - center_y1) * math.cos(a) + center_y1
    px2 = (x2 - center_x1) * math.cos(a) - (y2 - center_y1) * math.sin(a) + center_x1  # 旋转后右上
    py2 = (x2 - center_x1) * math.sin(a) + (y2 - center_y1) * math.cos(a) + center_y1
    px3 = (x3 - center_x1) * math.cos(a) - (y3 - center_y1) * math.sin(a) + center_x1  # 旋转后右下
    py3 = (x3 - center_x1) * math.sin(a) + (y3 - center_y1) * math.cos(a) + center_y1
    px4 = (x4 - center_x1) * math.cos(a) - (y4 - center_y1) * math.sin(a) + center_x1  # 旋转后左下
    py4 = (x4 - center_x1) * math.sin(a) + (y4 - center_y1) * math.cos(a) + center_y1

    return px1, py1, px2, py2, px3, py3, px4, py4  # 旋转后的四个点,左上,右上,右下,左下

画图的代码

根据自己的路径修改

img_dir = r'D:\dataset\sar\RSDD\RSDD-SAR\JPEGImages'
label_dir = r'D:\dataset\sar\RSDD\RSDD-SAR\Annotations'
save_dir = r'D:\dataset\sar\RSDD\RSDD-SAR\img_with_label'
label_dirs = os.listdir(label_dir)
if not os.path.exists(save_dir):
    os.makedirs(save_dir)

for label in label_dirs:
    xml_file = open(os.path.join(label_dir, label), encoding='utf-8')
    tree = et.parse(xml_file)
    root = tree.getroot()
    img = Image.open(os.path.join(img_dir, label[:-4] + '.jpg'))
    im_draw = ImageDraw.ImageDraw(img)
    for obj in root.iter('object'):
        box = obj.find('robndbox')
        x_c = box.find('cx').text
        y_c = box.find('cy').text
        h = box.find('h').text
        w = box.find('w').text
        theta = box.find('angle').text
        box = list(map(np.float32, [x_c, y_c, h, w, theta]))
        box = rota(box[0], box[1], *box)

        im_draw.line((box[0], box[1]) + (box[2], box[3]), fill='red', width=1)
        im_draw.line((box[2], box[3]) + (box[4], box[5]), fill='red', width=1)
        im_draw.line((box[4], box[5]) + (box[6], box[7]), fill='red', width=1)
        im_draw.line((box[6], box[7]) + (box[0], box[1]), fill='red', width=1)
        img.save(save_dir + '/%s' % label[:-4] + '.jpg')

最后效果图

用PIL画旋转的GT_第2张图片

你可能感兴趣的:(目标检测)