天天看點

MTCNN、FaceNet轉tflite模型,遷移至安卓使用(2)Methods A:Methods B:

這篇文章介紹将Tensorflow的ckpt模型,"當機”為pb模型,和一些我經過的“坑”。

上面部落格已經介紹了Tensorflow的幾種模型的定義和關系。傳送門:https://blog.csdn.net/qq_17721239/article/details/89295209

facecnet的模型中已經提供當機圖的程式,之前沒有發現,導緻耽擱了很長時間。這裡介紹兩種方法當機變量,生成pb模型。

Methods A:

使用bazel工具編譯tensorflow源碼。

1、首先下載下傳bazel編譯工具:https://docs.bazel.build/versions/master/install.html 我使用的ubuntu18.04:

step1:install require packages

sudo apt-get install pkg-config zip g++ zlib1g-dev unzip python
           

step2:download bazel

    下載下傳bazel-<version>-installer-linux-x86_64.sh檔案,從github連結。我下載下傳最新的總是失敗,我就下載下傳次最新的。

step3:run the installer

chmod +x bazel-<version>-installer-linux-x86_64.sh
./bazel-<version>-installer-linux-x86_64.sh --user
           

step 4:set up your environment

export PATH="$PATH:$HOME/bin"
           

注意:如果把bazel-<version>-installer-linux-x86_64.sh放入目錄有中文的路徑下,會報錯(Use the binary installer(recommended)),使用全英文路徑

2、下載下傳tensorflow源碼

mkdir tf2019
cd tf2019
git clone https://github.com/tensorflow/tensorflow.git
           

   進入tensorflow目錄,編譯生成freeze_graph和toco工具。最新版本toco替換成tflite_convert工具

cd tensorflow
bazel build tensorflow/python/tools:freeze_graph
bazel build tensorflow/lite/toco:toco
           

注意:推介在性能好一點的機器上運作,記憶體大一點,不然會卡死。編譯時ctrl+Alt+T打開終端,輸入gnome-system-monitor可以監控CPU,記憶體和swap記憶體。會發現,在編譯某一項的時候,記憶體占到99%(我的是4G記憶體),然後使用交換記憶體。直至卡死。

解決方法:

cd tensorflow
bazel build -c opt --jobs 1 --local_resources 2048,0.5,1.0 tensorflow/python/tools:freeze_graph
bazel build -c opt --jobs 1 --local_resources 2048,0.5,1.0 tensorflow/lite/toco:toco
           

這裡限制了記憶體和線程,會使得編譯速度非常慢。也可能卡死。我查的資料,swap記憶體使用後不會自動清理。手動清理的辦法是,進入root模式,再輸入指令。

sudo su
swapoff -a
swapon -a
           

知道編譯success。

3、在終端中繼續輸入下面指令。

bazel-bin/tensorflow/python/tools/freeze_graph \
  --input_graph=./model.pb \                       輸入模型的圖
  --input_checkpoint=./model.ckpt \                輸入模型的ckpt檔案
  --output_graph=./frozen_model.pb \               輸出模型的路徑
  --input_binary=true \
  --output_node_names=result                       輸出結點的名字 facenet是embeddings
           

分别帶入的模型路徑和,輸出的檔案名。至此得到當機了變量的模型,frozen.pb檔案

Methods B:

使用代碼生成。

首先下載下傳fecenet的源碼

git clone https://github.com/davidsandberg/facenet.git
           

 發現facenet/src/ 下面有freeze_graph.py檔案。

def parse_arguments(argv):
    parser = argparse.ArgumentParser()
    
    parser.add_argument('model_dir', type=str, 
        help='Directory containing the metagraph (.meta) file and the checkpoint (ckpt) file containing model parameters')
    parser.add_argument('output_file', type=str, 
        help='Filename for the exported graphdef protobuf (.pb)')
    return parser.parse_args(argv)
           

直接cd 到此目錄

python freeze_graph.py 20180402-114759 frozen.pb
           

至此得到當機了變量的模型,frozen.pb檔案