yolov5 pt转onnx_yolov5>onnx>ncnn>安卓apk

yolov5 pt转onnx_yolov5>onnx>ncnn>安卓apk_第1张图片

一. 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 detect(JNIEnv* env, jobject image, float threshold, float nms_threshold);
    std::vector labels{"car"}; //修改labels
private:
    static std::vector decode_infer(ncnn::Mat &data, int stride,const cv::Size& frame_size, int net_size,int num_classes,const std::vector& anchors,float threshold);
    static void nms(std::vector& result,float nms_threshold);
    ncnn::Net* Net;
    int input_size = 640;
    int num_class = 1; //修改类型
    std::vector 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");//修改模型文件
    }
}

直接编译

yolov5 pt转onnx_yolov5>onnx>ncnn>安卓apk_第2张图片

有问题添加QQ群:686070107

你可能感兴趣的:(yolov5,pt转onnx,yolov5转onnx)