Elffuss BraidHub

kikocis/ncnn public

master · 3.3 KiBRenderedRawPermalink
1### input data and extract output
2```cpp
3#include <opencv2/core/core.hpp>
4#include <opencv2/highgui/highgui.hpp>
5#include "net.h"
6
7int main()
8{
9 cv::Mat img = cv::imread("image.ppm", CV_LOAD_IMAGE_GRAYSCALE);
10 int w = img.cols;
11 int h = img.rows;
12
13 // subtract 128, norm to -1 ~ 1
14 ncnn::Mat in = ncnn::Mat::from_pixels_resize(img.data, ncnn::Mat::PIXEL_GRAY, w, h, 60, 60);
15 float mean[1] = { 128.f };
16 float norm[1] = { 1/128.f };
17 in.substract_mean_normalize(mean, norm);
18
19 ncnn::Net net;
20 net.load_param("model.param");
21 net.load_model("model.bin");
22
23 ncnn::Extractor ex = net.create_extractor();
24
25 ex.input("data", in);
26
27 ncnn::Mat feat;
28 ex.extract("output", feat);
29
30 return 0;
31}
32
33```
34
35### print Mat content
36```cpp
37void pretty_print(const ncnn::Mat& m)
38{
39 for (int q=0; q<m.c; q++)
40 {
41 const float* ptr = m.channel(q);
42 for (int z=0; z<m.d; z++)
43 {
44 for (int y=0; y<m.h; y++)
45 {
46 for (int x=0; x<m.w; x++)
47 {
48 printf("%f ", ptr[x]);
49 }
50 ptr += m.w;
51 printf("\n");
52 }
53 printf("\n");
54 }
55 printf("------------------------\n");
56 }
57}
58```
59
60### visualize Mat content
61```cpp
62void visualize(const char* title, const ncnn::Mat& m)
63{
64 std::vector<cv::Mat> normed_feats(m.c);
65
66 for (int i=0; i<m.c; i++)
67 {
68 cv::Mat tmp(m.h, m.w, CV_32FC1, (void*)(const float*)m.channel(i));
69
70 cv::normalize(tmp, normed_feats[i], 0, 255, cv::NORM_MINMAX, CV_8U);
71
72 cv::cvtColor(normed_feats[i], normed_feats[i], cv::COLOR_GRAY2BGR);
73
74 // check NaN
75 for (int y=0; y<m.h; y++)
76 {
77 const float* tp = tmp.ptr<float>(y);
78 uchar* sp = normed_feats[i].ptr<uchar>(y);
79 for (int x=0; x<m.w; x++)
80 {
81 float v = tp[x];
82 if (v != v)
83 {
84 sp[0] = 0;
85 sp[1] = 0;
86 sp[2] = 255;
87 }
88
89 sp += 3;
90 }
91 }
92 }
93
94 int tw = m.w < 10 ? 32 : m.w < 20 ? 16 : m.w < 40 ? 8 : m.w < 80 ? 4 : m.w < 160 ? 2 : 1;
95 int th = (m.c - 1) / tw + 1;
96
97 cv::Mat show_map(m.h * th, m.w * tw, CV_8UC3);
98 show_map = cv::Scalar(127);
99
100 // tile
101 for (int i=0; i<m.c; i++)
102 {
103 int ty = i / tw;
104 int tx = i % tw;
105
106 normed_feats[i].copyTo(show_map(cv::Rect(tx * m.w, ty * m.h, m.w, m.h)));
107 }
108
109 cv::resize(show_map, show_map, cv::Size(0,0), 2, 2, cv::INTER_NEAREST);
110 cv::imshow(title, show_map);
111}
112```
113
114### FAQ
115Q ncnn的起源
116
117A 深度学习算法要在手机上落地,caffe依赖太多,手机上也没有cuda,需要个又快又小的前向网络实现
118
119
120Q ncnn名字的来历
121
122A cnn就是卷积神经网络的缩写,开头的n算是一语n关。比如new/next(全新的实现),naive(ncnn是naive实现),neon(ncnn最初为手机优化),up主名字(←_←)
123
124
125Q 支持哪些平台
126
127A 跨平台,支持 android / ios / linux / windows / macos,也支持裸机跑
128
129
130Q 计算精度如何
131
132A armv7 neon float 不遵照 ieee754 标准,有些采用快速实现(如exp sin等),速度快但确保精度足够高
133
134
135Q logo
136
137A up主是mc玩家,所以灵魂手绘像素猫,还可以找到ncnn...