数据标注篇---从labelimg中提取目标框的坐标

数据标注篇—从labelimg中提取目标框的坐标

1、提取图片的名字

import random
import os
import xml.etree.ElementTree as ET

# 需要修改  标签的名字
XML_FILE_PATH = "./labels/"
SAVE_BASE_PATH = "./saves/"

temp_xml = os.listdir(XML_FILE_PATH)
total_xml = []
for xml in temp_xml:
    if xml.endswith(".xml"):
        total_xml.append(xml)

num = len(total_xml)
list = range(num)
tv = int(num)
tvs = random.sample(list, tv)

if not os.path.exists(SAVE_BASE_PATH):
    os.makedirs(SAVE_BASE_PATH)
ftvs = open(os.path.join(SAVE_BASE_PATH, 'images.txt'), 'w')

for i in list:
    name = total_xml[i][:-4]+'\n'
    if i in tvs:
        ftvs.write(name)

ftvs.close()

2、提前目标框的坐标

import xml.etree.ElementTree as ET
import os


# 需要修改 图片的所放的文件名称
sets = [("images")]
# 需要修改 图片里面的类别标签
classes = ["area"]
IMAGE_PATH = "./saves/{}.txt"
DATA_TXT = "./saves/"
# 需要修改 图片写入的路径 以及图片名称后缀
IMAGE_WRITE_PATH = "images/{}.jpg"
# 需要修改 图片所对应的标签的路径
OPEN_XML_PATH = "labels/{}.xml"

def convert_annotation(image_id, list_file):
    in_file = open(OPEN_XML_PATH.format(image_id))
    tree = ET.parse(in_file)
    root = tree.getroot()
    list_file.write(IMAGE_WRITE_PATH.format(image_id))
    for obj in root.iter('object'):
        difficult = obj.find('difficult').text
        cls = obj.find('name').text
        if cls not in classes or int(difficult) == 1:
            continue
        cls_id = classes.index(cls)
        xmlbox = obj.find('bndbox')
        b = (int(xmlbox.find('xmin').text), int(xmlbox.find('ymin').text), int(xmlbox.find('xmax').text), int(xmlbox.find('ymax').text))
        list_file.write(" " + ",".join([str(a) for a in b]) + ',' + str(cls_id))

    list_file.write('\n')


for image_set in sets:
    image_ids = open(IMAGE_PATH.format(image_set)).read().strip().split()
    save_data_path = '/'.join(DATA_TXT.split('/')[:-1])
    if not os.path.exists(save_data_path):
        os.makedirs(save_data_path)
    list_file = open(os.path.join(DATA_TXT, "images_final.txt"), 'w')
    for image_id in image_ids:
        convert_annotation(image_id, list_file)
    list_file.close()

结果如下

images.txt
数据标注篇---从labelimg中提取目标框的坐标_第1张图片
images_final.txt
数据标注篇---从labelimg中提取目标框的坐标_第2张图片

你可能感兴趣的:(java,python,前端)