一、格式转换
可以把python中的.pt文件,导出为libtorch识别的格式:
model = YOLO("yolo11n.pt")
model.export(format="torchscript")
二、查看结构
在c++中,我用qt,这样做的:
#include "mainwindow.h"
#include "ui_mainwindow.h"#undef slots
#include <torch/torch.h>
#include <torch/script.h>
#define slots Q_SLOTSMainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);
}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::on_pushButton_clicked()
{try {// 加载模型文件torch::jit::script::Module model = torch::jit::load("d:/BaiduNetdiskDownload/ultralytics-main/yolo11n.torchscript");model.eval();// 打印模型结构for (const auto& child : model.named_children()) {qDebug() << "层名称:" << QString::fromStdString(child.name);qDebug() << "层类型:" << QString::fromStdString(child.value.type()->str());// 打印该层的参数信息for (const auto& param : child.value.named_parameters()) {qDebug() << "参数名称:" << QString::fromStdString(param.name);// 获取并打印形状auto sizes = param.value.sizes();QString shape = "[";for(size_t i = 0; i < sizes.size(); ++i) {shape += QString::number(sizes[i]);if(i < sizes.size() - 1) shape += ", ";}shape += "]";qDebug() << "参数形状:" << shape;}qDebug() << "------------------------";}qDebug() << "模型加载成功";}catch (const c10::Error& e) {qDebug() << "模型加载失败:" << e.what();}
}