VOC xml转YOLO txt 的python脚本

从网上down了些数据集,是voc格式的,为了训练yolo写了个脚本做转化:

注意修改其中的classes和路径。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 15 21:56:32 2019

@author: youxinlin
"""

import copy
from lxml.etree import Element, SubElement, tostring, ElementTree
 
import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
 
classes = ["bottle","grass","branch","milk-box","plastic-bag","plastic-garbage","ball","leaf"]  #类别

def convert(size, box):
    dw = 1./size[0]
    dh = 1./size[1]
    x = (box[0] + box[1])/2.0
    y = (box[2] + box[3])/2.0
    w = box[1] - box[0]
    h = box[3] - box[2]
    x = x*dw
    w = w*dw
    y = y*dh
    h = h*dh
    return (x,y,w,h)
 
def convert_annotation(image_id):
    
    in_file = open('/Users/youxinlin/Desktop/datasets/dataset-floats/Annotations/%s.xml'%(image_id))
    
    out_file = open('/Users/youxinlin/Desktop/datasets/dataset-floats/%s.txt'%(image_id),'w') #生成txt格式文件
    tree=ET.parse(in_file)
    root = tree.getroot()
    size = root.find('size')  
    w = int(size.find('width').text)
    h = int(size.find('height').text)
 
    for obj in root.iter('object'):
        cls = obj.find('name').text
        if cls not in classes :
            continue
        cls_id = classes.index(cls)
        xmlbox = obj.find('bndbox')   
        b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text))
        bb = convert((w,h), b)
        out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
        
        
image_ids_train = open('/Users/youxinlin/Desktop/datasets/dataset-floats/ImageSets/Main/test.txt').read().strip().split()#list格式只有000000 000001
 
#image_ids_val = open('/home/*****/darknet/scripts/VOCdevkit/voc/list').read().strip().split()
 
 
list_file_train = open('test.txt', 'w')     
#list_file_val = open('val.txt', 'w')     
 
 
for image_id in image_ids_train:
    list_file_train.write('/Users/youxinlin/Desktop/datasets/dataset-floats/%s.jpg\n'%(image_id))  
    convert_annotation(image_id)   

其中,txt可改为train.txt valid.txt等,根据需要自行修改。

发布了150 篇原创文章 · 获赞 334 · 访问量 74万+

猜你喜欢

转载自blog.csdn.net/lyxleft/article/details/100868067