![0daa9a82eb28dcca5fe7a23567e11a90.png](https://i-blog.csdnimg.cn/blog_migrate/64c7fed178a0ec8346db38dd0f643a43.jpeg)
一. yolov5 pt模型转onnx
条件:
colab notebook
yolov5
1. 安装环境
!pip install onnx>=1.7.0 # for ONNX export
!pip install coremltools==4.0 # for CoreML export
!pip install onnx-simplifier
2.修改export.py
def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
return self.conv(torch.cat([x, x, x, x], 1))
# return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))
3.导出onnx
%cd /content/yolov5
!python models/export.py --weights /content/yolov5/weights/best.pt --img-size 320 320
4. 简化onnx
!python -m onnxsim /content/yolov5/weights/best.onnx /content/yolov5/weights/last.onnx
二. onnx转ncnn
1.安装环境
!sudo apt-get install autoconf automake libtool curl make g++ unzip
2.编译protobuf
!git clone https://github.com/protocolbuffers/protobuf.git
%cd /content/protobuf
!git submodule update --init --recursive
!./autogen.sh
!./configure
!make
!make check
!sudo make install
!sudo ldconfig
3.编译ncnn
%cd /content
!git clone https://github.com/Tencent/ncnn.git
%cd /content/ncnn
!mkdir -p build
%cd /content/ncnn/build
!cmake -DNCNN_VULKAN=OFF .. #vulkan是针对gpu的,如果想要ncnn能调用gpu做推理,那么选项需要打开,设置为ON。
!make -j4 #开始编译
4.onnx转ncnn
%cd /content/ncnn/build/tools/onnx/
!./onnx2ncnn last.onnx model.param model.bin
三. 安卓运行ncnn
1.下载文件
git clone https://github.com/cmdbug/YOLOv5_NCNN.git
2. 修改文件
yolo5.h 两处
lass YoloV5 {
public:
YoloV5(AAssetManager* mgr, const char* param, const char* bin);
~YoloV5();
std::vector<BoxInfo> detect(JNIEnv* env, jobject image, float threshold, float nms_threshold);
std::vector<std::string> labels{"car"}; //修改labels
private:
static std::vector<BoxInfo> decode_infer(ncnn::Mat &data, int stride,const cv::Size& frame_size, int net_size,int num_classes,const std::vector<cv::Size>& anchors,float threshold);
static void nms(std::vector<BoxInfo>& result,float nms_threshold);
ncnn::Net* Net;
int input_size = 640;
int num_class = 1; //修改类型
std::vector<YoloLayerData> layers{
{"394",32,{{116,90},{156,198},{373,326}}},
{"375",16,{{30,61},{62,45},{59,119}}},
{"output",8,{{10,13},{16,30},{33,23}}},
};
box.java 一处
public class Box {
public float x0,y0,x1,y1;
private int label;
private float score;
private static String[] labels={"car"};//修改labels
public Box(float x0,float y0, float x1, float y1, int label, float score){
this.x0 = x0;
this.y0 = y0;
this.x1 = x1;
this.y1 = y1;
this.label = label;
this.score = score;
}
jni_interface.cpp 一处
Java_gd_hq_yolov5_YOLOv5_init(JNIEnv* env, jclass, jobject assetManager) {
if(YoloV5::detector == nullptr){
AAssetManager* mgr = AAssetManager_fromJava(env, assetManager);
YoloV5::detector = new YoloV5(mgr,"model.param","model.bin");//修改模型文件
}
}
直接编译
![5c9136d97d7c5e442300a07327ffdc9d.png](https://i-blog.csdnimg.cn/blog_migrate/0e9bde0645e8b40119a1b5063580d949.jpeg)
有问题添加QQ群:686070107