1. 程式人生 > >深度學習實戰(1)--手機端跑YOLO目標檢測網路(從DarkNet到Caffe再到NCNN完整打通)

深度學習實戰(1)--手機端跑YOLO目標檢測網路(從DarkNet到Caffe再到NCNN完整打通)

深度學習實戰(1)--手機端跑YOLO目標檢測網路(從DarkNet到Caffe再到NCNN完整打通)

 

這篇算是關鍵技術貼,YOLO是什麼、DarkNet是什麼、Caffe是什麼、NCNN又是什麼…等等這一系列科普這裡就完全不說了,牽扯實在太多,通過其他帖子有一定的積累後,看這篇就相對容易了。

本文核心:把一個目標檢測模型跑到手機上

整個工作分以下幾個階段:

1、訓練得到一個目標檢測模型

目前可以做目標檢測的模型有很多,比如R-CNN、Fast R-CNN、Faster R-CNN、SSD、MobileNet-SSD、Mask R-CNN、YOLOv1、YOLOv2、YOLOv3等等。

本文選擇的是YOLOv2_tiny,原因有YOLO快,簡單比較好用,而且DarkNet的原始碼去看看還是比較有意思的,這裡使用的是YOLOv2的tiny版本,網路更小一些,畢竟我們最終是要跑在手機上,嵌入式終端設別就那麼點硬體資源。

具體怎麼做,看我這篇帖子:Caffe–實現YOLOv2目標檢測 https://blog.csdn.net/lwplwf/article/details/83011667
一些實現細節,原始碼,指令碼等我都準備好了,按帖子裡直接下載用就行,我自己也重新下載試了一遍,沒問題,有問題的話評論區喊我。

2、模型在NCNN下跑起來

在1階段中,訓練得到了DarkNet下的.cfg模型結構檔案

.weights模型權重檔案,然後轉換為Caffe下的.prototxt模型結構檔案.caffemodel模型權重檔案

(1)安裝編譯ncnn(Ubuntu16.04)

下載ncnn:

git clone https://github.com/Tencent/ncnn
  • 1

進入ncnn根目錄,執行命令:

mkdir -p build
cd build
cmake ..
  • 1
  • 2
  • 3

在這裡插入圖片描述

make -j8
  • 1

在這裡插入圖片描述

(2)將caffemodel和prototxt轉換為param和bin

NCNN框架中網路定義檔案為.param檔案

,權值檔案為.bin檔案,可以通過NCNN中自帶的工具進行轉換。

1)將1階段得到的yolov2_tiny_3.prototxtyolov2_tiny_3.caffemodel兩個檔案放到ncnn-master/build/tools/caffe目錄下。
2)需要修改一下yolov2_tiny_3.prototxt檔案
將最後一層

layer {
  name: "region1"
  type: "Region"
  bottom: "layer15-conv"
  top: "region1"
  region_param {
    classes: 3
    coords: 4
    boxes_of_each_grid: 5
    softmax: true
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

修改為:

layer {
  name: "detection_out"
  type: "YoloDetectionOutput"
  bottom: "layer15-conv"
  top: "detection_out"
  include {
	phase: TEST
  }
  yolo_detection_output_param {
    num_classes: 3
    coords: 4
    confidence_threshold: 0.3
	nms_threshold: 0.45

    biases: 1.08
    biases: 1.19
    biases: 3.42
    biases: 4.41
    biases: 6.63
    biases: 11.38
    biases: 9.42
    biases: 5.11
    biases: 16.62
    biases: 10.52
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

終端進入該目錄執行命令:

./caffe2ncnn yolov2_tiny_3.prototxt yolov2_tiny_3.caffemodel yolov2_tiny_3.param yolov2_tiny_3.bin
  • 1

在這裡插入圖片描述
(3)NCNN進行檢測

修改NCNN根目錄下CMakeLists.txt 檔案
取消註釋add_subdirectory(examples)
在這裡插入圖片描述
NCNN根目錄下執行命令重新編譯:
(以後修改NCNN原始碼後,都需要重新編譯)

 cd build
 cmake ..
 make -j8
  • 1
  • 2
  • 3

將之前生成的yolov2_tiny_3.paramyolov2_tiny_3.bin放到build/examples目錄下。
終端進入該目錄執行命令:

./yolov2 111.jpg 
  • 1

在這裡插入圖片描述
在這裡插入圖片描述

3、將NCNN跑到手機上

其實也可以選擇在手機上跑OpenCV,然後使用OpenCV的dnn模組呼叫DarkNet,這樣連Caffe都不需要經過,可是…太慢了…