当前位置: 首页 > news >正文

yolov26模型训练(使用yolov5样本训练)

1、样本转换

原始文件路径为

/dataSharing/otherTrain/dataset/yolo26_data/
Annotations/ # xml
images/ # jpg

第 0 步:确认你的数据是否一一对应

cd /dataSharing/otherTrain/dataset/yolo26_data # 看看有多少图片/标注 ls images | wc -l ls Annotations | wc -l # 随机抽几个看看是否同名 python3 - << 'PY' import os, random imgs = [f for f in os.listdir("images") if f.lower().endswith((".jpg",".jpeg",".png"))] xmls = set([os.path.splitext(f)[0] for f in os.listdir("Annotations") if f.lower().endswith(".xml")]) sample = random.sample(imgs, min(20, len(imgs))) bad = [f for f in sample if os.path.splitext(f)[0] not in xmls] print("sample missing xml:", bad) PY

如果sample missing xml为空,说明基本OK。

第 1 步:把 VOC(xml) 转 YOLO,并自动划分 train/val

/dataSharing/otherTrain/dataset/yolo26_data下新建脚本:

cd /dataSharing/otherTrain/dataset/yolo26_data nano voc_to_yolo_split.py

把下面代码粘进去(可直接用):

import os, random, shutil import xml.etree.ElementTree as ET from pathlib import Path ROOT = Path("/dataSharing/otherTrain/dataset/yolo26_data") IMG_DIR = ROOT / "images" ANN_DIR = ROOT / "Annotations" OUT_IMG_TRAIN = ROOT / "images" / "train" OUT_IMG_VAL = ROOT / "images" / "val" OUT_LBL_TRAIN = ROOT / "labels" / "train" OUT_LBL_VAL = ROOT / "labels" / "val" VAL_RATIO = 0.2 SEED = 42 def parse_xml(xml_path: Path): tree = ET.parse(xml_path) root = tree.getroot() size = root.find("size") if size is None: raise ValueError(f"{xml_path} missing <size>") w = int(size.findtext("width")) h = int(size.findtext("height")) objs = [] for obj in root.findall("object"): name = obj.findtext("name") if not name: continue difficult = obj.findtext("difficult") if difficult and difficult.strip() == "1": continue bnd = obj.find("bndbox") if bnd is None: continue xmin = float(bnd.findtext("xmin")) ymin = float(bnd.findtext("ymin")) xmax = float(bnd.findtext("xmax")) ymax = float(bnd.findtext("ymax")) xmin = max(0.0, xmin) ymin = max(0.0, ymin) xmax = min(float(w), xmax) ymax = min(float(h), ymax) if xmax <= xmin or ymax <= ymin: continue objs.append((name, xmin, ymin, xmax, ymax)) return w, h, objs def voc_to_yolo(w, h, xmin, ymin, xmax, ymax): xc = (xmin + xmax) / 2.0 / w yc = (ymin + ymax) / 2.0 / h bw = (xmax - xmin) / w bh = (ymax - ymin) / h return xc, yc, bw, bh def main(): assert IMG_DIR.exists(), IMG_DIR assert ANN_DIR.exists(), ANN_DIR # 收集图片 imgs = [p for p in IMG_DIR.iterdir() if p.suffix.lower() in [".jpg",".jpeg",".png"] and p.is_file()] # 排除已经分出来的 train/val 目录 imgs = [p for p in imgs if p.parent == IMG_DIR] if not imgs: raise RuntimeError(f"No images found in {IMG_DIR}") # 收集类别(扫一遍 xml) classes = set() missing_xml = 0 for img in imgs: xml = ANN_DIR / (img.stem + ".xml") if not xml.exists(): missing_xml += 1 continue _, _, objs = parse_xml(xml) for name, *_ in objs: classes.add(name) classes = sorted(list(classes)) if not classes: raise RuntimeError("No classes parsed from XML. Check your xml format.") class2id = {c:i for i,c in enumerate(classes)} # 写 classes.txt (ROOT / "classes.txt").write_text("\n".join(classes), encoding="utf-8") # 划分 train/val random.seed(SEED) random.shuffle(imgs) n_val = int(len(imgs) * VAL_RATIO) val_imgs = imgs[:n_val] train_imgs = imgs[n_val:] # 创建输出目录 for p in [OUT_IMG_TRAIN, OUT_IMG_VAL, OUT_LBL_TRAIN, OUT_LBL_VAL]: p.mkdir(parents=True, exist_ok=True) def write_one(img_path: Path, out_img_dir: Path, out_lbl_dir: Path): xml_path = ANN_DIR / (img_path.stem + ".xml") if not xml_path.exists(): return False, "missing_xml" w, h, objs = parse_xml(xml_path) lines = [] for name, xmin, ymin, xmax, ymax in objs: cid = class2id[name] xc, yc, bw, bh = voc_to_yolo(w, h, xmin, ymin, xmax, ymax) # 保险:限制在0~1 xc = min(max(xc, 0.0), 1.0) yc = min(max(yc, 0.0), 1.0) bw = min(max(bw, 0.0), 1.0) bh = min(max(bh, 0.0), 1.0) lines.append(f"{cid} {xc:.6f} {yc:.6f} {bw:.6f} {bh:.6f}") # 没有目标也要写空txt(YOLO允许) (out_lbl_dir / f"{img_path.stem}.txt").write_text("\n".join(lines), encoding="utf-8") # 复制图片(也可以改成移动:shutil.move) shutil.copy2(img_path, out_img_dir / img_path.name) return True, "ok" stats = {"ok":0, "missing_xml":0} for img in train_imgs: ok, reason = write_one(img, OUT_IMG_TRAIN, OUT_LBL_TRAIN) stats[reason] = stats.get(reason, 0) + (0 if ok else 1) if ok: stats["ok"] += 1 for img in val_imgs: ok, reason = write_one(img, OUT_IMG_VAL, OUT_LBL_VAL) stats[reason] = stats.get(reason, 0) + (0 if ok else 1) if ok: stats["ok"] += 1 # 生成 data.yaml(Ultralytics/YOLO系列通用) data_yaml = f"""path: {ROOT} train: images/train val: images/val names: """ for i, c in enumerate(classes): data_yaml += f" {i}: {c}\n" (ROOT / "data.yaml").write_text(data_yaml, encoding="utf-8") print("Done.") print("Classes:", classes) print("Stats:", stats) print("Generated:", ROOT/"data.yaml", ROOT/"classes.txt") if __name__ == "__main__": main()

保存退出后执行:

python3 voc_to_yolo_split.py

执行完成后,你会得到:

  • labels/train/*.txt

  • labels/val/*.txt

  • images/train/*.jpg

  • images/val/*.jpg

  • data.yaml

  • classes.txt

你的原始images/*.jpg不会被删(脚本是 copy2)。如果你想节省空间我可以使用“移动版”。

第 2 步:快速检查转换结果是否正确

cd /dataSharing/otherTrain/dataset/yolo26_data # 统计数量 find images/train -type f | wc -l find labels/train -type f | wc -l find images/val -type f | wc -l find labels/val -type f | wc -l # 随机看一个标注文件 ls labels/train | head head -n 5 labels/train/$(ls labels/train | shuf -n 1)

如果images/trainlabels/train数量一致,基本没问题。

第 3 步:新建一个虚拟环境训练 YOLOv26(Ultralytics 方式)

第 3-1 步:创建 YOLOv26 专用 conda 环境

进入你想放环境的目录(随便,比如放在项目目录旁边):

conda create -n yolo26 python=3.10 -y

第 3-2 步:激活虚拟环境

conda activate yolo26

激活成功后,你会看到前缀:

(yolo26) root@xxx:#

第 3-3 步:安装 PyTorch(最关键一步):

在 yolo26 环境中执行:

pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121

安装完马上验证

python - << 'PY' import torch print(torch.__version__) print("CUDA:", torch.cuda.is_available()) print("GPU:", torch.cuda.get_device_name(0)) PY

必须看到:

CUDA: True

第 3-4 步:安装 Ultralytics(清华源)

pip install ultralytics -i https://pypi.tuna.tsinghua.edu.cn/simple --default-timeout=1000

验证:

yolo version

第 3-4步:开始训练

yolo26x.pt下载地址

https://huggingface.co/Ultralytics/YOLO26?utm_source=chatgpt.com

yolo26n.pt下载地址

https://github.com/ultralytics/assets/releases/download/v8.4.0/yolo26n.pt

yolo detect train \ model=./yolo26x.pt \ data=./data.yaml \ imgsz=640 \ epochs=200 \ batch=10 \ device=3 \ workers=8 \ amp=True \ cos_lr=True \ close_mosaic=10 \ project=/dataSharing/otherTrain/yolo26_runs \ name=yolo26x_640

3-5 验证(最直观:拿你真实业务视频/图片做推理,看框对不对)

nohup yolo detect train \ model=/data/dataSharing/otherTrain/dataset/yolo26_data/yunnan/yolo26x.pt \ data=/data/dataSharing/otherTrain/dataset/yolo26_data/yunnan/data.yaml \ imgsz=640 \ epochs=100 \ batch=8 \ device=1 \ workers=16 \ amp=True \ cos_lr=True \ close_mosaic=10 \ project=/data/dataSharing/otherTrain/yolo26_runs \ name=yolo26x_640_yunnan_20260430 &

输出会在:

ls /dataSharing/otherTrain/yolo26_runs/exp01_pred_vid
http://www.jsqmd.com/news/732304/

相关文章:

  • 五分钟 带你认识 AI 时代的 nodejs 与 包管理工具
  • WzComparerR2完整指南:解密冒险岛WZ文件的终极工具
  • 从电路到代码:零极点分析如何帮你避开运放振荡、设计出更稳的滤波器?
  • RTAB-Map完整指南:如何用开源SLAM技术解决机器人导航难题
  • 终极Windows依赖库管理指南:如何一键解决所有Visual C++运行库问题
  • 如何高效使用Uni-Mol:药物研发的终极3D分子分析指南
  • 把 SAP Cryptographic Library 放对地方,SECUDIR 配对位置,SNC 才不会在运行时掉链子
  • 【flutter for open harmony】第三方库Flutter 鸿蒙版 优惠券展示 实战指南(适配 1.0.0)✨
  • 从JDK8到JDK17:Atomic与LongAdder的演进与最佳实践避坑指南
  • 别再到处找驱动了!STM32CubeMX安装后,CH340和ST-LINK驱动一键搞定指南
  • MuJoCo接触力学终极指南:从滑动问题到稳定仿真的完整解决方案
  • Phi-3-Mini-128K企业实操:将内部SOP文档注入对话系统实现零样本流程咨询
  • PWM触发ADC采样?深入浅出解析汽车ECU中硬件触发的ADC应用与优化技巧
  • VisualCppRedist AIO:告别DLL地狱,一站式解决VC++运行库依赖难题
  • Python量化回测框架Backtrader:从事件驱动到双均线策略实战
  • 全国淘宝村 DID 面板数据(2008-2024)|数字乡村 / 乡村振兴顶刊标配
  • 别再只盯着支持度了!用Python实战Apriori算法,手把手教你挖掘超市购物篮里的‘啤酒与尿布’
  • nRF52832低功耗按键设计详解:用GPIOTE PORT事件替代传统中断,功耗直降90%
  • Win11实时字幕的‘外挂’玩法:教你用C#抓取字幕文本并推送到浏览器插件
  • GD32F470双ADC(ADC0+ADC2)同步DMA采集配置指南:实现无中断轮询读取数据
  • NTU VIRAL多传感器融合SLAM系统完整实现指南:从架构设计到算法优化
  • 借助 Taotoken 多模型聚合能力为智能客服场景选择最佳模型
  • 亨得利官方声明公告|2026年5月雅典帕玛强尼表主正规服务点清单 附地址清单与避坑建议 - 时光修表匠
  • 基于AFSIM的无人机集群协同侦察打击一体化作战系统:最小化完整案例
  • 海棠山铁哥孤身对抗资本《灵魂摆渡・浮生梦》,《第一大道》撑起普通人奋斗希望
  • ComfyUI-Manager:3大核心功能彻底解决AI绘画插件管理难题
  • VLA模型鲁棒性测试:多模态协同与工业实践
  • Taotoken模型广场如何帮助开发者根据任务与预算选择合适模型
  • 如何在Windows 11上免费运行Android应用:Windows Subsystem for Android终极指南
  • Qwen3-4B-Instruct保姆级教程:从零部署到生产环境健康检查清单