【问题标题】:How do you pass in an image through a template and use a model to predict with FastAPI?如何通过模板传入图像并使用模型通过 FastAPI 进行预测?
【发布时间】:2021-11-11 22:16:47
【问题描述】:

我正在尝试创建一个机器学习 Web 应用程序。我有一个接收图像(jpg 或 png)的 html 页面,我正在将模型加载到 API 中以预测图像和输出结果。 FastAPI 的预测功能下的行在单独的文件中工作,但我认为 API 采用的数据格式有问题。

from starlette.responses import RedirectResponse
from fastapi.staticfiles import StaticFiles
from fastapi import FastAPI, Form
from tensorflow.keras import preprocessing
from keras.models import load_model
import numpy as np
import uvicorn

app = FastAPI()
app.mount("/Templates", StaticFiles(directory="Templates"), name="Templates")

model_dir = 'F:\\Saved-Models\\Dog-Cat-Models\\First_Generation_dog_cat_optuna.h5'
model = load_model(model_dir)


@app.get('/')
async def index():
    return RedirectResponse(url="/Templates/index.html")


@app.post('/prediction_page')
async def prediction_form(dogcat_img: bytes = Form(...)):
    pp_dogcat_image = preprocessing.image.load_img(dogcat_img, target_size=(150, 150))
    pp_dogcat_image_arr = preprocessing.image.img_to_array(pp_dogcat_image)
    input_arr = np.array([pp_dogcat_image_arr])
    prediction = np.argmax(model.predict(input_arr), axis=-1)
    print(prediction)


if __name__ == '__main__':
    uvicorn.run(app, host='localhost', port=8000)

我得到的错误:

FileNotFoundError: [Errno 2] No such file or directory: b'cat.83.jpg'

它不应该需要完整路径,因为图像正在通过网页传递,对吗?我也尝试过 UploadFile 而不是 bytes 并收到此错误:

INFO:     ::1:6918 - "POST /prediction_page HTTP/1.1" 422 Unprocessable Entity

编辑: HTML 代码:

<form action="/prediction_page" method="post">
        <label for="image-upload" class="custom-file-upload">Select Image:</label>
        <input type="file" id="image-upload" name="dogcat_img"><br>
        <input class="custom-submit-button" type="submit">
    </form>

【问题讨论】:

    标签: python api tensorflow keras fastapi


    【解决方案1】:

    使用async def prediction_form(dogcat_img: bytes = File(...)): 如果你想获取字节数据。

    在您的情况下: pp_dogcat_image = preprocessing.image.load_img(dogcat_img, target_size=(150, 150)) 似乎这一行将从本地文件路径加载文件。所以我建议你使用UploadFile 类型而不是字节。 你的功能是这样的:

    # ...
    from fastapi import File, UploadFile
    # ...
    
    async def prediction_form(dogcat_img: UploadFile = File(...)):
        # ...
        pp_dogcat_image = preprocessing.image.load_img(dogcat_img.file_name, target_size=(150, 150))
    
    
    

    【讨论】:

    • 所以我实际上之前尝试过,它给了我这个错误:INFO: ::1:6918 - "POST /prediction_page HTTP/1.1" 422 Unprocessable Entity。我试图在招摇的 UI 中寻找一些有用但没用的东西
    • 如果您在 swagger UI 上进行测试,那么请求内容类型应该是 multipart/form-data 符合预期。试试async def prediction_form(*, dogcat_img: UploadFile = File(...)):
    • 是的,试过了,仍然得到无法处理的实体......
    猜你喜欢
    • 2021-07-15
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多