在部署中遇到了若干问题,在此进行记录。。
首先pt转onnx模型
笔者使用的脚本代码进行转换(比较推荐,否则转换ncnn可能有问题)
from ultralytics import YOLO
model = YOLO("./bestpc.pt")
success = model.export(format ='onnx',simplify=True,opset=12)
转之前要进行对/ultralytics/nn/modules.py中的代码进行修改
找到C2f下的forward函数这样修改
def forward(self, x):
# y = list(self.cv1(x).chunk(2, 1))
# y.extend(m(y[-1]) for m in self.m)
# return self.cv2(torch.cat(y, 1))
x = self.cv1(x)
x = [x, x[:, self.c:, ...]]
x.extend(m(x[-1]) for m in self.m)
x.pop(1)
return self.cv2(torch.cat(x, 1))
找到Detect下的forward函数这样修改(yolov8——detect这样修改,分割项目不是)
def forward(self, x):
shape = x[0].shape # BCHW
for i in range(self.nl):
x[i] = torch.cat((self.cv2[i](x[i]), self.cv3[i](x[i])), 1)
if self.training:
return x
elif self.dynamic or self.shape != shape:
self.anchors, self.strides = (x.transpose(0, 1) for x in make_anchors(x, self.stride, 0.5))
self.shape = shape
pred = torch.cat([xi.view(shape[0], self.no, -1) for xi in x], 2).permute(0, 2, 1)
return pred
修改完毕进行转换得到onnx模型
注意:!!我使用的yolov8代码的版本是ultralytics-8.0.50,使用较新的版本会导致模型转换后有很多问题,亲自踩坑
然后就是onnx转ncnn
好多教程都是使用一键转换的网站,但这个网站失效了,因此笔者配置onnx转换ncnn的环境进行转换,问题记录。。
# 准备基础环境
sudo apt install build-essential libopencv-dev cmake
# 编译安装protobuf依赖库
git clone https://github.com/protocolbuffers/protobuf.git # 安装源文件
cd protobuf
git submodule update --init --recursive # clone子模块的依赖
./autogen.sh # 执行自动生成的shell脚本
./configure # 配置文件shell脚本
make # 编译
make install # 编译安装
sudo ldconfig # 刷新
编译有问题多换换版本
1.配置NCNN库必要依赖
sudo apt install build-essential git cmake libprotobuf-dev protobuf-compiler libvulkan-dev vulkan-utils libopencv-dev
2.编译NCNN
执行下列命令
git clone https://github.com/Tencent/ncnn.git
cd ncnn
git submodule update --init
mkdir build
cd build
cmake ..
make -j8
make install
sudo ldconfig # 刷新
编译完成进入build文件夹在这里可以实现转换模型 (找到onnx2ncnn可执行文件)
./onnx2ncnn my.onnx my.param my.bin
换入你的安卓项目就大功告成了!