参考博客:https://blog.csdn.net/Best_Coder/article/details/76201275#reply
https://blog.csdn.net/computerme/article/details/77876633
实现方法:
1、前提条件:下载并成功编译ncnn
(主要参考github文档:https://github.com/Tencent/ncnn/wiki/how-to-build)
install g++ cmake protobuf
$ cd <ncnn-root-dir>
$ mkdir -p build
$ cd build
$ cmake ..
$ make -j4
(PS:protobuf版本号要保证为2.6.1,如果版本号为protobuf2.5.0则会make -j4出错,多么痛的领悟!!!)
install opencv for building example
$ cd <ncnn-root-dir>
uncomment add_subdirectory(examples)//将examples的注释去掉
in CMakeLists.txt with your favourite editor
$ mkdir -p build
$ cd build
$ cmake ..
$ make -j4
copy examples/squeezenet_v1.1.param to build/examples
copy examples/squeezenet_v1.1.bin to build/examples
$ cd build/examples
$ ./squeezenet yourimage.jpg
output top-3 class-id and score
you may refer examples/synset_words.txt to find the class name
404 = 0.990290
908 = 0.004464
405 = 0.003941
编译完成后在ncnn/build/tools 目录下,可以看到已经生成了ncnn2mem这个可执行文件。同时,在caffe文件夹下可以看到有 caffe2ncnn可执行文件。
caffe2ncnn可的作用是将caffe模型生成ncnn 模型,ncnn2mem可对模型进行加密。
2、主要过程:
Step1: 下载mobileNet的caffe模型和配置文件:
可以从https://github.com/shicai/MobileNet-Caffe中下载
得到:mobilenet_deploy.prototxt和mobilenet.caffemodel两个文件。
step2:
PS:由于NCNN提供的转换工具只支持转换新版的caffe模型,所以我们需要利用caffe自带的工具将旧版的
caffe模型转换为新版的caffe模型后,再将新版本的模型转换为NCNN模型.
旧版本caffe模型--->新版本caffe模型--->NCNN模型
step2.1
旧版本caffe模型--->新版本caffe模型
命令:
ruyiwei@ruyiwei: /home/caffe/build/tools/upgrade_net_proto_text mobilenet_v2_deploy.prototxt mobilenet_v2_new_deplpy.prototxt
ruyiwei@ruyiwei:~/code/ncnn/build/tools$ /home/caffe/build/tools/upgrade_net_proto_binary mobilenet_v2.caffemodel mobilenet_v2_new.caffemodel
(注意:要根据自己的caffe位置进行修改)
执行之后,就可以生成新的caffe模型
step2.2
新版本caffe模型--->NCNN模型
在第一步生成的ncnn/build/tools/caffe目录下用caffe2ncnn来转换新版的mobileNet模型:
命令:
root@aa-pc:/home/aa/qxq/project/fruits/ncnn-master/build/tools/caffe# ./caffe2ncnn mobilenet_v2_new_deplpy.prototxt mobilenet_v2_new.caffemodel mobilenet2.param mobilenet2.bin
执行之后就生成了。执行上面命令后就可以生成NCNN模型需要的.param与.bin文件
其中,.param可以理解为网络的配置文件,.bin可以理解为网络的参数(各种权重)文件。 Step3:
可以对模型进行加密:
命令:
ruyiwei@ruyiwei:~/code/ncnn/build/tools$./ncnn2mem mobilenet.param mobilenet.bin mobilenet.id.h mobilenet.mem.h
最后可以生成 alexnet.param.bin 这样的二进制加密文件。ncnn对加密和非加密两种文件的读取方式不一样。
//load非加密的ncnn模型
ncnn::Net net;
net.load_param("mobilenet.param");
net.load_model("mobilenet.bin");
//load加密的ncnn模型
ncnn::Net net;
net.load_param_bin("mobilenet.param.bin");
net.load_model("mobilenet.bin");
3、编译NCNN例程
在生成之后,需要编译。
Step3.1
首先我们需要进入ncnn/build/examples目录,创建目录mobilenet_squeezenet,新建一个Makefile,内容如下,最重要的是,NCNN例程序只支持opencv2,不支持opencv3.
Makefile文件的内容如下:
NCNN_DIR =/home/tommy/NCNN/ncnn
OPENCV =/home/tommy/NCNN/opencv-2.4.10
INCPATH =-I${NCNN_DIR}/build/install/include \
-I${OPENCV}/modules/objdetect/include \
-I${OPENCV}/modules/highgui/include \
-I${OPENCV}/modules/imgproc/include \
-I${OPENCV}/modules/core/include
LIBS = -lopencv_core -lopencv_highgui -pthread
# -lopencv_imgproc -fopenmp -pthread
LIBPATH = -L${OPENCV}/build/lib
squeezenet_mobilenet:squeezenet_mobilenet.cpp
$(CXX) $(INCPATH) $(LIBPATH) $^ ${NCNN_DIR}/build/install/lib/libncnn.a $(LIBS) -o $@
Step3.2:
由于自己的模型已经生成了,所以我们要再重新写一个squeezenet_mobilenet.cpp文件,来执行生成的mobilenet.para和mobilenet.bin。
squeezenet_mobilenet.cpp的代码如下:
// Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//modified by tommy
//date:2019-1-31
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;
#include "net.h"
static int detect_squeezenet(const cv::Mat& bgr, std::vector<float>& cls_scores)
{
ncnn::Net squeezenet;
squeezenet.load_param("mobilenet2.param");
squeezenet.load_model("mobilenet2.bin");
ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR, bgr.cols, bgr.rows, 227, 227);
const float mean_vals[3] = {104.f, 117.f, 123.f};
in.substract_mean_normalize(mean_vals, 0);
ncnn::Extractor ex = squeezenet.create_extractor();
ex.input("data", in);
ncnn::Mat out;
ex.extract("prob", out);
cls_scores.resize(out.w);
for (int j=0; j<out.w; j++)
{
cls_scores[j] = out[j];
}
return 0;
}
#if 0
static int print_topk(const std::vector<float>& cls_scores, int topk)
{
// partial sort topk with index
int size = cls_scores.size();
std::vector< std::pair<float, int> > vec;
vec.resize(size);
for (int i=0; i<size; i++)
{
vec[i] = std::make_pair(cls_scores[i], i);
}
std::partial_sort(vec.begin(), vec.begin() + topk, vec.end(),
std::greater< std::pair<float, int> >());
// print topk and score
for (int i=0; i<topk; i++)
{
float score = vec[i].first;
int index = vec[i].second;
fprintf(stderr, "%d = %f\n", index, score);
}
return 0;
}
#endif
static int print_topk(const std::vector<float>& cls_scores, int topk, vector<int>& index_result, vector<float>& score_result)
{
// partial sort topk with index
int size = cls_scores.size();
std::vector< std::pair<float, int> > vec;
vec.resize(size);
for (int i=0; i<size; i++)
{
vec[i] = std::make_pair(cls_scores[i], i);
}
std::partial_sort(vec.begin(), vec.begin() + topk, vec.end(), std::greater< std::pair<float, int> >());
// print topk and score
for (int i=0; i<topk; i++)
{
float score = vec[i].first;
int index = vec[i].second;
index_result.push_back(index);
score_result.push_back(score);
//fprintf(stderr, "%d = %f\n", index, score);
}
return 0;
}
static int load_labels(string path, vector<string>& labels)
{
FILE* fp = fopen(path.c_str(), "r");
while (!feof(fp))
{
char str[1024];
fgets(str, 1024, fp); //¶ÁÈ¡Ò»ÐÐ
string str_s(str);
if (str_s.length() > 0)
{
for (int i = 0; i < str_s.length(); i++)
{
if (str_s[i] == ' ')
{
string strr = str_s.substr(i, str_s.length() - i - 1);
labels.push_back(strr);
i = str_s.length();
}
}
}
}
return 0;
}
#if 0
int main(int argc, char** argv)
{
if (argc != 2)
{
fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]);
return -1;
}
const char* imagepath = argv[1];
cv::Mat m = cv::imread(imagepath, CV_LOAD_IMAGE_COLOR);
if (m.empty())
{
fprintf(stderr, "cv::imread %s failed\n", imagepath);
return -1;
}
std::vector<float> cls_scores;
detect_squeezenet(m, cls_scores);
print_topk(cls_scores, 3);
return 0;
}
#endif
int main(int argc, char** argv)
{
const char* imagepath = argv[1];
vector<string> labels;
load_labels("synset.txt", labels);
cv::Mat m = cv::imread(imagepath, CV_LOAD_IMAGE_COLOR);
if (m.empty())
{
fprintf(stderr, "cv::imread %s failed\n", imagepath);
return -1;
}
std::vector<float> cls_scores;
detect_squeezenet(m, cls_scores);
vector<int> index;
vector<float> score;
print_topk(cls_scores, 3, index, score);
for (int i = 0; i < index.size(); i++)
{
cv::putText(m, labels[index[i]], Point(50, 50 + 30 * i), CV_FONT_HERSHEY_SIMPLEX, 1.2, Scalar(0, 100, 200), 2, 8);
}
imshow("m", m);
imwrite("test_result.jpg", m);
waitKey(0);
return 0;
}
step3.3:将上面的.cpp 文件生成可执行文件:
make
然后生成了一个可执行文件:squeezenet_mobilenet
./squeezenet_mobilenet cat.ipg