RUN ENV
- tf-1.12.3: import tensorflow as tf
- tf-1.15.2: import tensorflow as tf
- tf-2.1.0: import tensorflow.compat.v1 as tf
Functions
- 加载ckpt模型
- ckpt->SavedModel
- ckpt->Frozen Grapha
with tf.Graph.as_default(), tf.Session() as sess: input_shape = [1, height, width, 3] inputs = tf.placeholder(name='input', dtype=tf.float32, shape=input_shape) outputs = build_model(inputs, is_training=False) checkpoint = tf.train.latest_checkpoint(ckpt_path) ## TODO checkpoint = 'xxx' print('Loading checkpoint: %s', checkpoint) saver.restore(sess, checkpoint) output_node_names = [node.name.split(':')[0] for node in outputs] ## export SavedModel saved_model_name = './tmp/saved_model' tf.saved_model.simple_save(sess, saved_model_name, inputs={'input': inputs}, outputs={output_node_names[0]: outputs[0], output_node_names[1]: outputs[1], output_node_names[2]: outputs[2], output_node_names[3]: outputs[3], output_node_names[4]: outputs[4], output_node_names[5]: outputs[5], output_node_names[6]: outputs[6], output_node_names[7]: outputs[7], output_node_names[8]: outputs[8], output_node_names[9]: outputs[9]}) ## export frozen graph pbtxt_name = './tmp/pb_model/efficientdet_d0.pbtxt' pb_model_name = './tmp/pb_model/efficientdet_d0.pb' tf.train.write_graph(sess.graph_def, '', pbtxt_name, as_text=True) input_graph_def = tf.get_default_graph().as_graph_def() output_graph_def = tf.graph_util.convert_variables_to_constants(sess, sess.graph_def, # input_graph_def, output_node_names) with tf.io.gfile.GFile(pb_model_name, "wb") as f: f.write(output_graph_def.SerializeToString())
RUN ENV
- tf-1.12.3: import tensorflow as tf
- tf-1.15.2: import tensorflow as tf
- tf-2.1.0: import tensorflow.compat.v1 as tf
Functions
- SavedModel->float32 tflite
- SavedModel->int8 tflite
# 以来模型文件是基于哪个环境构建的,高版本中有些ops低版本不支持import sysif sys.version_info.major >= 3: import pathlibelse: import pathlib2 as pathlib tflite_model_dir = pathlib.Path('./tmp/tflite/efficentdet_d0/')tflite_model_dir.mkdir(exist_ok=True, parents=True)tflite_model_name = 'efficentdet_d0_flot32.tflite'tflite_model_file = tflite_model_dir/tflite_model_nameconverter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]tflite_model = converter.convert()tflite_model_file.write_bytes(tflite_model)## export tflite: SavedModel to tflite_int8# tf_1.15.2: import tensorflow as tf# tf_2.1: import tensorflow as tf# tf_2.1: import tensorflow.compat.v1 as tf# 以来模型文件是基于哪个环境构建的,高版本中有些ops低版本不支持import sysif sys.version_info.major >= 3: import pathlibelse: import pathlib2 as pathlib tflite_model_dir = pathlib.Path('./tmp/tflite/efficentdet_d0/')tflite_model_dir.mkdir(exist_ok=True, parents=True)tflite_model_name = 'efficentdet_d0_int8.tflite'tflite_model_file = tflite_model_dir/tflite_model_nameconverter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)data_path = './sample_imgs/*'data = glob.glob(data_path)print('Convert using full integer quantization ...')print("Calibration data size : ", len(data))def aspect_preserving_resize(img, _network_w, _network_h): orig_height, orig_width, _ = img.shape if orig_width > orig_height: resize_ratio = 1.0 * _network_w / orig_width target_size = (_network_w, int(resize_ratio * orig_height)) else: resize_ratio = 1.0 * _network_h / orig_height target_size = (int(resize_ratio * orig_width), _network_h) img = cv2.resize(img, target_size, interpolation=cv2.INTER_AREA) ## Pad image and label to have dimensions >= [crop_height, crop_width] image_height = target_size[1] image_width = target_size[0] bottom = max(_network_h - image_height, 0) right = max(_network_w - image_width, 0) # Pad image with mean pixel value. color = [127.5,127.5,127.5]#[0.0,0.0,0.0]# img = cv2.copyMakeBorder(img, 0, bottom, 0, right, cv2.BORDER_CONSTANT,value=color) return imgdef representative_data_gen(): for idx in range(len(data)): img = cv2.cvtColor(cv2.imread(data[idx]), cv2.COLOR_BGR2RGB) img = aspect_preserving_resize(img, 512, 512) img = np.float32(img - 127.5) * 2.0 / 255.0 input_value = np.expand_dims(img, axis=0) yield [input_value]image_size = [512, 512]def representative_dataset_gen(): for idx in range(len(data)): image = cv2.imread(data[idx]) image_ori = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image = np.float32((image_ori /255.0 - [0.485, 0.456, 0.406]) / [0.229, 0.224, 0.225]) _crop_offset_y = 0 _crop_offset_x = 0 height, width = image.shape[0], image.shape[1] image_scale_y = 512 * 1.0 / height image_scale_x = 512 * 1.0 / width image_scale = np.minimum(image_scale_x, image_scale_y) scaled_height = int(height * image_scale) scaled_width = int(width * image_scale) scaled_image = cv2.resize(image, (scaled_width, scaled_height), cv2.INTER_LINEAR) padding_value = (0.0, 0.0, 0.0) bottom = max(512 - scaled_height, 0) right = max(512 - scaled_width, 0) padding_img = cv2.copyMakeBorder(scaled_image, 0, bottom, 0, right, cv2.BORDER_CONSTANT, value=padding_value) # padding_img = np.float32(padding_img / 255.0) # padding_img = np.float32((padding_img - [0.485, 0.456, 0.406]) / [0.229, 0.224, 0.225]) input_value = np.expand_dims(padding_img, 0) yield [input_value]converter.representative_dataset = representative_dataset_genconverter.optimizations = [tf.lite.Optimize.DEFAULT]# converter.inference_input_type = tf.uint8# converter.inference_output_type = tf.uint8# converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]tflite_model = converter.convert()tflite_model_file.write_bytes(tflite_model)## export tflite: pb model to tflite_flot32# tf_1.15.2: import tensorflow as tf# tf_2.1: import tensorflow as tf# tf_2.1: import tensorflow.compat.v1 as tfimport tensorflow.compat.v1 as tfpb_model_name = './tmp/pb_model/efficientdet_d0.pb'tflite_model_name = './tmp/tflite/efficientdet_d0_flot32.tflite' inputs=["input"] classes=["class_net/class-predict/BiasAdd", 'class_net/class-predict_1/BiasAdd', 'class_net/class-predict_2/BiasAdd', 'class_net/class-predict_3/BiasAdd', 'class_net/class-predict_4/BiasAdd', 'box_net/box-predict/BiasAdd', 'box_net/box-predict_1/BiasAdd', 'box_net/box-predict_2/BiasAdd', 'box_net/box-predict_3/BiasAdd', 'box_net/box-predict_4/BiasAdd'] #模型文件的输出节点名称converter = tf.contrib.lite.TocoConverter.from_frozen_graph(pb_model_name, inputs, classes)tflite_model=converter.convert()open(tflite_model_name, 'wb').write(tflite_model)