yolov3可见光和红外数据集训练(VOC2007&FLIR)

yolov3可见光和红外数据集训练(VOC2007&FLIR)

1.VOC2007

用到数据集中以下三个文件夹
在这里插入图片描述

  1. Annotations中存放xml文件,标注了各个目标的位置信息
  2. images中存放图片
  3. ImageSets存放分割的train.txt , test.txt , val.txt , trainval.txt(自己生成)

1.1 makeTx.py

运行 makeTx.py 文件(放在根目录),会在ImageSets文件夹下生成上述四个 txt 文件

import os
import random
 
trainval_percent = 0.1
train_percent = 0.9
xmlfilepath = 'data/Annotations'
txtsavepath = 'data/ImageSets'
total_xml = os.listdir(xmlfilepath)
 
num = len(total_xml)
list = range(num)
tv = int(num * trainval_percent)
tr = int(tv * train_percent)
trainval = random.sample(list, tv)
train = random.sample(trainval, tr)
 
ftrainval = open('data/ImageSets/trainval.txt', 'w')
ftest = open('data/ImageSets/test.txt', 'w')
ftrain = open('data/ImageSets/train.txt', 'w')
fval = open('data/ImageSets/val.txt', 'w')
 
for i in list:
    name = total_xml[i][:-4] + '\n'
    if i in trainval:
        ftrainval.write(name)
        if i in train:
            ftest.write(name)
        else:
            fval.write(name)
    else:
        ftrain.write(name)
 
ftrainval.close()
ftrain.close()
fval.close()
ftest.close()

1.2 voc_label.py

运行 voc_label.py 文件(根目录)生成labels标签文件,以及data目录下的txt文件(对应图片路径),用于训练。

#-*- coding:utf-8 -*
import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
 
sets = ['train', 'test','val']
#classes = ['person','bird','cat','cow','dog','horse','bicycle','boat','bus','car','motorbike','train','bottle','chair','diningtable','pottedplant','sofa','tvmonitor']
classes = ['aeroplane','bicycle','bird','boat','bottle','bus','car','cat','chair','cow','diningtable','dog','horse','motorbike','person','pottedplant','sheep','sofa','train','tvmonitor']
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('data/Annotations/%s.xml' % (image_id))
    out_file = open('data/labels/%s.txt' % (image_id), 'w')
    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()
print(wd)
for image_set in sets:
    if not os.path.exists('data/labels/'):
        os.makedirs('data/labels/')
    image_ids = open('data/ImageSets/%s.txt' % (image_set)).read().strip().split()
    list_file = open('data/%s.txt' % (image_set), 'w')
    for image_id in image_ids:
        list_file.write('data/images/%s.jpg\n' % (image_id))
        convert_annotation(image_id)
    list_file.close()

1.3 添加voc.yaml

#train: ../VOC/images/train/  # 16551 images
#val: ../VOC/images/val/  # 4952 images
train: data/train.txt
valid: data/val.txt
# number of classes
nc: 20

# class names
names: [ 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog',
         'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor' ]

1.4 添加data和names文件

yolo.data

classes=20
train=data/train.txt
valid=data/val.txt
names=data/yolo.names
backup=backup/

yolo.names

aeroplane
bicycle
bird
boat
bottle
bus
car
cat
chair
cow
diningtable
dog
horse
motorbike
person
pottedplant
sheep
sofa
train
tvmonitor

1.5 修改cfg文件

修改yolo块中的class和filters为 3*(classes+5)
yolov3可见光和红外数据集训练(VOC2007&FLIR)_第1张图片

1.6 train.py

修改nc为class个数,main中做以下修改(weight,cfg,data,epochs,device)
yolov3可见光和红外数据集训练(VOC2007&FLIR)_第2张图片
训练结果保存在runs中。

2. FLIR

FLIR红外数据集是json格式,最重要的是数据格式转换,我只用到FLIR数据集中的train文件夹,thermal_8_bit文件夹中的图像(放入data目录下的 images中)和thermal_annotations.json文件。

2.1 json转txt(生成labels标签文件)

json_txt.py

from __future__ import print_function
import argparse
import glob
import os
import json

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--data/thermal_annotations.json", help='Directory of json files containing annotations')
    parser.add_argument(
        "--data/labels", help='Output directory for image.txt files')
    args = parser.parse_args()
    args.path = "data"
    args.output_path = "data/labels/"
    json_files = sorted(glob.glob(os.path.join(args.path, '*.json')))

    for json_file in json_files:
        with open(json_file) as f:
            data = json.load(f)
            images = data['images']
            annotations = data['annotations']

            file_names = []
            for i in range(0, len(images)):
                file_names.append(images[i]['file_name'])

            width = 640.0
            height = 512.0

            for i in range(0, len(images)):
                converted_results = []
                for ann in annotations:
                    if ann['image_id'] == i and ann['category_id'] <= 3:
                        cat_id = int(ann['category_id'])
                        # if cat_id <= 3:
                        left, top, bbox_width, bbox_height = map(float, ann['bbox'])

                        # Yolo classes are starting from zero index
                        cat_id -= 1
                        x_center, y_center = (
                            left + bbox_width / 2, top + bbox_height / 2)

                        # darknet expects relative values wrt image width&height
                        x_rel, y_rel = (x_center / width, y_center / height)
                        w_rel, h_rel = (bbox_width / width, bbox_height / height)
                        converted_results.append(
                            (cat_id, x_rel, y_rel, w_rel, h_rel))
                image_name = images[i]['file_name']
                image_name = image_name[14:-5]
                print(image_name)
                file = open(args.output_path + str(image_name) + '.txt', 'w+')
                file.write('\n'.join('%d %.6f %.6f %.6f %.6f' % res for res in converted_results))
                file.close()

2.2 makeTx.py

import os
import random
 
trainval_percent = 0.1
train_percent = 0.9
xmlfilepath = 'data/images'
txtsavepath = 'data/ImageSets'
total_xml = os.listdir(xmlfilepath)
 
num = len(total_xml)
list = range(num)
tv = int(num * trainval_percent)
tr = int(tv * train_percent)
trainval = random.sample(list, tv)
train = random.sample(trainval, tr)
 
ftrainval = open('data/ImageSets/trainval.txt', 'w')
ftest = open('data/ImageSets/test.txt', 'w')
ftrain = open('data/ImageSets/train.txt', 'w')
fval = open('data/ImageSets/val.txt', 'w')
 
for i in list:
    name = total_xml[i][:-5] + '\n'
    if i in trainval:
        ftrainval.write(name)
        if i in train:
            ftest.write(name)
        else:
            fval.write(name)
    else:
        ftrain.write(name)
 
ftrainval.close()
ftrain.close()
fval.close()
ftest.close()

2.3 生成data目录下的txt文件

data_txt.py

#-*- coding:utf-8 -*
import pickle
import os
from os import listdir, getcwd
from os.path import join
 
sets = ['train', 'test','val']
 
wd = getcwd()
print(wd)
for image_set in sets:

    image_ids = open('data/ImageSets/%s.txt' % (image_set)).read().strip().split()
    list_file = open('data/%s.txt' % (image_set), 'w')
    for image_id in image_ids:
        list_file.write('data/images/%s.jpeg\n' % (image_id))

    list_file.close()

最后修改yaml,data,names,cfg,train(同上)。

参考:
(https://blog.csdn.net/qq_37531572/article/details/96751846)
(https://blog.csdn.net/hello_levy/article/details/105212876#comments_16403827)

你可能感兴趣的:(python,深度学习,目标跟踪)