1、使用labelme进行图像标注,标注后生成json文件,json文件中存放的内容如下:
2、将json文件转换为yolo格式
labelme标注后的json文件中存放的为目标的实际位置坐标(x1,y1,x2,y2),但是yolov3中使用的是目标的相对位置(x,y,w,h),其中x,y为目标框的中心坐标点,w和h为目标框的宽和高。使用json2yolo.py文件实现转换。
# json2yolo.py
import json
import os
def convert(img_size, box):
dw = 1. / (img_size[0]) #将w和h压缩到0-1之间
dh = 1. / (img_size[1])
# (x,y)为标注框的中心坐标,w和h为宽和高
x = (box[0] + box[2]) / 2.0 - 1
y = (box[1] + box[3]) / 2.0 - 1
w = box[2] - box[0]
h = box[3] - box[1]
x = x * dw
w = w * dw
y = y * dh
h = h * dh
# x1 = box[0]
# y1 = box[1]
# x2 = box[2]
# y2 = box[3]
return (x, y, w, h)
def decode_json(json_floder_path, json_name):
# 修改转换后存放txt文件的路径
txt_name = 'data\custom\labels\' + json_name[0:-5] + '.txt'
txt_file = open(txt_name, 'w')
json_path = os.path.join(json_floder_path, json_name)
data = json.load(open(json_path, 'r', encoding='utf-8')) # 加载json文件 gb2312
img_w = data['imageWidth']
img_h = data['imageHeight']
for i in data['shapes']:
label_name = i['label']
if (i['shape_type'] == 'rectangle'):
x1 = int(i['points'][0][0])
y1 = int(i['points'][0][1])
x2 = int(i['points'][1][0])
y2 = int(i['points'][1][1])
bb = (x1, y1, x2, y2)
bbox = convert((img_w, img_h), bb) # 将(x1,y1,x2,y2)转换为yolo的格式(x,y,w,h)
txt_file.write(str(name2id[label_name]) + " " + " ".join([str(a) for a in bbox]) + 'n')
if __name__ == "__main__":
name2id = {'person':0,'airplane':1} # 自己数据集中全部的类别名
# json文件夹的路径
json_floder_path = 'data\Annotations'
json_names = os.listdir(json_floder_path)
for json_name in json_names:
decode_json(json_floder_path, json_name)
执行结束后存放txt文件的路径中的内容如下:
3、训练集和验证集数据的划分
将训练集图像和验证集图像的路径写入到train.txt和val.txt文件中,如下:
4、修改配置文件
(1)将classes.names文件中的类别修改为自己的类别
(2)修改config/custom.data文件中与自己任务相关的配置
5、准备模型
打开git bash,执行configcreate_custom_model.sh文件
执行语句
sh create_custom_model.sh 2 # 2为类别数,执行时换成自己的类别数
执行完成后会生成cfg文件
create_custom_model.sh文件不能重复执行,要先将生成的cfg文件删除再执行
6、模型训练
修改train.py文件中的这些参数,然后进行训练,训练结束会生成多个.pth文件



