pytorch yolov3转化为caffemodel

一、.pytorch yolov3

训练所用的代码

https://github.com/bubbliiiing/yolo3-pytorch

基于此模型训练得到pt权重文件,predict.py将mode改成export_onnx,修改yolo.py中model_path。运行predict.py,得到onnx权重文件。

二、.搭建caffe环境

参考博客:如何在Ubuntu18.04上安装caffe+darknet2caffe环境

  1. 在VM上配置好Ubuntu18.04后,分步执行下面的命令,对Ubuntu里面的软件进行更新
sudo apt-get update
sudo apt-get upgrade

在这里插入图片描述
2. 分步执行下面的命令,安装所需的依赖软件。

sudo apt-get install  -y libopencv-dev
sudo apt-get install -y build-essential cmake git pkg-config
sudo apt-get install -y libprotobuf-dev libleveldb-dev libsnappy-dev libhdf5-serial-dev protobuf-compiler
sudo apt-get install -y liblapack-dev
sudo apt-get install -y libatlas-base-dev 
sudo apt-get install -y --no-install-recommends libboost-all-dev
sudo apt-get install -y libgflags-dev libgoogle-glog-dev liblmdb-dev
sudo apt-get install -y python-numpy python-scipy
sudo apt-get install -y python3-pip
sudo apt-get install -y python3-numpy python3-scipy
  1. 执行下面的命令,下载caffe开源软件。`
git clone https://github.com/BVLC/caffe.git
cd caffe/python/
for req in $(cat requirements.txt); do pip3 install $req; done

在这里插入图片描述
4. 进入caffe目录下,执行下面的命令,将 Makefile.config.example 文件复制一份并更名为 Makefile.config

cp Makefile.config.example  Makefile.config

在这里插入图片描述
5. 接下来是修改Makefile.config里面的配置,使用vim命令打开Makefile.config。

vim Makefile.config

修改后的文件如下所示:

## Refer to http://caffe.berkeleyvision.org/installation.html
# Contributions simplifying and improving our build system are welcome!

# cuDNN acceleration switch (uncomment to build with cuDNN).
# USE_CUDNN := 1

# CPU-only switch (uncomment to build without GPU support).
CPU_ONLY := 1

# uncomment to disable IO dependencies and corresponding data layers
# USE_OPENCV := 0
# USE_LEVELDB := 0
# USE_LMDB := 0
# This code is taken from https://github.com/sh1r0/caffe-android-lib
# USE_HDF5 := 0

# uncomment to allow MDB_NOLOCK when reading LMDB files (only if necessary)
#	You should not set this flag if you will be reading LMDBs with any
#	possibility of simultaneous read and write
# ALLOW_LMDB_NOLOCK := 1

# Uncomment if you're using OpenCV 3
OPENCV_VERSION := 3

# To customize your choice of compiler, uncomment and set the following.
# N.B. the default for Linux is g++ and the default for OSX is clang++
# CUSTOM_CXX := g++

# CUDA directory contains bin/ and lib/ directories that we need.
CUDA_DIR := /usr/local/cuda
# On Ubuntu 14.04, if cuda tools are installed via
# "sudo apt-get install nvidia-cuda-toolkit" then use this instead:
# CUDA_DIR := /usr

# CUDA architecture setting: going with all of them.
# For CUDA < 6.0, comment the *_50 through *_61 lines for compatibility.
# For CUDA < 8.0, comment the *_60 and *_61 lines for compatibility.
# For CUDA >= 9.0, comment the *_20 and *_21 lines for compatibility.
CUDA_ARCH := -gencode arch=compute_20,code=sm_20 \
		-gencode arch=compute_20,code=sm_21 \
		-gencode arch=compute_30,code=sm_30 \
		-gencode arch=compute_35,code=sm_35 \
		-gencode arch=compute_50,code=sm_50 \
		-gencode arch=compute_52,code=sm_52 \
		-gencode arch=compute_60,code=sm_60 \
		-gencode arch=compute_61,code=sm_61 \
		-gencode arch=compute_61,code=compute_61

# BLAS choice:
# atlas for ATLAS (default)
# mkl for MKL
# open for OpenBlas
BLAS := atlas
# Custom (MKL/ATLAS/OpenBLAS) include and lib directories.
# Leave commented to accept the defaults for your choice of BLAS
# (which should work)!
# BLAS_INCLUDE := /path/to/your/blas
# BLAS_LIB := /path/to/your/blas

# Homebrew puts openblas in a directory that is not on the standard search path
# BLAS_INCLUDE := $(shell brew --prefix openblas)/include
# BLAS_LIB := $(shell brew --prefix openblas)/lib

# This is required only if you will compile the matlab interface.
# MATLAB directory should contain the mex binary in /bin.
# MATLAB_DIR := /usr/local
# MATLAB_DIR := /Applications/MATLAB_R2012b.app

# NOTE: this is required only if you will compile the python interface.
# We need to be able to find Python.h and numpy/arrayobject.h.
# PYTHON_INCLUDE := /usr/include/python2.7 \
#		/usr/lib/python2.7/dist-packages/numpy/core/include
# Anaconda Python distribution is quite popular. Include path:
# Verify anaconda location, sometimes it's in root.
# ANACONDA_HOME := $(HOME)/anaconda
# PYTHON_INCLUDE := $(ANACONDA_HOME)/include \
		# $(ANACONDA_HOME)/include/python2.7 \
		# $(ANACONDA_HOME)/lib/python2.7/site-packages/numpy/core/include

# Uncomment to use Python 3 (default is Python 2)
PYTHON_LIBRARIES := boost_python3 python3.6m
PYTHON_INCLUDE := /usr/include/python3.6m \
                 /usr/lib/python3.6/dist-packages/numpy/core/include

# We need to be able to find libpythonX.X.so or .dylib.
PYTHON_LIB := /usr/lib
# PYTHON_LIB := $(ANACONDA_HOME)/lib

# Homebrew installs numpy in a non standard path (keg only)
# PYTHON_INCLUDE += $(dir $(shell python -c 'import numpy.core; print(numpy.core.__file__)'))/include
# PYTHON_LIB += $(shell brew --prefix numpy)/lib

# Uncomment to support layers written in Python (will link against Python libs)
WITH_PYTHON_LAYER := 1

# Whatever else you find you need goes here.
INCLUDE_DIRS := $(PYTHON_INCLUDE) /usr/local/include /usr/include/hdf5/serial
LIBRARY_DIRS := $(PYTHON_LIB) /usr/local/lib /usr/lib usr/lib/x86_64-linux-gnu /usr/lib/x86_64-linux-gnu/hdf5/serial

# If Homebrew is installed at a non standard location (for example your home directory) and you use it for general dependencies
# INCLUDE_DIRS += $(shell brew --prefix)/include
# LIBRARY_DIRS += $(shell brew --prefix)/lib

# NCCL acceleration switch (uncomment to build with NCCL)
# https://github.com/NVIDIA/nccl (last tested version: v1.2.3-1+cuda8.0)
# USE_NCCL := 1

# Uncomment to use `pkg-config` to specify OpenCV library paths.
# (Usually not necessary -- OpenCV libraries are normally installed in one of the above $LIBRARY_DIRS.)
# USE_PKG_CONFIG := 1

# N.B. both build and distribute dirs are cleared on `make clean`
BUILD_DIR := build
DISTRIBUTE_DIR := distribute

# Uncomment for debugging. Does not work on OSX due to https://github.com/BVLC/caffe/issues/171
# DEBUG := 1

# The ID of the GPU that 'make runtest' will use to run unit tests.
TEST_GPUID := 0

# enable pretty build (comment to see full commands)
Q ?= @
  1. 修改Makefile文件里面的一些配置,使用vim 打开Makefile,进行修改。
vim Makefile

(1)修改DYNAMIC_VERSION_REVISION的值

将
DYNAMIC_VERSION_REVISION 	:= 0
改为
DYNAMIC_VERSION_REVISION 	:= 0-rc3

(2)修改 LIBRARIES 的值。

将
LIBRARIES += glog gflags protobuf boost_system boost_filesystem m
改为
LIBRARIES += glog gflags protobuf boost_system boost_filesystem boost_regex m hdf5_hl hdf5

在这里插入图片描述

将
LIBRARIES += opencv_imgcodecs
改为
LIBRARIES += opencv_imgcodecs opencv_videoio

在这里插入图片描述
(3)将# NCCL acceleration configuration下面的四行注释掉

# NCCL acceleration configuration
ifeq ($(USE_NCCL), 1)
	LIBRARIES += nccl
	COMMON_FLAGS += -DUSE_NCCL
endif
改为
# NCCL acceleration configuration
# ifeq ($(USE_NCCL), 1)
#	LIBRARIES += nccl
#	COMMON_FLAGS += -DUSE_NCCL
# endif

在这里插入图片描述

  1. 在caffe目录下,分步执行下面的命令,来编译caffe。
make -j4
make pycaffe

在这里插入图片描述
在这里插入图片描述

  1. 执行下面的命令,将caffe的python路径设置为环境变量,并更新环境变量。
    打开.bashrc:
sudo vim ~/.bashrc 

在文件的末尾加上下面的语句

export PYTHONPATH=/home/hispark/code/caffe/python:$PYTHONPATH #修改为自己的caffe/python路径

再执行下面的命令,更新环境变量

source ~/.bashrc
  1. 测试caffe环境是否OK,在Ubuntu的任意目录下,执行 python3,当出现”>>>”的提示符后,再输入import caffe,如果没有任何报错信息,说明caffe环境已经搭建成功了。
python3
import caffe

在这里插入图片描述

三、重新编译caffe

git clone https://github.com/jnulzl/caffe_plus.git
cp caffe_plus/include/caffe/layers/upsample_layer.hpp caffe/include/caffe/layers/
cp caffe_plus/src/caffe/layers/upsample_layer.cpp caffe/src/caffe/layers/
cp caffe_plus/src/caffe/layers/upsample_layer.cu caffe/src/caffe/layers/
cp caffe_plus/include/caffe/layers/permute_layer.hpp caffe/include/caffe/layers/
cp caffe_plus/src/caffe/layers/permute_layer.cpp caffe/src/caffe/layers/
cp caffe_plus/src/caffe/layers/permute_layer.cu caffe/src/caffe/layers/
# 修改caffe.proto文件
vim caffe/src/caffe/proto/caffe.proto
  在optional WindowDataParameter window_data_param = 129;(约第423行)后增加代码:
optional PermuteParameter permute_param = 150;
optional UpsampleParameter upsample_param = 151;
  在末尾增加代码:
message PermuteParameter {
    
    
  // The new orders of the axes of data. Notice it should be with
  // in the same range as the input data, and it starts from 0.
  // Do not provide repeated order.
  repeated uint32 order = 1;
}
message UpsampleParameter {
    
    		
	optional int32 height = 1 [default = 32];
	optional int32 width = 2 [default = 32];
	optional int32 height_scale = 3 [default = 2];
	optional int32 width_scale = 4 [default = 2];
	enum UpsampleOp {
    
    
		NEAREST = 0;
		BILINEAR = 1;
	}
	optional UpsampleOp mode = 5 [default = BILINEAR];
}
# 重新编译
cd caffe
make all -j8
make pycaffe -j8

四、onnx转caffe

参考博客:yolo模型转换:pytorch -> onnx -> caffe

git clone https://github.com/xxradon/ONNXToCaffe.git
 
cd ONNXToCaffe
 
python3 convertCaffe.py ./model/yolov3-si.onnx ./model/yolov3-si.prototxt ./model/yolov3-si.caffemodel

报错一:

Traceback (most recent call last):
  File "convertCaffe.py", line 122, in <module>
    convertToCaffe(graph, opset_version, prototxt_path, caffemodel_path)
  File "convertCaffe.py", line 67, in convertToCaffe
    layer = converter_fn(node,graph,err)
  File "/home/ubuntu/ONNXToCaffe-master/onnx2caffe/_operators.py", line 257, in _convert_Reshape
    return err.unsupported_op_configuration(node, "Reshape dimention number shall be 2 or 4")
  File "/home/ubuntu/ONNXToCaffe-master/onnx2caffe/_error_utils.py", line 44, in unsupported_op_configuration
    raise TypeError(
TypeError: Error while converting op of type: Reshape. Error message: Reshape dimention number shall be 2 or 4

修改_operators.py(yolo的数据shape是5维数组)

vim ./onnx2caffe/_operators.py
 
  修改代码:
elif len(shape) == 4:elif len(shape) == 4 or len(shape) == 5:

报错二:

"ONNX opset version {
    
    } is not supported,only opset 9 is supported,you can export onnx by setting opset_version like torch.onnx.export(model, '', opset_version=9, verbose=True

因为转换脚本只支持opset_version=9,注意在用torch.onnx.export()接口导出onnx时将opset_version参数设置为opset_version=9。

报错三:

cannot fit 'int' into an index-sized integer

在这里插入图片描述
重新编译caffe,进入caffe目录下:

make clean
make
make pycaffe

转换成功的caffemodel和prototxt保存在model文件夹下。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44769034/article/details/124523084