yolo训练自己的数据集,如何生成图像标签txt文件

前提:

1、待训练图像已经有标签文件xml了(可使用labelImage工具获得)。

2、下载了darknet-master安装包

正文:

在darknet-master/scripts/文件夹下,有voc_label.py文件,是针对VOC数据集生成标签txt文件的,这里把这个文件修改下,用来生成自己数据集的标签txt文件。

修改后的voc_label.py文件如下:

#!/usr/bin/python
# -*- coding:utf-8 -*-

import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join

#classes = ["aeroplane", "bicycle", "bird", "boat", "bottle"]
classes = ["smoke"]#(改!)自己要测的目标类别


def convert(size, box):
    dw = 1./(size[0])
    dh = 1./(size[1])
    x = (box[0] + box[1])/2.0 - 1
    y = (box[2] + box[3])/2.0 - 1
    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('/root/darknet-master/data/Annotations/%s.xml'%(image_id))#(改!)自己的图像标签xml文件的路径
    out_file = open('/root/darknet-master/data/obj/%s.txt'%(image_id), 'w')#(改!)自己的图像标签txt文件要保存的路径
    tree=ET.parse(in_file)#直接解析xml文件
    root = tree.getroot()#获取xml文件的根节点
    size = root.find('size')#获取指定节点“图像尺寸”
    w = int(size.find('width').text)#获取图像宽
    h = int(size.find('height').text)#图像高

    for obj in root.iter('object'):
        difficult = obj.find('difficult').text#xml里的difficult参数
        cls = obj.find('name').text#要检测的类别名称name
        if cls not in classes or int(difficult)==1:
            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')


#用VOC数据集的话,是将VOCdevkit/VOC2007/ImageSets/Main/文件夹下的所有txt都循环读入了
#这里我只读入所有待训练图像的路径list.txt
image_paths = open('/root/darknet-master/data/obj/list.txt').read().strip().split()#(改!)
#list_file = open('train.txt', 'w')
for image_path in image_paths:
    #list_file.write('/root/darknet-master/data/obj/%s.jpg\n'%(image_id))
    image_id=os.path.split(image_path)[1]#image_id内容类似'0001.jpg'
    image_id2=os.path.splitext(image_id)[0]#image_id2内容类似'0001'
    convert_annotation(image_id2)

为了防止出错,我的文件路径用的都是绝对路径。

最终结果如下图,图像与txt文件放在了一个文件夹下:

你们要用的话需要修改如下内容(代码里有注明):

1、类别名称classes

2、xml路径

3、保存的txt路径

4、图像名列表txt文件路径

猜你喜欢

转载自blog.csdn.net/qq_38214193/article/details/81132053