纯YOLOV5实现,参考视频[yolov5小白训练教程]0基础教学,训练自己的数据集,详细教学_哔哩哔哩_bilibili
Json转txt文件代码
import os
import json
from tqdm import tqdm
import argparse
parser = argparse.ArgumentParser()
# 这里根据自己的json文件位置,换成自己的就行
parser.add_argument('--json_path',
default="D:/cowboyoutfits/train.json", type=str,
help="input: coco format(json)")
# 这里设置.txt文件保存位置
parser.add_argument('--save_path', default="D:/cowboyoutfits/train", type=str,
help="specify where to save the output dir of labels")
arg = parser.parse_args()
def convert(size, box):
dw = 1. / (size[0])
dh = 1. / (size[1])
x = box[0] + box[2] / 2.0
y = box[1] + box[3] / 2.0
w = box[2]
h = box[3]
# round函数确定(xmin, ymin, xmax, ymax)的小数位数
x = round(x * dw, 6)
w = round(w * dw, 6)
y = round(y * dh, 6)
h = round(h * dh, 6)
return (x, y, w, h)
if __name__ == '__main__':
json_file = arg.json_path # COCO Object Instance 类型的标注
ana_txt_save_path = arg.save_path # 保存的路径
data = json.load(open(json_file, 'r'))
if not os.path.exists(ana_txt_save_path):
os.makedirs(ana_txt_save_path)
id_map = {} # coco数据集的id不连续!重新映射一下再输出!
with open(os.path.join(ana_txt_save_path, 'classes.txt'), 'w') as f:
# 写入classes.txt
for i, category in enumerate(data['categories']):
f.write(f"{category['name']}\n")
id_map[category['id']] = i
# print(id_map)
# 这里需要根据自己的需要,更改写入图像相对路径的文件位置。
list_file = open(os.path.join(ana_txt_save_path, 'train2017.txt'), 'w')
for img in tqdm(data['images']):
filename = img["file_name"]
img_width = img["width"]
img_height = img["height"]
img_id = img["id"]
head, tail = os.path.splitext(filename)
ana_txt_name = head + ".txt" # 对应的txt名字,与jpg一致
f_txt = open(os.path.join(ana_txt_save_path, ana_txt_name), 'w')
for ann in data['annotations']:
if ann['image_id'] == img_id:
box = convert((img_width, img_height), ann["bbox"])
f_txt.write("%s %s %s %s %s\n" % (id_map[ann["category_id"]], box[0], box[1], box[2], box[3]))
f_txt.close()
# 将图片的相对路径写入train2017或val2017的路径
list_file.write('D:/cowboyoutfits/images/%s.jpg\n' % (head))
list_file.close()
文件转移代码
import pandas as pd
import os
import shutil #用于移动文件
#输入表格所在路径+名称并读取,如D:/data/label.csv,文件后缀不要忘记
csv_path ="E:/PyCharmProjects/yolov5-master/data/cowboyoutfits/valid.csv"
list=pd.read_csv(csv_path)
print(list)
# print(list) #此命令可查看csv文件内容
path = "E:/PyCharmProjects/yolov5-master/data/cowboyoutfits/images/.jpg" #若图像格式为其他,则将后缀更改为其他
# list["File ID"] = input_path
list["File ID1"]=list["file_name"] #File_ID为csv文件中图片文件名,含后缀,即与path路径的图片名完全一致
print(list["File ID1"])
# # #
#label为0,1,2
# for i in range(3):
#即例如指定输出路径分别为D:/data/val/0,1,2
output_path = "E:/PyCharmProjects/yolov5-master/data/cowboyoutfits/images/valid"
#输出路径是否存在,若不存在则创建
isExists = os.path.exists(output_path)
if not isExists:
os.makedirs(output_path)
#label为csv文件中标签列的列名
# listnew = list[list["label"] == i]
l = list["File ID1"].tolist()
print(l)
# 对于File ID中的每一个,执行移动指令
for each in l:
print(each)
# name=each.strip("'")
# print(name)
each = "E:/PyCharmProjects/yolov5-master/data/cowboyoutfits/images/" + each
# each="E:/PyCharmProjects/yolov5-master/data/cowboyoutfits/train/"+each.strip(".jpg")+'.txt'
print(each)
shutil.move(each, output_path)
Data文件夹下结构
data.yaml
train: E:\PyCharmProjects\yolov5-master\data\cowboyoutfits\images\train
val: E:\PyCharmProjects\yolov5-master\data\cowboyoutfits\images\valid
test: E:\PyCharmProjects\yolov5-master\data\cowboyoutfits\images\test
# Classes
nc: 5
names: ["belt","sunglasses","boot","cowboy_hat","jacket"]
终端运行代码
python train.py --batch-size 16 --epochs 300 --data data/cowboyoutfits/data.yaml --weights weights/yolov5l.pt
# 测试
python .\detect.py --source E:\PyCharmProjects\yolov5-master\data\cowboyoutfits\images\test111 --weights runs/train/exp4/weights/best.pt
batch_size大小请根据自己的显卡调整,我使用的是4080,在上述代码运行时会占用13G显存