convert_annotations.py

'''

import sys
import os
import argparse
import xml.etree.ElementTree as ET
from pathlib import Path


def convert_voc_annotation(data_path, anno_path, use_difficult_bbox=True):

classes = ['camera1',  'camera2']
img_inds_file = 'F:/Object detection/YunYang1994-tensorflow-yolov3-master/scripts/number'#
with open(img_inds_file, 'r') as f:
    txt = f.readlines()  # 读取所有行
    image_inds = [line.strip() for line in txt]  # strip()去除首尾的空格,放入列表中
with open(anno_path, 'a') as f:
    for image_ind in image_inds:
        image_path = os.path.join(data_path, 'JPEGImages', image_ind + '.jpg')#拼接路  径/home/yang/test/VOC/test/VOCdevkit/VOC2007/JPEGImages/000001.jpg
        annotation = image_path
        label_path = os.path.join(data_path, 'labels', image_ind + '.xml')

        root = ET.parse(label_path).getroot()
        objects = root.findall('object')
        for obj in objects:
            difficult = obj.find('difficult').text.strip()
            if (not use_difficult_bbox) and(int(difficult) == 1):
                continue
            bbox = obj.find('bndbox')
            class_ind = classes.index(obj.find('name').text.lower().strip())#找出某个值在列表中的索引位置
            xmin = bbox.find('xmin').text.strip()
            xmax = bbox.find('xmax').text.strip()
            ymin = bbox.find('ymin').text.strip()
            ymax = bbox.find('ymax').text.strip()
            annotation += ' ' + ','.join([xmin, ymin, xmax, ymax, str(class_ind)])#拼接坐标值,48,240,195,371,11 8,12,352,498,14
        print(annotation)
        f.write(annotation + "\n")
return len(image_inds)

if __name__=="__main__":
data_path='F:/Object detection/YunYang1994-tensorflow-yolov3-master/'
anno_path=os.path.join(data_path,"data/dataset/voc1_train.txt")

parser = argparse.ArgumentParser()  # 创建一个解析器
parser.add_argument("--data_path", default='F:/Object detection/YunYang1994-tensorflow-yolov3-master/')  # 添加参数
parser.add_argument("--train_annotation", default="./data/dataset/voc1_train.txt")
parser.add_argument("--test_annotation",  default="./data/dataset/voc_test1.txt")
flags = parser.parse_args()  # 解析参数
path = Path('F:/Object detection/YunYang1994-tensorflow-yolov3-master/labels')
if os.path.exists(flags.train_annotation):os.remove(flags.train_annotation)#如果路径下存在文件,删除文件
if os.path.exists(flags.test_annotation):os.remove(flags.test_annotation)#
num1=convert_voc_annotation(flags.data_path,flags.train_annotation,False)
print(num1)
上一篇:python 编写 git 服务端钩子hook


下一篇:Day01-2