""" 使用VGG16模型测试图片识别 20221116 byp 程序来源:https://blog.csdn.net/java_raylu/article/details/123536858 注意:keras提示有红色波浪线,但是程序依然可以执行 增加前3种预测结果 """ from tensorflow.keras import applications from tensorflow.keras import applications # decode_predictions 对预测结果进行处理,解码 from tensorflow.keras.applications.vgg16 import decode_predictions # preprocess_input处理输入图片 from tensorflow.keras.applications.vgg16 import preprocess_input from tensorflow import keras from tensorflow.keras.preprocessing.image import img_to_array from tensorflow.keras.preprocessing.image import load_img # VGG 图片输入大小要求 224*224*3 # VGG 有1.4亿个参数 # 获取已训练好的模型 def predict(my_model, images): y_lables = [] for image in images: y_predictions = my_model.predict(image) # print(y_predictions) y_lable = decode_predictions(y_predictions) y_lables.append(y_lable) return y_lables # 图片读取处理 def load_img1(files_path): images = [] # 加载图片 for path in files_path: image = load_img(path, target_size=(224, 224)) # 图片进行数组转换 image = img_to_array(image) print('-----') print(image.shape) # 形状修改,输入到卷积需要四维[1,224,224,3],1代表batch,如果多张图片就使用多张 image = image.reshape(1, image.shape[0], image.shape[1], image.shape[2]) print(image.shape) # print(image) # 对图片进行归一化处理 images.append(preprocess_input(image)) return images # 输入到模型进行预测 if __name__ == '__main__': import os # 获取当前路径 path = os.getcwd() files = os.listdir(os.path.join(path, "tiger")) file_count = len(files) print(file_count) files_path = [] for i in range(file_count): print(i) files_path.append(os.path.join(path, 'tiger', files[i])) print(files_path) my_model = applications.vgg16.VGG16() images = load_img1(files_path) print('123') y_predicts = predict(my_model, images) print(y_predicts) i = 0 for y_predict in y_predicts: i = i + 1 print('图片', i, '预测结果是:%s,%.2f' % (y_predict[0][0][1], y_predict[0][0][2] * 100), "%;", '%s,%.2f' % (y_predict[0][1][1], y_predict[0][1][2] * 100), "%;", '%s,%.2f' % (y_predict[0][2][1], y_predict[0][2][2] * 100), "%")