這幾天做了基于MobileNet的一個(gè)身份證區(qū)域分割的語(yǔ)義分割小網(wǎng)絡(luò),需要部署到移動(dòng)端,就研究了一下NCNN和MNN,發(fā)現(xiàn)NCNN對(duì)ONNX一些操作的支持不是很好,resize需要自己寫接口修改結(jié)構(gòu),就被勸退直接投入MNN。
不得不說二者都是很友好的深度學(xué)習(xí)部署工具,維護(hù)快速、有文檔也有中文社區(qū),而且優(yōu)化也徹底,充分發(fā)揮移動(dòng)端的運(yùn)算潛力。
沒有安卓開發(fā)經(jīng)驗(yàn)/C++不太熟練,遇到了一些問題:
- 使用移動(dòng)端Opencv的時(shí)候(我這里最開始是OpenCV-android-sdk 3.4),
undefined reference to `cv::imwrite(cv::String const&, cv::_InputArray const&, std::__ndk1::vector<int, std::__ndk1::allocator<int> > const&)'
這個(gè)問題可能是因?yàn)槟愕腛pencv是用gnustl編譯的,但是NDK改用了 libc++,導(dǎo)致Jni編譯報(bào)錯(cuò),驗(yàn)證一下可以打開與CMakeList.txt同級(jí)的build.gradle,里面會(huì)有"-DANDROID_STL=c++_shared"。
問題解決來(lái)自這里,三種方法:要么把項(xiàng)目STL改為"-DANDROID_STL=gnustl_shared"(可能出問題),要么把Opencv用c++_shared編譯,再或者下載最新的Opencv4.0.x庫(kù),它已經(jīng)支持 NDK r.18+。在這里建議使用4.0.x。 -
ninja: build stopped: subcommand failed. error: use of undeclared identifier 'CV_BGR2RGBA'
這個(gè)問題是比較新的Opencv版本中,CV_BGR2GRAY等參數(shù)已改為COLOR_BGR2GRAY類似形式。
解決:include "opencv2/imgproc.hpp"然后把參數(shù)按文件中的命名規(guī)則替換 - 轉(zhuǎn)換tensorflow/ Keras模型
Converte Tensorflow's Op batch_normalization_16/cond/FusedBatchNorm , type = FusedBatchNorm, failed, may be some node is not const Segmentation fault (core dumped)BN層沒凍住,也就是沒有保存訓(xùn)練中的均值方差。
解決:tensorflow中設(shè)置BN層的is_training=False,Keras中x = BatchNormalization()(y, training=False) - 沒有進(jìn)行NCHW與NHWC格式轉(zhuǎn)換,導(dǎo)致圖片交換了維度,輸出結(jié)果變成九宮格或者完全錯(cuò)誤。
解決在MNN中,可以直接復(fù)制Tensor來(lái)進(jìn)行對(duì)圖片進(jìn)行維度交換,即python中的numpy.transpose(),在這里有說明:
格式轉(zhuǎn)換
以O(shè)pencv的HWC(高、寬、通道)格式為例,可以先根據(jù)同樣NHWC格式的TensorFlow Tensor讀進(jìn)來(lái),再?gòu)?fù)制到NCHW格式的Caffe Tensor中,自動(dòng)完成了轉(zhuǎn)換:
const std::vector<int> inputDims1 = {1, size_img, size_img, 3};
auto nchwTensor_1 = MNN::Tensor::create<float32_t >(inputDims1, pImg.data, MNN::Tensor::TENSORFLOW);
g_input_1->copyFromHostTensor(nchwTensor_1);
g_input_1 = new Tensor(g_input_1, Tensor::CAFFE); //如果網(wǎng)絡(luò)的輸入g_input_1本來(lái)就是CAFFE格式,那也不同加這句,會(huì)自動(dòng)轉(zhuǎn)換
5.Keras->TensorFlow模型轉(zhuǎn)換
Start to Convert Other Model Format To MNN Model...
Start to Optimize the MNN Net...
Segmentation fault (core dumped)
首先確認(rèn)參數(shù)有沒有加載成功,Batch Normalization有沒有凍住,Drop out有沒有置0,以及定義網(wǎng)絡(luò)的輸入是不是定義了size:input = Input( shape=(img_h, 280, 1), name='the_input'),在這里如果是定義batch_size的話也會(huì)轉(zhuǎn)換失敗。
解決:確認(rèn)以上問題,記得在編譯MNNConvert時(shí)在ools/converter/CMakeLists.txt中打開[TFMODEL_OPTIMIZE]
- 把輸入圖像按照制定寬進(jìn)行等比縮放并pad0:
首先 把config里的wrap調(diào)成0填充:
ImageProcess::Config config_data;
config_data.filterType = BILINEAR;
config_data.wrap=ZERO;
const float mean_vals[1] = {mean_val};
const float norm_vals[1] = {std_val};
::memcpy(config_data.mean, mean_vals, sizeof(mean_vals));
::memcpy(config_data.normal, norm_vals, sizeof(norm_vals));
config_data.sourceFormat = GRAY;
config_data.destFormat = GRAY;
然后設(shè)置矩陣,寬度為按比例賦值:
int width = img.cols;
int height = img.rows;
int tp = img.type();
auto dims = o_input->shape();
int bpp = dims[1];
int size_h = dims[2];
int size_w = dims[3];
MNN::CV::Matrix trans;
auto s = 1.0*width/height*size_h;
trans.postScale(1.0f/s, 1.0f/size_h);
trans.postScale(width, height);
pretreat_data->setMatrix(trans);
pretreat_data->convert(img.data, width, height, 0, input);
- 編譯后的安卓libmnn.so或ibmnn.a太大(大于50mb):
解決:$ANDROID_NDK/build/cmake/android.toolchain.cmake 里去掉編譯選項(xiàng)-g,然后重新編譯。 - 友情贈(zèng)送 語(yǔ)義分割的C++ ArgMax與外接矩形操作(改自網(wǎng)絡(luò)):
typedef struct BBox {
float xmin;
float ymin;
float xmax;
float ymax;
}
// 數(shù)組最大值下標(biāo)
template<class ForwardIterator>
inline int argmax(ForwardIterator first, ForwardIterator last) {
return std::distance(first, std::max_element(first, last));
}
static BBox post_process(cv::Mat img,const int size_img, const int w, const int h)
{
// argmax
cv::Mat out = cv::Mat::zeros(size_img, size_img, CV_8U);
for (int h = 0; h < size_img; ++h) {
for (int w = 0; w < size_img; ++w) {
float_t *p = (float_t *)img.ptr(h, w); // prob of a point
out.at<uint8_t>(h, w) = (uint8_t) argmax(p, p + 3);
}
}
//
std::vector< std::vector< cv::Point> > contours;
cv::findContours(
out,
contours,
cv::noArray(),
CV_RETR_TREE,
cv::CHAIN_APPROX_SIMPLE
);
cv::Rect boundRect;
boundRect = cv::boundingRect(cv::Mat(contours[0]));
BBox box;
auto scale_x = 1.0*w/size_img;
auto scale_y = 1.0*h/size_img;
box.xmin = static_cast<int>(boundRect.x*scale_x);
box.ymin = static_cast<int>(boundRect.y*scale_y);
box.xmax = static_cast<int>((boundRect.x+boundRect.width)*scale_x);
box.ymax = static_cast<int>((boundRect.y+boundRect.height)*scale_y);
return box;
