yolo11训练模型,我所遇到的一些报错问题
一、数据集格式转换,json文件批量转化为yolo的txt文件格式
1、在使用程序进行格式转换后的txt文件中出现负数的情况
我在网上搜罗了一堆关于格式转换的代码,换了换文件路径开始转换,也没有检查到底转换后的文件是否存在问题,就直接用来训练模型了,然后就开始出现警告:Scanning C:\Users\Administrator\Desktop\dataset\yolo11\labels\train... 307 images, 0 backgrounds, 161 corrupt: 100%|██████████| 307/307 [00:00<00:00, 3891.78it/s]和WARNING ⚠️ C:\Users\Administrator\Desktop\dataset\yolo11\images\train\192.168.1.10_01_20230310164723455.JPEG: ignoring corrupt image/label: negative label values [ -0.018229 -0.049134 -0.02193 -0.031676],显示我一共307个文件其中161个文件有问题,训练时就少了161个数据,就是格式转换后坐标出现了负数。
Scanning C:\Users\Administrator\Desktop\dataset\yolo11\labels\train... 307 images, 0 backgrounds, 161 corrupt: 100%|██████████| 307/307 [00:00<00:00, 3891.78it/s]
WARNING ⚠️ C:\Users\Administrator\Desktop\dataset\yolo11\images\train\192.168.1.10_01_20230310164723455.JPEG: ignoring corrupt image/label: negative label values [ -0.018229 -0.049134 -0.02193 -0.031676]
解决办法:使用abs函数强制转换

2、转换后数据丢失
我一共386个文件,转换后却只有384文件,尝试各种代码死活找不出来,后来找个笨办法将txt文件复制到json文件中,找那个json文件没有txt文件,找到之后我又仔细在labelme中一看,发现214433和220140两个文件,名不一样但是里面的图片和标注都一模一样。在转换的时候把这个文件跳过去了。

Found 386 JSON files to convert.
Successfully converted 386 files. YOLO files generated: 384
解决办法:删除文件或者重新标注。
最后附上批量转换代码
import os
import json
def convert_to_yolo(json_file, output_dir, missing_files):
"""
将单个 JSON 文件转换为 YOLO 格式
"""
try:
with open(json_file, 'r', encoding='utf-8') as f:
data = json.load(f)
# 检查 shapes 是否存在且有效
if 'shapes' not in data or not data['shapes']:
print(f"Warning: No shapes found in {json_file}")
missing_files.append(json_file)
return # 跳过无效的 JSON 文件
shapes = data['shapes']
image_path = data.get('imagePath', '')
image_width = 1280 # 假设图像宽度(需根据实际情况修改)
image_height = 720 # 假设图像高度(需根据实际情况修改)
# 生成输出文件名
base_filename = os.path.basename(image_path) if image_path else os.path.splitext(os.path.basename(json_file))[0]
base_filename = os.path.splitext(base_filename)[0] # 去掉扩展名
yolo_file = os.path.join(output_dir, f"{base_filename}.txt")
with open(yolo_file, 'w') as out_file:
has_valid_data = False # 标记文件中是否写入了有效内容
for shape in shapes:
if 'points' not in shape or len(shape['points']) != 2:
print(f"Warning: Invalid shape data in {json_file}")
continue # 跳过无效的 shape
# 提取坐标
points = shape['points']
xmin = points[0][0]
ymin = points[0][1]
xmax = points[1][0]
ymax = points[1][1]
# 归一化坐标
x_center = abs((xmin + xmax) / 2.0 / image_width)
y_center = abs((ymin + ymax) / 2.0 / image_height)
width = abs((xmax - xmin) / image_width)
height = abs((ymax - ymin) / image_height)
# 写入 YOLO 格式:<class_id> <x_center> <y_center> <width> <height>
class_id = 0 # 假设类别为 0
out_file.write(f"{class_id} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}\n")
has_valid_data = True # 确认写入了内容
# 如果文件为空,则删除并记录为失败文件
if not has_valid_data:
print(f"Warning: No valid data written to {yolo_file}")
if os.path.exists(yolo_file):
os.remove(yolo_file) # 删除空文件
missing_files.append(json_file)
except Exception as e:
print(f"Error processing {json_file}: {e}")
missing_files.append(json_file)
def batch_convert(input_dir, output_dir):
"""
批量处理目录中的所有 JSON 文件,并打印未生成输出文件的文件列表
"""
if not os.path.exists(output_dir):
os.makedirs(output_dir)
json_files = [f for f in os.listdir(input_dir) if f.lower().endswith('.json')]
print(f"Found {len(json_files)} JSON files to convert.")
missing_files = [] # 用于记录未成功生成的文件
converted_count = 0
for filename in json_files:
json_file = os.path.join(input_dir, filename)
convert_to_yolo(json_file, output_dir, missing_files)
if json_file not in missing_files:
converted_count += 1
# 验证生成的文件数量
txt_files = [f for f in os.listdir(output_dir) if f.endswith('.txt')]
print(f"Successfully converted {converted_count} files. YOLO files generated: {len(txt_files)}")
# 打印未生成输出文件的 JSON 文件列表
if missing_files:
print("\nThe following files did not generate YOLO output:")
for file in missing_files:
print(file)
else:
print("\nAll files converted successfully!")
if __name__ == "__main__":
input_directory = "C:\\Users\\Administrator\\Desktop\\dataset\\label-json" # 输入 JSON 文件夹路径
output_directory = "C:\\Users\\Administrator\\Desktop\\dataset\\label-yolo1" # 输出 YOLO 文件夹路径
batch_convert(input_directory, output_directory)
二、跑代码报错
1、ValueError: not enough values to unpack (expected 3, got 0)和RuntimeError: torch.cat(): expected a non-empty list of Tensors
在跑程序的过程中各种,出现ValueError: not enough values to unpack (expected 3, got 0)报错。我最开始在数据集划分的时候同时生成了三个train.txt、val.txt和test.txt文件用于记录我的训练集、测试集和验证集图片的路径,在新建data.yaml文件时就写这三个文件的路径,就可以训练。txt文件内容如下

解决方法:
当时我的图片和标签的文件名称分别是image和label,而不是标准的images和labels。我运行之后就报错RuntimeError: torch.cat(): expected a non-empty list of Tensors。为了解决这个问题,我首先把文件名改为images和labels,没改data.yaml文件里的路径,没有用,换了一个报错ValueError: not enough values to unpack (expected 3, got 0)。后来我重新建了一个数据目录并且直接不用这三个train.txt、val.txt和test.txt文件而是直接附上我图片的绝对地址,work!

2、OSError: [WinError 1455] 页面文件太小,无法完成操作
在修改完我上面所提到的报错之后,程序运行了,但只运行了90%,然后报错OSError: [WinError 1455] 页面文件太小,无法完成操作。
解决办法:
调小batch和workes

仅在此记录一下我的学习过程。
更多推荐

所有评论(0)