如何解码 base64 图像并获取我的图像分类模型 FastAPI API 的类



这里是新手。我一直致力于猫和狗的图像分类模型API。

我有一个模型,即使它不是那么准确,我从本教程中得到了一个API,即使它看起来不漂亮,最后的代码,基本上就是我的整个API。

如果你在上传到";帖子";。但问题是:我的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玩得很开心。

你们能帮帮我吗?

我做到了。好吧,我只需要发布一个关于它的问题,我突然找到了答案。

要接收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

}

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

感谢

最新更新