我建议您首先.h5
使用此存储库将 yolov4 权重转换为 keras 权重。
获得.h5
权重后,您可以使用此代码将 keras 模型转换为 tflite。
import tensorflow.compat.v1 as tf
import numpy
import cv2
def representative_dataset_gen():
num_calibration_steps = 100 # should be a subset of your dataset size
imgs = []
batch_size = 1
for _ in range(num_calibration_steps):
img = cv2.imread(img_file)
img = img / 255.0
img = img.astype(np.float32)
imgs.append(img)
imgs = np.array(imgs)
images = tf.data.Dataset.from_tensor_slices(imgs).batch(1)
for i in images.take(batch_size):
yield [i]
converter = tf.lite.TFLiteConverter.from_keras_model_file("path_to_h5_weights")
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.int8 # or tf.uint8
converter.inference_output_type = tf.int8 # or tf.uint8
converter.representative_dataset = representative_dataset_gen
tflite_model = converter.convert()
# Save the model.
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
来源 - Tensorflow 量化
tflite 转换
生成有代表性的数据集