用Resnet 模型进行验证
- import numpy as np
- import tensorflow as tf
-
-
-
- physical_devices = tf.config.list_physical_devices('GPU')
- for device in physical_devices: # 使用GPU
- tf.config.experimental.set_memory_growth(device, True)
-
- model = tf.keras.applications.resnet50.ResNet50(weights='imagenet') # 导入resnet 模型
- img = tf.keras.utils.load_img('123.jpg', target_size=[224, 224,3]) # 载入图片并给出size
-
- x = tf.keras.preprocessing.image.img_to_array(img) # 处理输入图片尺寸
- x = np.expand_dims(x, axis=0)
- x = tf.keras.applications.resnet50.preprocess_input(x)
-
-
- preds = model.predict(x) # 预测结果
- # 将结果解码为元组列表 (class, description, probability)
- # (一个列表代表批次中的一个样本)
- print('Predicted:', tf.keras.applications.resnet50.decode_predictions(preds, top=3)[0])
-
-
-
-
-
-
-
-
(1)低级API
存储 tf.saved_model.save (model, path)
这种形式保存以后文件夹是这样的

加载 tf.saved_model.load(path_to_dir)
具体代码如下
- load_model = tf.saved_model.load('resnet50_low_level_save/') # 加载模型
- labeling = load_model(x) #
- imagenet_labels = np.array(open('ImageNetLabels.txt').read().splitlines()) # ImageNetLabels.txt 文件中包含1000个被识别的物体名字列表 和 一个backgroud 所以下面的物体标号是+1
- decoded = imagenet_labels[np.argsort(labeling)[0, ::-1][:3] + 1]
- print(decoded)
(2)高级API
存储 tf.keras.models.save_model(model, path)
这种形式保存以后文件夹是这样的 多了一个keras_metadata.pb的文件

加载 tf.keras.models.save_model(path_to_dir)
具体代码如下
- tf.keras.models.save_model(model, 'resnet50_high_level_save/')
- load_model = tf.keras.models.load_model('resnet50_high_level_save/') # 加载模型
- preds = load_model.predict(x)
- decoded = imagenet_labels[np.argsort(preds)[0, ::-1][:3] + 1]
这种方法好处在于可以继续使用keras 的方法
(1) 低级API
- convert = tf.lite.TFLiteConverter.from_saved_model('resnet50_low_level_save')
- tflite_model = convert.convert()
-
- tflite_model_file = pathlib.Path('resnet50_low_level.tflite')
- tflite_model_file.write_bytes(tflite_model)
(2) 高级API
- convert = tf.lite.TFLiteConverter.from_saved_model('resnet50_high_level_save')
- tflite_model = convert.convert()
-
- tflite_model_file = pathlib.Path('resnet50_high_level.tflite')
- tflite_model_file.write_bytes(tflite_model)
- import numpy as np
- import tensorflow as tf
-
- interpreter = tf.lite.Interpreter(model_path="resnet50_low_level.tflite")
- # Get input and output tensors.
- input_details = interpreter.get_input_details()
- output_details = interpreter.get_output_details()
- interpreter.allocate_tensors()
- imagenet_labels = np.array(open('ImageNetLabels.txt').read().splitlines())
-
-
- ################################### 输入矩阵处理方式 1 ###################################
- img_path = '123.jpg'
- print(np.shape(img_path))
- img = tf.keras.preprocessing.image.load_img(img_path, target_size=(224, 224, 3)) # 输入矩阵处理方式 1
- x = tf.keras.preprocessing.image.img_to_array(img)
- x = np.expand_dims(x, axis=0)
- x = tf.keras.applications.resnet50.preprocess_input(x)
-
-
- print(np.shape(x))
-
- interpreter.set_tensor(input_details[0]['index'], x)
- interpreter.invoke()
- output_data = interpreter.get_tensor(output_details[0]['index'])
-
- decoded = imagenet_labels[np.argsort(output_data)[0, ::-1][:3] + 1]
- print(output_data[:,[np.argsort(output_data)[0, ::-1][:3]]])
- print("Result before saving:\n", decoded)
结果 :

与前面的结果基本一样,所以证明一切正确。
- import numpy as np
- import tensorflow as tf
- import cv2
- interpreter = tf.lite.Interpreter(model_path="resnet50_low_level.tflite")
- # Get input and output tensors.
- input_details = interpreter.get_input_details()
- output_details = interpreter.get_output_details()
- interpreter.allocate_tensors()
- imagenet_labels = np.array(open('ImageNetLabels.txt').read().splitlines())
-
-
- ################################### 输入矩阵处理方式 2 利用Opencv ###################################
- img = cv2.imread("123.jpg")
- new_img = cv2.resize(img, (224, 224))
- new_img = new_img.astype(dtype=np.float32)
- # new_img = tf.cast(new_img , dtype=np.float32)
- x = np.expand_dims(new_img, axis=0)
-
- print(np.shape(x))
-
- interpreter.set_tensor(input_details[0]['index'], x)
- interpreter.invoke()
- output_data = interpreter.get_tensor(output_details[0]['index'])
-
- decoded = imagenet_labels[np.argsort(output_data)[0, ::-1][:3] + 1]
- print(output_data[:,[np.argsort(output_data)[0, ::-1][:3]]])
- print("Result before saving:\n", decoded)
-

从结果看,Opencv 处理的图片,识别效果更好。
只需要把低级API保存的模型,改成高级的。

结论保存结果的形式,对于tflite的结果无影响。
只需要把低级API保存的模型,改成高级的。
