【问题标题】:How to decode a base64 image and getting It's class for my image classification model FastAPI API如何解码 base64 图像并为我的图像分类模型 FastAPI API 获取它的类
【发布时间】:2021-07-06 04:00:00
【问题描述】:

这里是新手。我一直在研究猫狗 API 的图像分类模型。

我有一个模型,即使它不是那么准确,并且我从this tutorial 获得了一个 API,即使它看起来并不花哨,最后的代码基本上就是我的整个 API。

如果您在上传到“post”时使用 jpg 图像或其他常规图像类型,效果会很好。但问题是:我的 API 需要能够接收 base64 编码的图像并从数组中返回我的一个类别,例如:

categories = ['dog', 'cat']

不是教程返回的预测变量 API 那样的数字。

我为base64图像转换找到了这个:

 def base64str_to_PILImage(base64str):
  base64_img_bytes = base64.encode("utf-8")
  base64bytes = base64.b64decode(base64_img_bytes)
  bytesObj = io.BytesIO(base64bytes)
  img = Image.open(bytesObj)
  return img

但我不确定如何将它集成到我的 API 中。我试图将它放在教程中的“读取图像内容”部分,并将 img = Image.open(bytesObj) 更改为:

pil_image = Image.open(bytesObj)
return pil_image

但 FastAPI 响应正文向我返回以下内部服务器错误:

detail": "encode() missing 1 required positional argument: 'output'

我刚刚掌握了编码的基础知识,使用 python 和 API 进行机器学习。但我正在学习,同时尝试构建它并通过这些可爱的小狗预测获得一些乐趣 xD。

你们能帮帮我吗?

【问题讨论】:

    标签: python tensorflow machine-learning base64 fastapi


    【解决方案1】:

    JEZZZ 我做到了。好的,我刚想发个关于它的问题,我突然找到了答案。

    要接收 base64 编码的图像并对其进行解码以便将其传递给您的模型,您必须执行以下操作(假设您有与我类似的 API):

    [...]
    @app.post('/prediction/', response_model=Prediction)
    async def prediction_route(file: UploadFile = File(...)):
    
     try:
       #Read the user posted file
       user_image = await file.read()
    
       #Decode the received file
       base64bytes = base64.b64decode(user_image)
       bytesObj = io.BytesIO(base64bytes)
    
       #Open the (now) image file
       pil_image = Image.open(bytesObj)
    

    现在您可以使用“pil_image”变量对图像做任何您想做的事情。

    哦,为了从“类别”数组变量中获取类,您只需要:

    #Declare it (obviously)
    categories = ["dog", "cat"]
    
    #On your base model you have to put a variable from the type of the response you want
    #in my case is one of my strings from my categories array
    class Prediction(BaseModel):
    predicted_class: str
    [your other base model stuff]
    

    之后:

    [...]
    #use this where you are making your prediction:
    [prediction stuff]
    predicted_class = categories[np.argmax(prediction)]
    

    最后:

    #return the predicted class variable with your other responses from the base model
    return{
      [your other responses stuff]
      "predicted_class" : predicted_class
    

    }

    我知道这没什么大不了的,但我真的很高兴自己找到了这个,我希望能帮助其他人。

    谢谢

    【讨论】:

      猜你喜欢
      • 2013-10-08
      • 1970-01-01
      • 2017-03-20
      • 2013-07-22
      • 1970-01-01
      • 2012-06-21
      • 1970-01-01
      • 2021-10-24
      相关资源
      最近更新 更多