深度学习目标检测rt-detr-18环境配置
本文介绍了在RTX4090显卡(CUDA11.8)环境下配置RT-DETR目标检测模型的完整流程。首先基于Miniconda创建Python3.10的纯净环境,然后分步骤安装PyTorch2.1.2、NumPy和OpenCV等核心依赖项,特别注意版本兼容性问题。针对VisDrone数据集,提供了详细的格式转换脚本,将原始标注转换为YOLO格式,并给出数据集目录结构的配置方法。最后通过修改visdr
1.基础环境
镜像:Miniconda conda3,Python 3.10(ubuntu22.04),CUDA 11.8
显卡:RTX4090
2.代码与环境准备(地基)
上传代码
cd /root/autodl-tmp/
unzip my-first-project.zip
git clone 代码地址
3. 创建纯净环境
使用 Python 3.10(项目推荐版本)
source /etc/network_turbo # 开启加速
conda remove -n rtdetr --all -y # 删除旧环境(如果有)
conda create -n rtdetr python=3.10 -y
conda activate rtdetr
4.依赖安装(核心避坑区)
这是之前最容易出错的地方,请按顺序复制执行。
4.1. 安装 PyTorch (锁定 CUDA 11.8)
理由: 你的机器是 11.8,必须装适配版本,否则 Mamba 无法编译。
pip install torch==2.1.2 torchvision==0.16.2 torchaudio==2.1.2 --index-url https://download.pytorch.org/whl/cu118
4.2. 锁定 NumPy 和 OpenCV (防止冲突)
理由: 解决 Failed to initialize NumPy 和 OpenCV 版本报错。
pip install "numpy<2.0" "opencv-python<4.10.0" "opencv-python-headless<4.10.0"
4.3. 安装 MMCV (使用官方直链)
理由: 解决下载慢的问题。链接适配 Torch 2.1.x + CUDA 11.8。
pip install "https://download.openmmlab.com/mmcv/dist/cu118/torch2.1.0/mmcv-2.2.0-cp310-cp310-manylinux1_x86_64.whl"
4.4. 安装项目基础依赖
理由: 补全项目运行所需的常规包。
pip install -r requirements.txt
pip install timm==1.0.7 thop efficientnet_pytorch==0.7.1 einops grad-cam==1.5.4 dill==0.3.8 albumentations==1.4.11 pytorch_wavelets==1.3.0 tidecv PyWavelets prettytable ninja packaging
4.5. 修改源代码
数据集的位置,数据集的格式转换
格式转换代码
import os
from pathlib import Path
from PIL import Image
from tqdm import tqdm
def convert_visdrone_to_yolo(visdrone_raw_path, project_dataset_path):
# VisDrone原始类别(1-10) → YOLO类别(0-9)
class_map = {1: 0, 2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 7: 6, 8: 7, 9: 8, 10: 9}
valid_categories = set(class_map.keys()) # 有效类别:1-10
for split in ['train', 'val']:
# 自动适配解压路径
split_root = Path(visdrone_raw_path) / split
src_split_dirs = [d for d in split_root.glob('*') if d.is_dir()]
if not src_split_dirs:
print(f"错误:{split} 目录下未找到解压文件夹!")
continue
src_split_dir = src_split_dirs[0]
img_src_dir = src_split_dir / 'images'
label_src_dir = src_split_dir / 'annotations'
# 目标路径
save_img_dir = Path(project_dataset_path) / 'images' / split
save_label_dir = Path(project_dataset_path) / 'labels' / split
save_img_dir.mkdir(parents=True, exist_ok=True)
save_label_dir.mkdir(parents=True, exist_ok=True)
print(f"\n处理 {split} 集:")
print(f" 图片路径:{img_src_dir}")
print(f" 标注路径:{label_src_dir}")
label_files = list(label_src_dir.glob('*.txt'))
print(f" 找到 {len(label_files)} 个标注文件")
valid_count = 0
for label_file in tqdm(label_files, desc=f"转换进度"):
img_file = img_src_dir / (label_file.stem + '.jpg')
if not img_file.exists():
continue
# 获取图片宽高
try:
with Image.open(img_file) as img:
w_img, h_img = img.size
except:
continue
yolo_lines = []
with open(label_file, 'r', encoding='utf-8', errors='ignore') as f:
for line_idx, line in enumerate(f):
line = line.strip()
if not line:
continue
data = line.split(',')
if len(data) < 8:
continue
# 强制处理类别(容错处理,避免编码错误)
try:
category = int(data[5].strip()) # 去除空格,防止隐性错误
except:
continue # 类别无法转换为数字则跳过
# 只过滤 0(忽略)和 11(其他),其余 1-10 强制保留
if category not in valid_categories:
continue
# 转换坐标
try:
x1, y1, w, h = map(float, [d.strip() for d in data[:4]])
except:
continue # 坐标错误则跳过
# YOLO 格式转换
x_center = (x1 + w/2) / w_img
y_center = (y1 + h/2) / h_img
w_norm = w / w_img
h_norm = h / h_img
# 边界修正
x_center = max(0.001, min(0.999, x_center))
y_center = max(0.001, min(0.999, y_center))
w_norm = max(0.001, min(0.999, w_norm))
h_norm = max(0.001, min(0.999, h_norm))
yolo_lines.append(f"{class_map[category]} {x_center:.6f} {y_center:.6f} {w_norm:.6f} {h_norm:.6f}\n")
# 保存有效标注和图片链接
if yolo_lines:
valid_count += 1
# 保存标注
with open(save_label_dir / label_file.name, 'w', encoding='utf-8') as f:
f.writelines(yolo_lines)
# 创建图片软链接
link_path = save_img_dir / img_file.name
if not link_path.exists():
os.symlink(img_file, link_path)
print(f" 有效转换文件数:{valid_count}")
if __name__ == '__main__':
RAW_DATA_PATH = '/root/autodl-tmp/VisDrone2019'
PROJECT_DATASET_PATH = '/root/autodl-tmp/my-first-project/dataset'
convert_visdrone_to_yolo(RAW_DATA_PATH, PROJECT_DATASET_PATH)
print("\n✅ 转换完成!")
5.数据准备
5.1. 准备 VisDrone 数据集
将 VisDrone2019-DET-train.zip 和 VisDrone2019-DET-val.zip 上传到虚拟环境中。
解压:
mkdir -p dataset/VisDrone2019/train dataset/VisDrone2019/val
unzip -q /root/autodl-tmp/VisDrone2019-DET-train.zip -d dataset/VisDrone2019/train
unzip -q /root/autodl-tmp/VisDrone2019-DET-val.zip -d dataset/VisDrone2019/val
5.2. 转换标签 (YOLO格式)
确保你使用了项目中的转换脚本将 VisDrone 的标注转换为 txt 格式,并放在对应的 labels 文件夹下,代码前面已经给出。
5.3. 配置文件 dataset/visdrone.yaml
# 文件名:dataset/visdrone.yaml
# 1. 修改为你的 AutoDL 绝对路径 (根据你代码所在位置)
path: /root/autodl-tmp/my-first-project/dataset # 指向包含 images 和 labels 的上一级目录
# 2. 训练和验证集的相对路径
train: images/train
val: images/val
test: images/test
# 3. 修改为 VisDrone 的 10 个类别 (必须对齐!)
nc: 10
names:
0: pedestrian
1: people
2: bicycle
3: car
4: van
5: truck
6: tricycle
7: awning-tricycle
8: bus
9: motor
第四阶段:训练代码
实验 1:Baseline (原始 RT-DETR-R18)
python train.py
更多推荐
所有评论(0)