一. yolov5 pt模型轉onnx
條件:
colab notebook
yolov5java
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 兩處python
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 一處git
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 一處github
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");//修改模型文件 } }
直接編譯
有問題添加QQ羣:686070107bash