飞道的博客

yolov5 转onnx转ncnn

788人阅读  评论(0)

代码:https://github.com/ultralytics/yolov5(v3.0)
一、yolov5 pt模型转onnx
安装:

pip install onnx>=1.7.0  # for ONNX export
pip install coremltools==4.0  # for CoreML export
pip install onnx-simplifier

pytorch->onnx转化
yolov5s.pt 权重文件复制到yolov5-3.0工程下,
在终端运行:

python models/export.py --weights yolov5s.pt --img 640 --batch 1  # export at 640x640 with batch size 1


CoreML 有报错,解决办法:
https://github.com/ultralytics/yolov5/issues/1945
在终端执行:

pip install -Uqq git+https://github.com/apple/coremltools.git 
#或:
python3 -m pip install -Uqq git+https://github.com/apple/coremltools.git

生成yolov5s.onnx , yolov5s.torchscript.pt,yolov5s.mlmodel 文件

在终端运行:

python -m onnxsim  onnx_inputpath onnx_outputpath


生成:yolov5s_sim.onnx文件

二、onnx转ncnn
1、protobuf更换
忘记了出于什么原因,我是更换了protobuf 3.15.8
下载 protobuf-cpp-3.15.8.tar.gz
运行命令:

./configure
make
make check
sudo make install
sudo ldconfig

报错:error while loading shared libraries: libprotoc.so.26: cannot open shared object file: No such file or directory
解决方法:

export LD_LIBRARY_PATH=/usr/local/lib
ldconfig

2、编译ncnn

#cd yolov5
git clone https://github.com/Tencent/ncnn.git
#cd /yolov5pro/ncnn
mkdir -p build
#cd /content/ncnn/build
cmake -DNCNN_VULKAN=OFF ..  #vulkan是针对gpu的,如果想要ncnn能调用gpu做推理,那么选项需要打开,设置为ON,但是我用on的时候没有编译过去
make -j4  #开始编译


3、onnx转ncnn

#cd /content/ncnn/build/tools/onnx/
./onnx2ncnn last.onnx model.param model.bin

若出现下图这种情况,是因为没有用onnx-simplifer 简化的模型



ncnn不支持focus结构,需要手动对生成的yolov5s_sim.param 进行修改,修改两个地方
(1)、

删除大红框中的10行,用自定义的YoloV5Focus 代替

YoloV5Focus       focus       1 1  images  207

把小红框的201修改为201-(10-1)=192

(2)、支持动态尺寸输入
将reshape中的6400,1600,400更改为-1,或者其他 0=后面的数


4、ncnnoptimize优化

./ncnnoptimize yolov5s_sim.param yolov5s_sim.bin yolov5s-opt.param yolov5s-opt.bin 1

其中最后的flag 如果是0指的的是fp32,如果是1指的是fp16

5、修改ncnn/example/yolov5.cpp
加载yolov5s-opt.param和 yolov5s-opt.bin

修改ex.extract(),按照yolov5s.param中Permute层修改


6、运行example
先重新编译


在终端运行:

#cd yolov5pro/ncnn/build/examples
./yolov5 images/bus.jpg


遇到的报错:
这里又遇到了opencv报错的问题,3.4.2版本太低了

我的方法是:修改CMakeLists.txt
添加一段opencv3.4.12的代码

set(OpenCV_DIR "/usr/local/opencv3.4.12/") 
find_package(OpenCV 3.4.12 REQUIRED)
if (OpenCV_FOUND)
    # If the package has been found, several variables will
    # be set, you can find the full list with descriptions
    # in the OpenCVConfig.cmake file.
    # Print some message showing some of them
    message(STATUS "OpenCV library status:")
    message(STATUS " version: ${OpenCV_VERSION}")
    message(STATUS " include path: ${OpenCV_INCLUDE_DIRS}" \n)
else ()
    message(FATAL_ERROR "Could not locate OpenCV" \n)
endif()

然后在重新 cmake
在把这段代码删除,make,make install 找的opencv就是3.4.12
参考:
https://www.tqwba.com/x_d/jishu/355441.html
https://blog.csdn.net/weixin_39786141/article/details/112405164
https://blog.csdn.net/flyfish1986/article/details/116604907


转载:https://blog.csdn.net/yx868yx/article/details/116663020
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场