yolo 训练 动态改变类别
目录
update_cls.py
训练调用:
update_cls.py
import re
import yamldef yaml_to_uitls(file_path, yaml_path, output_file_path=None):# 读取YAML文件获取类别名称with open(yaml_path, 'r', encoding='utf-8') as f:yaml_data = yaml.safe_load(f)# 获取类别名称列表if 'names' in yaml_data:class_names = yaml_data['names']else:raise ValueError("YAML文件中未找到 'names' 字段")# 生成新的_class_to_ind字典new_dict = {}for idx, name in enumerate(class_names):new_dict[name] = idx# 构建新的代码行new_line = f'_class_to_ind = {new_dict}'# 读取Python文件with open(file_path, 'r', encoding='utf-8') as f:content = f.read()# 使用正则表达式替换_class_to_ind定义# 匹配各种可能的格式:_class_to_ind = {...}pattern = r'_class_to_ind\s*=\s*\{[^}]+\}'# 检查是否找到匹配if re.search(pattern, content):# 替换匹配的内容new_content = re.sub(pattern, new_line, content)# 写入文件output_path = output_file_path if output_file_path else file_pathwith open(output_path, 'w', encoding='utf-8') as f:f.write(new_content)print(f"成功更新 {file_path}")print(f"新的 _class_to_ind: {new_line}")return Trueelse:print(f"在 {file_path} 中未找到 _class_to_ind 定义")return Falsedef class_to_utils(file_path, class_names, output_file_path=None):"""根据类别名称列表更新Python文件中的_class_to_ind定义Args:file_path (str): 要修改的Python文件路径class_names (list): 类别名称列表output_file_path (str, optional): 输出文件路径,如果为None则覆盖原文件"""# 生成新的_class_to_ind字典new_dict = {}for idx, name in enumerate(class_names):new_dict[name] = idx# 构建新的代码行new_line = f'_class_to_ind = {new_dict}'# 读取Python文件with open(file_path, 'r', encoding='utf-8') as f:content = f.read()# 使用正则表达式替换_class_to_ind定义pattern = r'_class_to_ind\s*=\s*\{[^}]+\}'# 检查是否找到匹配if re.search(pattern, content):# 替换匹配的内容new_content = re.sub(pattern, new_line, content)# 写入文件output_path = output_file_path if output_file_path else file_pathwith open(output_path, 'w', encoding='utf-8') as f:f.write(new_content)print(f"成功更新 {file_path}")print(f"新的 _class_to_ind: {new_line}")return Trueelse:print(f"在 {file_path} 中未找到 _class_to_ind 定义")return Falseif __name__ == "__main__":# 方法1: 从YAML文件更新python_file = r"ultralytics/data/utils.py"# yaml_file = "data_jw.yaml" # 替换为实际的YAML文件路径yaml_file = "data_chan.yaml" # 替换为实际的YAML文件路径try:yaml_to_uitls(python_file, yaml_file)except Exception as e:print(f"更新失败: {e}")if 0:class_names = ['chan', 'penzi', 'zhi']class_to_utils(python_file, class_names)
训练调用:
import os
from multiprocessing import freeze_supportfrom update_cls import yaml_to_uitlsos.chdir(os.path.dirname(os.path.abspath(__file__)))
from ultralytics import YOLO
if __name__ == '__main__':freeze_support()model = YOLO('yolov12s.pt')util_path = r"ultralytics/data/utils.py"yaml_path = 'data_hand.yaml'yaml_to_uitls(util_path, yaml_path)results = model.train(data=yaml_path,epochs=150,batch=8,imgsz=(640,352),scale=0.9, # S:0.9; M:0.9; L:0.9; X:0.9mosaic=0.5,mixup=0.15, # S:0.05; M:0.15; L:0.15; X:0.2copy_paste=0.1, # S:0.15; M:0.4; L:0.5; X:0.6device="0",optimizer='AdamW')
