拓冰建站拓冰建站
首页 / 资讯中心 / 正文

不安装YOLO只安装 PyTorch,加载已有yolo数据,从无到有创建模型训练数据并加载使用(重要)

目录遗留问题:1、安装依赖2、训练脚本 train.py3、独立推理脚本 infer.py(完全独立,不需要数据集、不需要训练代码)关键知识点补充:导出 ONNX 代码(追加到 train.py 末尾)OpenCV‑C++ DNN 加载 detect.onnx 完整 Demo(VS2015)1. pro 工程配置要点(如果你用 Qt+VS2015)2. main.cpp 完整代码(复制直接编译)3. 非常关键的注意点(踩坑重点)4. 和之前整套链路完整回顾可参考课程如下课程未看完。仅仅看到18节课课程已看完,但没实操遗留问题:1.课程未看完。仅仅看到18节课2.课程已看完,但没实操注意:与本章节《PyTorch 完整流程:从零搭建模型 → 训练 → 保存权重 → 加载自定义模型推理(学习pytorch框架和YOLO笔记(重要)部分说明)》进行对比更加深入了解需求说明:不安装 ultralytics/yolo 库,但是使用 YOLO 标注格式的数据集(images 图片 + labels txt 标注),自己手写 PyTorch 检测网络,读取 yolo 格式数据集、训练、保存权重、独立脚本推理。环境:miniconda python3.8 + CPU 版 PyTorch,不引入 YOLO 任何包。YOLO 数据集格式:plaintextdataset/ ├─images/ │ ├─001.jpg │ └─002.jpg └─labels/ ├─001.txt # 格式:class_id x_center y_center w h (全部归一化0~1) └─002.txt1、安装依赖bashconda create -n torch_detect python=3.8 -y conda activate torch_detect # cpu pytorch pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu pip install opencv-python pillow2、训练脚本 train.py功能:自定义简易检测 CNN 网络(不是 YOLO,自己手写)读取YOLO 标注格式数据集(图片 + txt 标签)Dataset + DataLoader损失、优化器、训练循环保存 state_dict 权重(工程推荐方式)pythonimport os import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import Dataset, DataLoader import cv2 from PIL import Image import torchvision.transforms as T # -------------------------- 1.自定义简易检测网络 -------------------------- class SimpleDetectNet(nn.Module): def __init__(self, num_classes=2): super().__init__() # backbone卷积提取特征 self.conv1 = nn.Conv2d(3, 16, 3, padding=1) self.conv2 = nn.Conv2d(16, 32, 3, padding=1) self.conv3 = nn.Conv2d(32, 64, 3, padding=1) self.pool = nn.MaxPool2d(2,2) # 输出:简化设计,每张图输出 1个框 [x,y,w,h] + 类别概率 self.head = nn.Sequential( nn.Flatten(), nn.Linear(64*16*16, 256), nn.ReLU(), nn.Linear(256, 4 + num_classes) #4个框坐标 + num_classes类别 ) def forward(self, x): x = self.pool(torch.relu(self.conv1(x))) x = self.pool(torch.relu(self.conv2(x))) x = self.pool(torch.relu(self.conv3(x))) out = self.head(x) return out # -------------------------- 2.读取YOLO格式数据集 Dataset -------------------------- class YoloFormatDataset(Dataset): def __init__(self, root_dir, img_size=128, num_classes=2): self.root = root_dir self.img_dir = os.path.join(root_dir, "images") self.label_dir = os.path.join(root_dir, "labels") self.img_list = [f for f in os.listdir(self.img_dir) if f.endswith((".jpg",".png"))] self.img_size = img_size self.num_classes = num_classes self.transform = T.Compose([ T.Resize((img_size, img_size)), T.ToTensor(), #归一化0~1 ]) def __len__(self): return len(self.img_list) def __getitem__(self, index): img_name = self.img_list[index] img_path = os.path.join(self.img_dir, img_name) # 对应txt标签 txt_name = os.path.splite
分享:

看完干货,该让你的企业上线了

免费需求沟通 · 48 小时内出具建站方案 · 河南本地可上门