voc_annotation.py
1、解析xml文件
import xml.etree.ElementTree as ET
in_file = open('VOCdevkit/VOC%s/Annotations/%s.xml'%(year,image_id))
tree=ET.parse(in_file)
root = tree.getroot()
for obj in root.iter('object'):
# print(obj)
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))
------》注解
2、获取当前路径
from os import getcwd
wd=getcwd()
wd=wd.replace('\\', '/')
3、将解析的数据写入xml文件中
for year, image_set in sets:
image_ids = open('VOCdevkit/VOC%s/ImageSets/Main/%s.txt'%(year, image_set)).read().strip().split()
print(image_ids)
list_file = open('%s_%s.txt'%(year, image_set), 'w')
for image_id in image_ids:
list_file.write('%s/VOCdevkit/VOC%s/JPEGImages/%s.jpg'%(wd, year, image_id))
convert_annotation(year, image_id, list_file)
list_file.write('\n')
list_file.close()
---------》》》》注解
strip():移除头尾指定字符,此时移除为头尾的空格
split() 通过指定分隔符对字符串进行切片,此时以空格为分隔符
4、列表的应用(包含元组的列表和索引)
sets=[('2007', 'train'), ('2007', 'val'), ('2007', 'test')]
for year, image_set in sets:
classes = ["aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]
cls_id = classes.index(cls)
5、结果输出
6、整体代码
https://blog.csdn.net/m0_45085566/article/details/109322383
仅用于自身学习记录