from fastapi import FastAPI, UploadFile, File from pydantic import BaseModel import cv2 import numpy as np import tensorflow as tf
# Load the pre-trained TensorFlow model model = tf.keras.models.load_model('./model')
# Define the class labels for the model predictions class_labels = ["health", "Ecoli", "rotavirus", "coronavirus"]
# Define the target size for image resizing img_height = 224 img_width = 224
# Initialize the FastAPI application app = FastAPI()
# Define the prediction response model classPrediction(BaseModel): filename: str prediction: str
# Define the prediction endpoint @app.post("/predict", response_model=Prediction) asyncdefpredict(file: UploadFile = File(...)): # Read the uploaded image file contents = await file.read() # Convert the image file to a NumPy array np_img = np.frombuffer(contents, np.uint8) # Decode the image from the NumPy array img = cv2.imdecode(np_img, cv2.IMREAD_COLOR) # Resize the image to the target size img = cv2.resize(img, (img_height, img_width)) # Convert the image to a NumPy array img_array = np.array(img) # Ensure the image array is of type uint8 img_array = img_array.astype(np.uint8) # Expand dimensions to match the model's input shape img_array = np.expand_dims(img_array, axis=0)
# Make a prediction using the model predictions = model.predict(img_array)
# Get the index of the highest probability class predicted_class_index = np.argmax(predictions[0]) # Map the index to the corresponding class label predicted_class = class_labels[predicted_class_index]
# Return the prediction result return Prediction(filename=file.filename, prediction=predicted_class)
# Run the FastAPI application if __name__ == "__main__": import uvicorn
# Start the Uvicorn server to serve the FastAPI application uvicorn.run(app='main:app', host="127.0.0.1", port=8000)
然后在终端运行如下指令:
1
uvicorn main:app --reload
即可启动
Request测试代码
提供一个request.py的demo代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
import requests
# Define the URL of the FastAPI prediction endpoint url = "http://127.0.0.1:8000/predict"
# Path to the image file you want to upload image_path = "./img/111.jpg"
# Open the image file in binary mode withopen(image_path, "rb") as image_file: # Prepare the files dictionary with the image file files = {"file": image_file}
# Send a POST request to the FastAPI endpoint response = requests.post(url, files=files)
# Print the response from the server print(response.json())