這幾天做了基于MobileNet的一個身份證區域分割的語義分割小網絡,需要部署到移動端,就研究了一下NCNN和MNN,發現NCNN對ONNX一些操作的支持不是很好,resize需要自己寫接口修改結構,就被勸退直接投入MNN。
不得不說二者都是很友好的深度學習部署工具,維護快速、有文檔也有中文社區,而且優化也徹底,充分發揮移動端的運算潛力。
沒有安卓開發經驗/C++不太熟練,遇到了一些問題:
- 使用移動端Opencv的時候(我這里最開始是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&)'
這個問題可能是因為你的Opencv是用gnustl編譯的,但是NDK改用了 libc++,導致Jni編譯報錯,驗證一下可以打開與CMakeList.txt同級的build.gradle,里面會有"-DANDROID_STL=c++_shared"
。
問題解決來自這里,三種方法:要么把項目STL改為"-DANDROID_STL=gnustl_shared"
(可能出問題),要么把Opencv用c++_shared編譯,再或者下載最新的Opencv4.0.x庫,它已經支持 NDK r.18+。在這里建議使用4.0.x。 -
ninja: build stopped: subcommand failed. error: use of undeclared identifier 'CV_BGR2RGBA'
這個問題是比較新的Opencv版本中,CV_BGR2GRAY等參數已改為COLOR_BGR2GRAY類似形式。
解決:include "opencv2/imgproc.hpp"然后把參數按文件中的命名規則替換 - 轉換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層沒凍住,也就是沒有保存訓練中的均值方差。
解決:tensorflow中設置BN層的is_training=False
,Keras中x = BatchNormalization()(y, training=False)
- 沒有進行NCHW與NHWC格式轉換,導致圖片交換了維度,輸出結果變成九宮格或者完全錯誤。
解決在MNN中,可以直接復制Tensor來進行對圖片進行維度交換,即python中的numpy.transpose(),在這里有說明:
格式轉換
以Opencv的HWC(高、寬、通道)格式為例,可以先根據同樣NHWC格式的TensorFlow Tensor讀進來,再復制到NCHW格式的Caffe Tensor中,自動完成了轉換:
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); //如果網絡的輸入g_input_1本來就是CAFFE格式,那也不同加這句,會自動轉換
5.Keras->TensorFlow模型轉換
Start to Convert Other Model Format To MNN Model...
Start to Optimize the MNN Net...
Segmentation fault (core dumped)
首先確認參數有沒有加載成功,Batch Normalization有沒有凍住,Drop out有沒有置0,以及定義網絡的輸入是不是定義了size:input = Input( shape=(img_h, 280, 1), name='the_input')
,在這里如果是定義batch_size的話也會轉換失敗。
解決:確認以上問題,記得在編譯MNNConvert時在ools/converter/CMakeLists.txt中打開[TFMODEL_OPTIMIZE]
- 把輸入圖像按照制定寬進行等比縮放并pad0:
首先 把config里的wrap調成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;
然后設置矩陣,寬度為按比例賦值:
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 里去掉編譯選項-g,然后重新編譯。 - 友情贈送 語義分割的C++ ArgMax與外接矩形操作(改自網絡):
typedef struct BBox {
float xmin;
float ymin;
float xmax;
float ymax;
}
// 數組最大值下標
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;