import tensorflow as tf from tensorflow.keras.preprocessing import image from tensorflow.keras.applications.mobilenet_v2 import preprocess_input, decode_predictions import numpy as np import gradio as gr # 加载 MobileNetV2 模型 # model = tf.keras.applications.MobileNetV2(weights='imagenet') # model.save('D:/ai/model') model = tf.keras.models.load_model('./MobileNetV2.h5') model.summary() # from tensorflow.keras.models import load_model # loaded_model.save('D:\\ai\\h5\\MobileNetV2.h5') import cv2 # 定义图片分类函数 def classify_image(img): # 将 Gradio 上传的图片数据转换为 NumPy 数组 img = cv2.resize(img,(224,224)) img_array = image.img_to_array(img) img_array = np.expand_dims(img_array, axis=0) img_array = preprocess_input(img_array) # # 使用模型进行分类 predictions = model.predict(img_array) decoded_predictions = decode_predictions(predictions, top=3)[0] # 构建结果字符串 results = [f"{i + 1}: {label} ({score:.2f})" for i, (_, label, score) in enumerate(decoded_predictions)] # return "There run successfully" return "\n".join(results) # 构建Gradio 界面 iface = gr.Interface(fn=classify_image, inputs=gr.Image(), outputs="text") # 启动 Gradio 界面 iface.launch(share=True) share_link = iface.share() print("Share this link: ", share_link)