Pytorch每一步该怎么做 !!!——得到数据

1. 先创建自己的 JpgImages 文件夹,存放需要训练的图片。

2. 利用LabelImg标注工具,生成存放标注 .xml 文件的 Annotations 文件。

3. 利用 xml_2_txt.py, 将 标注文件(Annotations) 生成 ImageSets/Main文件夹内的索引文件 包含了每个类别包含的图片名称。

.
└── Main
├── test.txt
├── train.txt
├── trainval.txt
└── val.txt

import os
import random 
 
xmlfilepath=r'./VOCdevkit/VOC2007/Annotations'                  # 从 Annotations 中读取 .xml 标签文件 
saveBasePath=r"./VOCdevkit/VOC2007/ImageSets/Main/"             # 将生成的 .txt 文件 保存在 Main 文件夹中
 
trainval_percent=1
train_percent=1

temp_xml = os.listdir(xmlfilepath)
total_xml = []
for xml in temp_xml:
    if xml.endswith(".xml"):
        total_xml.append(xml)

num=len(total_xml)  
list=range(num)              
tv=int(num*trainval_percent)                                     # .xml 中有多少用于验证集             
tr=int(tv*train_percent)                                         # .xml 中有多少用于训练集
trainval= random.sample(list,tv)  
train=random.sample(trainval,tr)  
 
print("train and val size",tv)
print("traub suze",tr)
ftrainval = open(os.path.join(saveBasePath,'trainval.txt'), 'w')   # 验证集 .txt 保存的是用于验证的 图片 文件名
ftest = open(os.path.join(saveBasePath,'test.txt'), 'w')           # 测试集 .txt 保存的是用于测试的 图片 文件名
ftrain = open(os.path.join(saveBasePath,'train.txt'), 'w')         # 训练集 .txt 保存的是用于训练的 图片 文件名
fval = open(os.path.join(saveBasePath,'val.txt'), 'w')             # 验证集 .txt 保存的是用于验证的 图片 文件名      
 
for i  in list:  
    name=total_xml[i][:-4]+'\n'  
    if i in trainval:  
        ftrainval.write(name)  
        if i in train:  
            ftrain.write(name)  
        else:  
            fval.write(name)  
    else:  
        ftest.write(name)  
  
ftrainval.close()  
ftrain.close()  
fval.close()  
ftest .close()

例如:

train.txt:

1921681108_IPPTZCamera_main_20190930151046_1
1921681108_IPPTZCamera_main_20191010154500_1
1921681108_IPPTZCamera_main_20190930104237_1
1921681108_IPPTZCamera_main_20190930104147_1

4. voc_annotation.py 把 Main/train.txt 文件加以利用, 生成最后传给训练网络的数据。

实际就是根据 train.txt 里面的 图片 文件名,找到对应的图片,并将 Annotations 里面的标签框 的信息加在后面,构成了输入数据

生成了.
├── 2007_test.txt
├── 2007_train.txt
├── 2007_val.txt

2007_train.txt 文件内容是:
/home/yonne/Pro/YOLO_v4/my_yolov4/VOCdevkit/VOC2007/JPEGImages/001816.jpg 1,36,369,250,7
表示: 图片的绝对路径 | 目标框出的位置 | 目标种类

voc_annotation.py 代码如下:

import xml.etree.ElementTree as ET
from os import getcwd

sets=[('2007', 'train'), ('2007', 'val'), ('2007', 'test')]

classes = ["aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]


def convert_annotation(year, image_id, list_file):
    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'):
        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))

wd = getcwd()

for year, image_set in sets:
    image_ids = open('VOCdevkit/VOC%s/ImageSets/Main/%s.txt'%(year, image_set)).read().strip().split()
    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()


import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
 
# 要制作的数据路径
sets=[('myData', 'train')]

# 自己的要分类的类别 
classes = ["luosuan"]

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)
 
# image_id 是不带后缀的文件名  
def convert_annotation(fdir, image_id):
    in_file = open('myData/Annotations/%s.xml'%(image_id))      # 根据索引得到标签文件 .xml
    out_file = open('myData/labels/%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'):
        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 = (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')
 
wd = getcwd()       # 获取当前 目录 绝对路径
 
for fdir, image_set in sets:                        # fdir 表示索引文件的父路径
    
    if not os.path.exists('myData/labels/'):        # 生成最终的标签文件路径
        os.makedirs('myData/labels/')
    image_ids = open('myData/ImageSets/Main/%s.txt'%(image_set)).read().strip().split()     # 打开 train.txt 索引文件,并且按行读取
    list_file = open('myData/%s_%s.txt'%(fdir, image_set), 'w')         # 打开 myData/my_data_train.txt 文件,这是个新生成的空文件,可写
    
    # 根据 train.txt 中的文件索引,向 my_data_train.txt 中写入训练数据信息
    for image_id in image_ids:  
        list_file.write('%s/myData/JPEGImages/%s.jpg\n'%(wd, image_id)) # 写如当前图片完整的名称 (带.jpg 后缀的,因为索引文件中没有图像后缀!!!)
        convert_annotation(fdir, image_id)  # 写入 当前图片的标注信息
    
    list_file.close()


  1. 在 train.py文件中输入是:
if __name__ == "__main__":
    # 标签的位置
    annotation_path = '2007_train.txt'
    # 获取classes和anchor的位置
    classes_path = 'model_data/voc_classes.txt'    
    anchors_path = 'model_data/yolo_anchors.txt'
    weights_path = 'model_data/yolo4_weight.h5'
表示输入的训练数据,类别标签(voc是20类),先验框的尺寸,和预训练的权重。

posted @ 2020-10-09 20:53  yonne  阅读(96)  评论(0)    收藏  举报