第0步

了解自己显卡所需要的算力

https://en.wikipedia.org/wiki/CUDA

在这基础上往上滑会看到算力对应能装的cuda版本

查看自己显卡所允许最高的cuda版本

win+r-->输入cmd进入终端-->nvidia-smi

查看cuda所对应的pytorch,也要注意python版本

pytorch/RELEASE.md at main · pytorch/pytorch · GitHub

以上东西详细在这位博主的帖子

在anaconda中安装cuda-pytorch_anaconda安装cuda-CSDN博客

现在anaconda外部,即终端下载cuda13.0.2

CUDA Toolkit 13.2 Downloads | NVIDIA Developer


第1步        创建环境

conda create -n ostrack python=3.9

conda activate ostrack


第2步        改install.sh

echo "****************** Installing pytorch ******************" conda install pytorch==1.9.0 torchvision==0.10.0 torchaudio==0.9.0 cudatoolkit=10.2 -c pytorch echo "" echo ""

改成

echo "****************** Installing pytorch ******************" pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu128 echo "" echo ""

删掉:

echo "****************** Downgrade setuptools ******************" pip install setuptools==59.5.0 echo "" echo ""

echo "****************** Installing visdom ******************" pip install visdom echo "" echo ""

echo "****************** Installing thop tool for FLOPs and Params computing ******************" pip install thop-0.0.31.post2005241907 echo "" echo ""

终端输入

conda install m2-base

bash.install.sh

第3步        改代码

下载(忘记需不需要了)

pip install setuptools==63.2.0

卸载(这个是为了下一步检查)

pip uninstall -y tikzplotlib

检查

python -c "import torch; import torchvision; import torchaudio; import yaml; import easydict; import cv2; import pandas; import tqdm; import pycocotools; import jpeg4py; import tensorboard; import thop; import lmdb; import scipy; import tensorboardX; import wandb; import timm; print('✅ 所有核心成功!'); print('🔥 Torch 版本:', torch.__version__); print('🔥 GPU 可用:', torch.cuda.is_available()); print('🔥 显卡:', torch.cuda.get_device_name(0))"

正常应输出

✅ 所有核心库安装成功!

🔥 Torch 版本: 2.8.0+cu128

🔥 GPU 可用: True

🔥 显卡: NVIDIA GeForce RTX 5060 Laptop GPU (ostrack02) PS D:\Program\test11\OSTrack-main>

改代码

打开OSTrack-main\lib\train\data\loader.py

注释from torch._six import string_classes

在同一位置加入string_classes = (str, bytes)

打开OSTrack-main\lib\test\evaluation\local.py

from test.evaluation.environment import EnvSettings

替换成

from lib.test.evaluation.environment import EnvSettings

打开OSTrack-main\lib\vis\visdom_cus.py

注释import visdom import visdom.server这俩行

这里省略把权重放到相应位置、数据集放入,修改local文件和数据集文件

输入命令

python tracking/test.py ostrack vitb_384_mae_ce_32x4_ep300 --dataset lasot --threads 4 --num_gpus 1

就能跑了

第4步        生成跟踪结果视频+画框

把其中一个序列的跟踪结果画成视频 + 画框,生成 MP4

将下面代码写入一个py文件,放在根目录下面,直接运行

import os
import cv2
import numpy as np

# ====================== 已经帮你全部改正确 ======================
DATASET_ROOT = "D:/Program/test11/OSTrack-main/data/lasot/electricfan"
RESULT_ROOT = "D:/Program/test11/OSTrack-main/output/test/tracking_results/ostrack/vitb_384_mae_ce_32x4_ep300/lasot"
SEQUENCE_NAME = "electricfan-1"
SAVE_VIDEO_PATH = f"{SEQUENCE_NAME}_tracking_result.mp4"
# =================================================================

# 读取跟踪结果 txt
def load_results(txt_path):
    with open(txt_path, 'r') as f:
        lines = f.readlines()
    bboxes = []
    for line in lines:
        line = line.strip().replace(',', ' ')
        coords = list(map(float, line.split()))
        x1, y1, w, h = coords[:4]
        bboxes.append([int(x1), int(y1), int(w), int(h)])
    return bboxes

# 读取图片列表
def get_image_paths(seq_path):
    img_dir = os.path.join(seq_path, "img")
    img_names = sorted(os.listdir(img_dir))
    return [os.path.join(img_dir, n) for n in img_names]

# 画框 + 生成视频
def visualize():
    seq_path = os.path.join(DATASET_ROOT, SEQUENCE_NAME)
    txt_path = os.path.join(RESULT_ROOT, f"{SEQUENCE_NAME}.txt")

    if not os.path.exists(txt_path):
        print(f"错误:找不到结果文件 {txt_path}")
        return

    bboxes = load_results(txt_path)
    img_paths = get_image_paths(seq_path)

    # 视频设置
    first_img = cv2.imread(img_paths[0])
    h, w = first_img.shape[:2]
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter(SAVE_VIDEO_PATH, fourcc, 30, (w, h))

    print(f"正在生成视频:{SAVE_VIDEO_PATH}")

    for i, img_path in enumerate(img_paths):
        img = cv2.imread(img_path)
        if i >= len(bboxes):
            break

        x1, y1, w, h = bboxes[i]
        x2 = x1 + w
        y2 = y1 + h

        # 画跟踪框
        cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 3)
        cv2.putText(img, f"Frame: {i+1}", (20, 40),
                    cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 255, 0), 3)

        out.write(img)

    out.release()
    print(f"✅ 视频已保存到:{SAVE_VIDEO_PATH}")

if __name__ == "__main__":
    visualize()

第5步        生成auc

要进行修改后同第4步放在根目录下

import os
import numpy as np

# ===================== 【完全按你的真实路径填写】 =====================
# 你的预测结果路径
RESULT_DIR = r"D:\Program\test11\OSTrack-main\output\test\tracking_results\ostrack\vitb_384_mae_ce_32x4_ep300\lasot"
# 你的数据集真实标签路径(完全匹配你给的路径)
DATASET_ROOT = r"D:\Program\test11\OSTrack-main\data\lasot"
# ====================================================================

# 读取真实框 GT
def load_gt(seq_name):
    class_name = seq_name.split('-')[0]
    gt_path = os.path.join(DATASET_ROOT, class_name, seq_name, "groundtruth.txt")
    gt = []
    with open(gt_path, 'r') as f:
        for line in f:
            line = line.strip().replace(',', ' ')
            parts = list(map(float, line.split()))
            if len(parts) >= 4:
                gt.append(parts[:4])
    return np.array(gt)

# 读取预测框
def load_pred(seq_name):
    pred_path = os.path.join(RESULT_DIR, f"{seq_name}.txt")
    pred = []
    with open(pred_path, 'r') as f:
        for line in f:
            line = line.strip().replace(',', ' ')
            parts = list(map(float, line.split()))
            if len(parts) >= 4:
                pred.append(parts[:4])
    return np.array(pred)

# IoU 计算
def iou(boxA, boxB):
    x1, y1, w1, h1 = boxA
    x2, y2, w2, h2 = boxB
    xx1 = max(x1, x2)
    yy1 = max(y1, y2)
    xx2 = min(x1 + w1, x2 + w2)
    yy2 = min(y1 + h1, y2 + h2)
    w = max(0, xx2 - xx1)
    h = max(0, yy2 - yy1)
    inter = w * h
    union = w1 * h1 + w2 * h2 - inter
    return inter / (union + 1e-8)

# 计算标准 AUC
def compute_auc(ious):
    thresholds = np.arange(0.0, 1.01, 0.01)
    success = [np.mean(ious >= t) for t in thresholds]
    return np.mean(success)

# 主函数
def main():
    seq_list = [f[:-4] for f in os.listdir(RESULT_DIR) if f.endswith('.txt')]
    print(f"✅ 找到序列总数:{len(seq_list)}")

    auc_list = []

    for seq in seq_list:
        try:
            gt = load_gt(seq)
            pred = load_pred(seq)
        except:
            print(f"⚠️ {seq} 跳过")
            continue

        min_len = min(len(gt), len(pred))
        ious = [iou(gt[i], pred[i]) for i in range(min_len)]
        auc = compute_auc(ious)
        auc_list.append(auc)
        print(f"{seq:<28} | AUC = {auc:.4f}")

    print("\n" + "=" * 70)
    print("📊 所有序列 【标准平均 Success AUC】")
    print("=" * 70)
    print(f"✅ 平均 AUC = {np.mean(auc_list):.4f}")
    print("=" * 70)

if __name__ == "__main__":
    main()

生成可视化

import os
import numpy as np
import matplotlib.pyplot as plt

# ===================== 你的路径 =====================
RESULT_DIR = r"D:\Program\test11\OSTrack-main\output\test\tracking_results\ostrack\vitb_384_mae_ce_32x4_ep300\lasot"
DATASET_ROOT = r"D:\Program\test11\OSTrack-main\data\lasot"
# ====================================================

def load_gt(seq):
    prefix = seq.split('-')[0]
    path = os.path.join(DATASET_ROOT, prefix, seq, "groundtruth.txt")
    gt = []
    for line in open(path, errors='ignore'):
        line = line.strip().replace(',', ' ')
        vals = list(map(float, line.split()))
        if len(vals) >= 4:
            gt.append(vals[:4])
    return gt

def load_pred(seq):
    path = os.path.join(RESULT_DIR, seq + ".txt")
    pred = []
    for line in open(path, errors='ignore'):
        line = line.strip().replace(',', ' ')
        vals = list(map(float, line.split()))
        if len(vals) >= 4:
            pred.append(vals[:4])
    return pred

def iou(a, b):
    x1, y1, w1, h1 = a
    x2, y2, w2, h2 = b
    xx1 = max(x1, x2)
    yy1 = max(y1, y2)
    xx2 = min(x1 + w1, x2 + w2)
    yy2 = min(y1 + h1, y2 + h2)
    w = max(0, xx2 - xx1)
    h = max(0, yy2 - yy1)
    inter = w * h
    union = w1 * h1 + w2 * h2 - inter
    return inter / (union + 1e-8)

# ===================== 绘图主函数 =====================
def plot_curve():
    seqs = [f[:-4] for f in os.listdir(RESULT_DIR) if f.endswith('.txt')]
    all_ious = []

    for seq in seqs:
        try:
            gt = load_gt(seq)
            pred = load_pred(seq)
            n = min(len(gt), len(pred))
            for i in range(n):
                all_ious.append(iou(gt[i], pred[i]))
        except:
            continue

    thresholds = np.arange(0.0, 1.01, 0.01)
    success = [np.mean(np.array(all_ious) >= t) for t in thresholds]
    auc = np.mean(success)

    plt.figure(figsize=(7, 5))
    plt.plot(thresholds, success, 'b-', linewidth=3, label=f'AUC = {auc:.3f}')
    plt.fill_between(thresholds, success, alpha=0.3, color='blue')
    plt.xlabel('IoU Threshold')
    plt.ylabel('Success Rate')
    plt.title('LaSOT Success Curve (AUC)')
    plt.grid(True)
    plt.legend()
    plt.savefig('auc_curve.png', dpi=300)
    plt.close()

    print(f"✅ 图片已生成:auc_curve.png")
    print(f"✅ 最终 AUC = {auc:.3f}")

if __name__ == '__main__':
    plot_curve()

第6步        otb100数据集

修改路径

打开OSTrack-main\lib\test\evaluation\local.py

settings.otb_path = 'D:/Program/test11/OSTrack-main/data/OTB100'改成实际路径

打开lib/test/evaluation/otbdataset.py

40行左右ground_truth_rect = load_text(str(anno_path), delimiter=(',', None), dtype=np.float64, backend='numpy')

改成ground_truth_rect = load_text(str(anno_path), delimiter=',', dtype=np.float64, backend='numpy')


打开lib/test/utils/load_text.py

注释

ground_truth_rect = np.loadtxt(path, delimiter=d, dtype=dtype)

换成

with open(path, 'r') as f:

ground_truth_rect=np.loadtxt(io.StringIO(f.read().replace(',', ' ')))

打开 lib/test/utils/load_text.py

直接全部改成(豆包出品)

import numpy as np
import pandas as pd
import io

def load_text_numpy(path, delimiter, dtype):
    try:
        with open(path, 'r', encoding='utf-8', errors='ignore') as f:
            lines = []
            for line in f:
                line = line.strip()
                if not line:
                    continue
                line = line.replace(',', ' ')
                parts = list(map(float, line.split()))
                if len(parts) >= 4:
                    lines.append(parts[:4])
        return np.array(lines, dtype=dtype)
    except:
        pass

    raise Exception('Could not read file {}'.format(path))


def load_text_pandas(path, delimiter, dtype):
    try:
        with open(path, 'r', encoding='utf-8', errors='ignore') as f:
            lines = []
            for line in f:
                line = line.strip()
                if not line:
                    continue
                line = line.replace(',', ' ')
                parts = list(map(float, line.split()))
                if len(parts) >= 4:
                    lines.append(parts[:4])
        return np.array(lines, dtype=dtype)
    except:
        pass

    raise Exception('Could not read file {}'.format(path))


def load_text(path, delimiter=' ', dtype=np.float32, backend='numpy'):
    if backend == 'numpy':
        return load_text_numpy(path, delimiter, dtype)
    elif backend == 'pandas':
        return load_text_pandas(path, delimiter, dtype)


def load_str(path):
    with open(path, "r") as f:
        text_str = f.readline().strip().lower()

运行python tracking/test.py ostrack vitb_384_mae_ce_32x4_ep300 --dataset_name otb --threads 2 --num_gpus 1

更多推荐