SSD-函式用法

醬紫,發表於2020-10-28

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
僅用於自身學習記錄

相關文章