Elffuss BraidHub

kikocis/ncnn public

master · 6.2 KiBRenderedRawPermalink
1### caffemodel should be row-major
2
3`caffe2ncnn` tool assumes the caffemodel is row-major (produced by c++ caffe train command).
4
5The kernel 3x3 weights should be stored as
6```
7a b c
8d e f
9g h i
10```
11
12However, matlab caffe produced col-major caffemodel.
13
14You have to transpose all the kernel weights by yourself or re-training using c++ caffe train command.
15
16Besides, you may interest in https://github.com/conanhujinming/matcaffe2caffe
17
18### check input is RGB or BGR
19
20If your caffemodel is trained using c++ caffe and opencv, then the input image should be BGR order.
21
22If your model is trained using matlab caffe or pytorch or mxnet or tensorflow, the input image would probably be RGB order.
23
24The channel order can be changed on-the-fly through proper pixel type enum
25```
26// construct RGB blob from rgb image
27ncnn::Mat in_rgb = ncnn::Mat::from_pixels(rgb_data, ncnn::Mat::PIXEL_RGB, w, h);
28
29// construct BGR blob from bgr image
30ncnn::Mat in_bgr = ncnn::Mat::from_pixels(bgr_data, ncnn::Mat::PIXEL_BGR, w, h);
31
32// construct BGR blob from rgb image
33ncnn::Mat in_bgr = ncnn::Mat::from_pixels(rgb_data, ncnn::Mat::PIXEL_RGB2BGR, w, h);
34
35// construct RGB blob from bgr image
36ncnn::Mat in_rgb = ncnn::Mat::from_pixels(bgr_data, ncnn::Mat::PIXEL_BGR2RGB, w, h);
37```
38
39
40### image decoding
41
42JPEG(`.jpg`,`.jpeg`) is loss compression, people may get different pixel value for same image on same position.
43
44`.bmp` images are recommended instead.
45
46### interpolation / resizing
47
48There are several image resizing methods, which may generate different result for same input image.
49
50Even we specify same interpolation method, different frameworks/libraries and their various versions may also introduce difference.
51
52A good practice is feed same size image as the input layer expected, e.g. read a 224x244 bmp image when input layer need 224x224 size.
53
54
55### Mat::from_pixels/from_pixels_resize assume that the pixel data is continuous
56
57You shall pass continuous pixel buffer to from_pixels family.
58
59If your image is an opencv submat from an image roi, call clone() to get a continuous one.
60```
61cv::Mat image;// the image
62cv::Rect facerect;// the face rectangle
63
64cv::Mat faceimage = image(facerect).clone();// get a continuous sub image
65
66ncnn::Mat in = ncnn::Mat::from_pixels(faceimage.data, ncnn::Mat::PIXEL_BGR, faceimage.cols, faceimage.rows);
67```
68
69### pre process
70Apply pre process according to your training configuration
71
72Different model has different pre process config, you may find the following transform config in Data layer section
73```
74transform_param {
75 mean_value: 103.94
76 mean_value: 116.78
77 mean_value: 123.68
78 scale: 0.017
79}
80```
81Then the corresponding code for ncnn pre process is
82```cpp
83const float mean_vals[3] = { 103.94f, 116.78f, 123.68f };
84const float norm_vals[3] = { 0.017f, 0.017f, 0.017f };
85in.substract_mean_normalize(mean_vals, norm_vals);
86```
87
88Mean file is not supported currently
89
90So you have to pre process the input data by yourself (use opencv or something)
91```
92transform_param {
93 mean_file: "imagenet_mean.binaryproto"
94}
95```
96
97For pytorch or mxnet-gluon
98```python
99transforms.ToTensor(),
100transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
101```
102Then the corresponding code for ncnn pre process is
103```cpp
104// R' = (R / 255 - 0.485) / 0.229 = (R - 0.485 * 255) / 0.229 / 255
105// G' = (G / 255 - 0.456) / 0.224 = (G - 0.456 * 255) / 0.224 / 255
106// B' = (B / 255 - 0.406) / 0.225 = (B - 0.406 * 255) / 0.225 / 255
107const float mean_vals[3] = {0.485f*255.f, 0.456f*255.f, 0.406f*255.f};
108const float norm_vals[3] = {1/0.229f/255.f, 1/0.224f/255.f, 1/0.225f/255.f};
109in.substract_mean_normalize(mean_vals, norm_vals);
110```
111
112### use the desired blob
113The blob names for input and extract are differ among models.
114
115For example, squeezenet v1.1 use "data" as input blob and "prob" as output blob while mobilenet-ssd use "data" as input blob and "detection_out" as output blob.
116
117Some models may need multiple input or produce multiple output.
118
119```cpp
120ncnn::Extractor ex = net.create_extractor();
121
122ex.input("data", in);// change "data" to yours
123ex.input("mask", mask);// change "mask" to yours
124
125ex.extract("output1", out1);// change "output1" to yours
126ex.extract("output2", out2);// change "output2" to yours
127```
128
129### blob may have channel gap
130Each channel pointer is aligned by 128bit in ncnn Mat structure.
131
132blob may have gaps between channels if (width x height) can not divided exactly by 4
133
134Prefer using ncnn::Mat::from_pixels or ncnn::Mat::from_pixels_resize for constructing input blob from image data
135
136If you do need a continuous blob buffer, reshape the output.
137```cpp
138// out is the output blob extracted
139ncnn::Mat flattened_out = out.reshape(out.w * out.h * out.c);
140
141// plain array, C-H-W
142const float* outptr = flattened_out;
143```
144
145### create new Extractor for each image
146The `ncnn::Extractor` object is stateful, if you reuse for different input, you will always get exact the same result cached inside.
147
148Always create new Extractor to process images in loop unless you do know how the stateful Extractor works.
149```cpp
150for (int i=0; i<count; i++)
151{
152 // always create Extractor
153 // it's cheap and almost instantly !
154 ncnn::Extractor ex = net.create_extractor();
155
156 // use
157 ex.input(your_data[i]);
158}
159```
160
161### use proper loading api
162
163If you want to load plain param file buffer, you shall use Net::load_param_mem instead of Net::load_param.
164
165For more information about the ncnn model load api, see [ncnn-load-model](ncnn-load-model)
166
167```cpp
168ncnn::Net net;
169
170// param_buffer is the content buffe of XYZ.param file
171net.load_param_mem(param_buffer);
172```
173
174
175### disable fp16
176
177Some models may overflow fp16, resulting in a nan result.
178
179So try to turn off fp16 lower-precision optimizations, and the precision will be improved to fp32 to investigate and solve the overflow problem caused by this.
180
181You can set it as follows
182```cpp
183ncnn::Net net;
184
185net.opt.use_fp16_packed = false;
186net.opt.use_fp16_storage = false;
187net.opt.use_fp16_arithmetic = false;
188```
189
190### make data contiguous
191If you find the output of pnnx.py and ncnn.py (generated by pnnx) is different, This may be due to data discontiguous. You can set the ncnn.py as follows and moditfity other codes:
192``` python
193def test_inference():
194 torch.manual_seed(0)
195 in0 = torch.rand(1, 3, 224, 224, dtype=torch.float)
196 in0.contiguous()
197```