簡體   English   中英

如何將 h5 文件轉換為 tflite 文件?

[英]How to convert just a h5 file to a tflite file?

我正在嘗試在 Android 上運行車牌檢測。 所以首先我找到了這個教程: https : //medium.com/@quangnhatnguyenle/detect-and-recognize-vehicles-license-plate-with-machine-learning-and-python-part-1-detection-795fda47e922順便說一句真的很棒。

在本教程中,我們可以找到wpod-net.h5因此我嘗試使用以下命令將其轉換為 TensorFlow lite:

import tensorflow as tf

model = tf.keras.models.load_model('wpod-net.h5')
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.post_training_quantize = True
tflite_model = converter.convert()
open("wpod-net.tflite", "wb").write(tflite_model)

但是當我運行這個我有這個錯誤:

  File "converter.py", line 3, in <module>
    model = tf.keras.models.load_model('License_character_recognition.h5')
  File "/home/.local/lib/python3.8/site-packages/tensorflow/python/keras/saving/save.py", line 184, in load_model
    return hdf5_format.load_model_from_hdf5(filepath, custom_objects,
  File "/home/.local/lib/python3.8/site-packages/tensorflow/python/keras/saving/hdf5_format.py", line 175, in load_model_from_hdf5
    raise ValueError('No model found in config file.')
ValueError: No model found in config file.

我也嘗試使用 API tflite_convert --keras_model_file=License_character_recognition.h5 --output_file=test.tflite但它給了我同樣的錯誤。

這是否意味着如果我沒有自己訓練模型,我就不能將它轉換為 tflite ? 還是有另一種方法可以轉換 .h5?

TensorFlow Lite 模型結合了權重和模型代碼本身。 您需要加載 Keras 模型(帶權重),然后才能轉換為 tflite 模型。

獲取作者repo的副本,然后執行get-networks.sh 對於車牌檢測器,您只需要data/lp-detector/wpod-net_update1.h5 ,這樣您就可以提前停止下載。

深入研究代碼,您可以在keras utils 中找到准備好的加載模型函數。

獲得模型對象后,可以將其轉換為 tflite。

Python3、TF2.4 測試:

import sys, os
import tensorflow as tf
import traceback

from os.path                    import splitext, basename

print(tf.__version__)

mod_path = "data/lp-detector/wpod-net_update1.h5"

def load_model(path,custom_objects={},verbose=0):
    #from tf.keras.models import model_from_json

    path = splitext(path)[0]
    with open('%s.json' % path,'r') as json_file:
        model_json = json_file.read()
    model = tf.keras.models.model_from_json(model_json, custom_objects=custom_objects)
    model.load_weights('%s.h5' % path)
    if verbose: print('Loaded from %s' % path)
    return model

keras_mod = load_model(mod_path)

converter = tf.lite.TFLiteConverter.from_keras_model(keras_mod)
tflite_model = converter.convert()

# Save the TF Lite model.
with tf.io.gfile.GFile('model.tflite', 'wb') as f:
    f.write(tflite_model)

祝你好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM