距離真正完成表情辨識的App,
只差把辨識圖像的功能實作出來,
在這裡我們必須將Day21存好的TFLite模型拿出來,
製作出含有metadata的TFLite模型。
我把"effB0_fer.tflite"加入metadata後,
另存為"effB0_fer_meta.tflite"。
# %% 生成 model metadata
from tflite_support.metadata_writers import writer_utils
from tflite_support.metadata_writers import image_classifier
ImageClassifierWriter = image_classifier.MetadataWriter
_MODEL_PATH = "./models/effB0_fer.tflite"
_LABEL_FILE = "./data/FER2013_labels.txt"
_SAVE_TO_PATH = "./models/effB0_fer_meta.tflite"
_INPUT_NORM_MEAN = 0
_INPUT_NORM_STD = 1
# Create the metadata writer.
writer = ImageClassifierWriter.create_for_inference(
writer_utils.load_file(_MODEL_PATH), [_INPUT_NORM_MEAN], [_INPUT_NORM_STD],
[_LABEL_FILE])
# Verify the metadata generated by metadata writer.
print(writer.get_metadata_json())
# Populate the metadata into the model.
writer_utils.save_file(writer.populate(), _SAVE_TO_PATH)
這邊唯一有需要自己決定的只有_INPUT_NORM_MEAN
和_INPUT_NORM_STD
,
這兩個變數的數值決定於我們輸入圖片矩陣的時候有無做正規化,
因為我是將[0. ~ 255.]直接丟入模型,所以設mean = 0, std = 1。
官網原文:
Normalization is a common data preprocessing technique in machine learning. The goal of normalization is to change the values to a common scale, without distorting differences in the ranges of values.
在app
上按滑鼠右鍵,最後點擊tensorflow lite model
。
選擇已訓練model的位置進行import,按下finish進行import。(不建議勾gpu選項)
等待1分鐘後,可以看到菜單左欄位多出ml
資料夾。
ml
資料夾下有我們的tflite model,可以點開他查看(這邊記錄了input shape和scale range)
呼叫模型的程式碼
val model = Effb0FerMeta.newInstance(context)
// Creates inputs for reference.
val image = TensorImage.fromBitmap(bitmap)
// Runs model inference and gets result.
val outputs = model.process(image)
val probability = outputs.probabilityAsCategoryList
// Releases model resources if no longer used.
model.close()
終於把模型放進去了,
現在只差把 2.5 (呼叫模型的程式碼)的程式碼實作成function加入MainActivity.kt了!
明天再見~