【服务器训练调整yolov8时踩坑问题,修改记录】
服务器训练调整yolov8时出现的问题
* 另外网上yolov8教程特别多,关于数据集准备和制作这块,可以直接拆分的时候图片也拆分,也可以只记录在txt中,有三种方式所以在制作的时候都可以选择。需要也可以私信把我的处理脚本发你。
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
近期在服务器利用yolov8训练一些通用模型,发现不同时间段clone的yolov8内容和文件路径不同,因为比较新更新变动比较多,训练过程中踩的坑记录下来。
1、mobaxterm打开服务器上的 .py直接更改导致训练报错的乱码问题
有些bug会因为你的小失误导致一连串的效应,我因为更改labels路径,想去修改utils.py的默认images换成JPEGImages,结果报错是漏下的后引号;然后直接在mobaxterm上打开修改添加后引号,接着开始训练报错乱码问题:
YOLOV8:FileNotFoundError: train: No labels found in; 出现这个问题,是没有找到labels相应的位置,大概率是你生成的train.txt中路径对应的名称对不上号导致,检查一下文件夹的名字,是images还是JPEGImages。尽量不去修改utils.py,去重新生成train.txt,不然直接修改有可能会导致编码问题。 如果要改的话建议参考: https://blog..net/Nuy_oah1/article/details/130809480 在ultralytics/yolo/data这个目录下找到utils.py文件,并按照下图修改,修改内容为:
def img2label_paths(img_paths):
"""Define label paths as a function of image paths."""
sa, sb = f'{os.sep}images{os.sep}', f'{os.sep}labels{os.sep}' # /images/, /labels/ substrings
return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths]
SyntaxError: (unicode error) ‘utf-8‘ codec can‘t decode byte 0xc5 in position 0: invalid; 出现这个问题是因为使用了非标准编辑器导致的源码出现编码错误。 这时候再拉到本地用pycharm打开编码utf-8也无济于事,你会发现.py文件中还是存在乱码, 可以尝试在文件中添加声明,
#!/usr/bin/python
# -*- coding: UTF-8 -*-
如果还是不还用,还有笨办法,也是最有效的:出现这种问题基本都是.py文件里的表情符号问题,可以删掉,或者utils.py可以从你的虚拟环境中找到,把缺失的符号乱码问题替换掉即可(注意,不同时段的yolov8文件内容可能不同,别全部copy,只copy需要更换的)
2、yolov8训练停掉,继续上次last.pt继续训练;
网上有很多方法,比如修改trainer.py文件和model.py文件;或者只修改resume=last.pt后重新跑,报错很多类型,建议直接参考官网方法。 AssertionError: ./yolov8n.pt training to 500 epochs is finished, nothing to resume. Start a new training without resuming, i.e. ‘yolo train model=./yolov8n.pt’ 官网方法没有那么多花里胡哨,而且修改简单, https://docs.ultralytics.com/modes/train/#resuming-interrupted-trainings官网链接; 打开resume=True后,直接命令行:
yolo train resume model=path/to/last.pt
3、训练完成后,发现测试结果完全相反;
烟和火全相反了
出现这种情况的原因是标签错误,检查下:
xml转txt脚本中,有class列表,元素顺序是否和classes.txt中行元素顺序对应。data.yaml中有classes的names: 所有顺序都要对应,不然标注框对应的非识别物体。
4、标签和类别不匹配
RuntimeError: CUDA error: device-side assert triggered CUDA kernel errors might be asynchronously reported at some other API call,so the stacktrace below might be incorrect. For debugging consider passing CUDA_LAUNCH_BLOCKING=1.
出现这个问题的原因,一开始以为是图像质量或者编码问题,因为我在数据处理的时候有格式报错过, libpng warning: sBIT: invalid 这个警告一直存在,是图像原来有png格式的我强制改后缀jpg造成的。后来借鉴https://blog..net/Penta_Kill_5/article/details/118085718这篇,应该是我检测类型和标签类型对不上号,比如标签是1-4,而我分三类;或者是标签是1-3,分类0-2。 我想直接更改yaml中nc names设置类型和标签对得上,还是报错,最后直接重新操作数据,csv to json to txt 重新生成对应的txt标签后报错解决。
5、实时检测时对接rtsp视频流
以海康威视为例,source改成"rtsp://admin:123456@192.168.1.3/Streaming/Channels/1"这个字符串即可,用户名:密码@摄像头地址
6、数据集制作过程中可能会用到的数据处理脚本
1. csv转json
'''
官方给出的csv中的
{
"meta":{},
"id":"88eb919f-6f12-486d-9223-cd0c4b581dbf",
"items":
[
{"meta":{"rectStartPointerXY":[622,2728],"pointRatio":0.5,"geometry":[622,2728,745,3368],"type":"BBOX"},"id":"e520a291-bbf7-4032-92c6-dc84a1fc864e","properties":{"create_time":1620610883573,"accept_meta":{},"mark_by":"LABEL","is_system_map":false},"labels":{"鏍囩":"ground"}}
{"meta":{"pointRatio":0.5,"geometry":[402.87,621.81,909,1472.01],"type":"BBOX"},"id":"2c097366-fbb3-4f9d-b5bb-286e70970eba","properties":{"create_time":1620610907831,"accept_meta":{},"mark_by":"LABEL","is_system_map":false},"labels":{"鏍囩":"safebelt"}}
{"meta":{"rectStartPointerXY":[692,1063],"pointRatio":0.5,"geometry":[697.02,1063,1224,1761],"type":"BBOX"},"id":"8981c722-79e8-4ae8-a3a3-ae451300d625","properties":{"create_time":1620610943766,"accept_meta":{},"mark_by":"LABEL","is_system_map":false},"labels":{"鏍囩":"offground"}}
],
"properties":{"seq":"1714"},"labels":{"invalid":"false"},"timestamp":1620644812068
}
'''
import pandas as pd
import json
import os
from PIL import Image
df = pd.read_csv(r"E:/safebelt/3train_rname.csv", header=None)
df_img_path = df[4]
df_img_mark = df[5]
# print(df_img_mark)
# 统计一下类别,并且重新生成原数据集标注文件,保存到json文件中
dict_class = {
"ground": 0,
"offground": 0,
"safebelt": 0,
# "badge": 0
}
dict_lable = {
"ground": 0,
"offground": 1,
"safebelt": 2,
# "badge": 0
}
data_dict_json = []
image_width, image_height = 0, 0
ids = 0
false = False # 将其中false字段转化为布尔值False
true = True # 将其中true字段转化为布尔值True
for img_id, one_img in enumerate(df_img_mark):
# print('img_id',img_id)
one_img = eval(one_img)["items"]
# print('one_img',one_img)
one_img_name = df_img_path[img_id]
# print(os.path.join("./", one_img_name))
img = Image.open(os.path.join(r"E:/safebelt", one_img_name))
ids = ids + 1
w, h = img.size
image_width += w
# print(image_width)
image_height += h
# print(one_img_name)
i=1
for one_mark in one_img:
# print('%d '%i,one_mark)
one_label = one_mark["labels"]['标签']
# print('%d '%i,one_label)
try:
dict_class[str(one_label)] += 1
# category = str(one_label)
category = dict_lable[str(one_label)]
# print('category:', category)
bbox = one_mark["meta"]["geometry"]
# print('bbox:', bbox)
except:
# dict_class["badge"] += 1 # 标签为"监护袖章(红only)"表示类别"badge"
# # category = "badge"
# category = 0
# bbox = one_mark["meta"]["geometry"]
continue
i += 1
one_dict = {}
one_dict["name"] = str(one_img_name)
one_dict["category"] = category
one_dict["bbox"] = bbox
data_dict_json.append(one_dict)
print(image_height / ids, image_width / ids)
print(dict_class)
print(len(data_dict_json))
print(data_dict_json[0])
with open(r"E:/safebelt/data-qudiao.json", 'w') as fp:
json.dump(data_dict_json, fp, indent=1, separators=(',', ': ')) # 缩进设置为1,元素之间用逗号隔开 , key和内容之间 用冒号隔开
fp.close()
2. json转txt
import json
import os
import cv2
file_name_list = {}
with open(r"E:/safebelt/data-qudiao.json", 'r', encoding='utf-8') as fr:
data_list = json.load(fr)
file_name = ''
label = 0
[x1, y1, x2, y2] = [0, 0, 0, 0]
for data_dict in data_list:
for k,v in data_dict.items():
if k == "category":
label = v
if k == "bbox":
[x1, y1, x2, y2] = v
if k == "name":
file_name = v[9:-4]
if not os.path.exists(r'E:/safebelt/data1'):
os.mkdir(r'E:/safebelt/data1')
print(r'E:/safebelt/3_images/' + file_name + '.jpg')
img = cv2.imread(r'E:/safebelt/3_images/' + file_name + '.jpg')
size = img.shape # (h, w, channel)
dh = 1. / size[0]
dw = 1. / size[1]
x = (x1 + x2) / 2.0
y = (y1 + y2) / 2.0
w = x2 - x1
h = y2 - y1
x = x * dw
w = w * dw
y = y * dh
h = h * dh
# print(size)
# cv2.imshow('image', img)
# cv2.waitKey(0)
content = str(label) + " " + str(x) + " " + str(y) + " " + str(w) + " " + str(h) + "\n"
if not content:
print(file_name)
with open(r'E:/safebelt/data1/' + file_name + '.txt', 'a+', encoding='utf-8') as fw:
fw.write(content)
3. xml转txt(根据存放图片的txt转)
# -*- coding: utf-8 -*-
# xml解析包
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 = ['fire', 'smoke']
# 进行归一化操作
def convert(size, box): # size:(原图w,原图h) , box:(xmin,xmax,ymin,ymax)
dw = 1./size[0] # 1/w
dh = 1./size[1] # 1/h
x = (box[0] + box[1])/2.0 # 物体在图中的中心点x坐标
y = (box[2] + box[3])/2.0 # 物体在图中的中心点y坐标
w = box[1] - box[0] # 物体实际像素宽度
h = box[3] - box[2] # 物体实际像素高度
x = x*dw # 物体中心点x的坐标比(相当于 x/原图w)
w = w*dw # 物体宽度的宽度比(相当于 w/原图w)
y = y*dh # 物体中心点y的坐标比(相当于 y/原图h)
h = h*dh # 物体宽度的宽度比(相当于 h/原图h)
return (x, y, w, h) # 返回 相对于原图的物体中心点的x坐标比,y坐标比,宽度比,高度比,取值范围[0-1]
# year ='2012', 对应图片的id(文件名)
def convert_annotation(image_id):
'''
将对应文件名的xml文件转化为label文件,xml文件包含了对应的bunding框以及图片长款大小等信息,
通过对其解析,然后进行归一化最终读到label文件中去,也就是说
一张图片文件对应一个xml文件,然后通过解析和归一化,能够将对应的信息保存到唯一一个label文件中去
labal文件中的格式:class x y w h 同时,一张图片对应的类别有多个,所以对应的bunding的信息也有多个
'''
# 对应的通过year 找到相应的文件夹,并且打开相应image_id的xml文件,其对应bund文件
in_file = open('/home/fire1026/Annotations/%s.xml' % (image_id), encoding='utf-8')
print(image_id)
# 准备在对应的image_id 中写入对应的label,分别为
#
out_file = open('/home/fire1026/labels/%s.txt' % (image_id), 'w', encoding='utf-8')
# 解析xml文件
tree = ET.parse(in_file)
# 获得对应的键值对
root = tree.getroot()
# 获得图片的尺寸大小
size = root.find('size')
# 如果xml内的标记为空,增加判断条件
if size != None:
# 获得宽
w = int(size.find('width').text)
# 获得高
h = int(size.find('height').text)
# 遍历目标obj
for obj in root.iter('object'):
# 获得difficult ??
difficult = obj.find('difficult').text
# 获得类别 =string 类型
cls = obj.find('name').text
# 如果类别不是对应在我们预定好的class文件中,或difficult==1则跳过
if cls not in classes or int(difficult) == 1:
continue
# 通过类别名称找到id
cls_id = classes.index(cls)
# 找到bndbox 对象
xmlbox = obj.find('bndbox')
# 获取对应的bndbox的数组 = ['xmin','xmax','ymin','ymax']
b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
float(xmlbox.find('ymax').text))
print(image_id, cls, b)
# 带入进行归一化操作
# w = 宽, h = 高, b= bndbox的数组 = ['xmin','xmax','ymin','ymax']
bb = convert((w, h), b)
# bb 对应的是归一化后的(x,y,w,h)
# 生成 calss x y w h 在label文件中
out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
# 返回当前工作目录
wd = getcwd()
print(wd)
for image_set in sets:
'''
对所有的文件数据集进行遍历
做了两个工作:
1.将所有图片文件都遍历一遍,并且将其所有的全路径都写在对应的txt文件中去,方便定位
2.同时对所有的图片文件进行解析和转化,将其对应的bundingbox 以及类别的信息全部解析写到label 文件中去
最后再通过直接读取文件,就能找到对应的label 信息
'''
# 先找labels文件夹如果不存在则创建
if not os.path.exists('/home/fire1026/labels/'):
os.makedirs('/home/fire1026/labels/')
# 读取在ImageSets/Main 中的train、test..等文件的内容
# 包含对应的文件名称
image_ids = open('/home/fire1026/ImageSets/%s.txt' % (image_set)).read().strip().split()
print(image_ids)
# 打开对应的2012_train.txt 文件对其进行写入准备
list_file = open('/home/fire1026/%s.txt' % (image_set), 'w')
# 将对应的文件_id以及全路径写进去并换行
for image_id in image_ids:
list_file.write('/home/fire1026/images/%s.jpg\n' % (image_id))
# 调用 year = 年份 image_id = 对应的文件名_id
convert_annotation(image_id)
# 关闭文件
list_file.close()
# print(image_ids)
# print(image_id)
# print()
4. xml转txt(根据图片文件夹转)
#coding=utf-8
import cv2
import xml.etree.ElementTree as ET
import os
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 read_cls_txt(filenam):
pos = []
clsfile = open(filenam)
rows = len(clsfile.readlines())
print("There are %d lines in %s" % (rows, filenam))
if (rows == 0):
print(filenam, ": there is no lines")
return pos
with open(filenam, 'r') as file_to_read:
while True:
lines = file_to_read.readline()
if not lines:
break
pass
print("line:", lines)
pos.append(lines.rstrip("\n"))
pass
print(filenam, pos)
return pos
def xml2yolotxt():
xml_path = r'D:\pythonProject\1028_fall\fire1026\train\Annotations'
obj_img_path = r'D:\pythonProject\1028_fall\fire1026\train\labels'
xml_path_list = []
obj_img_path_list = []
obj_img_path_loss_list = []
size_list = []
classes = read_cls_txt(r'D:/pythonProject/1028_fall/fire1026/classes.txt')
print("classes:", classes)
for xml_name in os.listdir(xml_path):
x_name = xml_name.split(".")[0]
print("xml_name:", xml_name)
xml_path_list.append(xml_name)
obj_img_path_list.append(obj_img_path)
root = ET.parse(xml_path +"/"+ xml_name).getroot()
size = root.find('size')
size_list.append(size)
w = int(size.find('width').text)
print('w:', w)
h = int(size.find('height').text)
print('h:', h)
with open(obj_img_path+"/"+x_name+""+".txt", "w") as out_file:
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:
print('转化失败的xml:', obj_img_path)
obj_img_path_loss_list.append(obj_img_path)
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')
#print(len(xml_path_list))
#print(len(obj_img_path_list))
#print(len(size_list))
#print(obj_img_path_loss_list)
#print(len(obj_img_path_loss_list))
xml2yolotxt()
7、UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xad in position 466: illegal multibyte sequence
出现这个问题场景是使用其他编辑器修改json或csv文件后,导致编码格式不能被yolov8识别, 可以使用notepad++,编码→转为UTF-8-BOM 编码 ,然后保存,格式就转回来了。