Python:基于FastAPI的映像I/O问题 [英] python: A problem of image i/o based on fastapi
本文介绍了Python:基于FastAPI的映像I/O问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试编写一个基于Fastapi的图像样式转换代码。
我参考了Github和堆栈溢出中的许多文章来编写代码, 我发现将图像的字节转换为Base64并传输它是有效的。
因此,我设计了我的客户端代码被编码为Base64,并发送了一个请求, 我的服务器完美地接收到了它。
但是,我在将图像字节还原为ndarray时遇到了困难。
我的代码告诉我以下错误:
image_array = np.frombuffer(base64.b64decode(image_byte)).reshape(image_shape)
ValueError: cannot reshape array of size 524288 into shape (512,512,4)
这是我的客户端代码:
import base64
import requests
import numpy as np
import json
from matplotlib.pyplot import imread
from skimage.transform import resize
if __name__ == '__main__':
path_to_img = "my image path"
image = imread(path_to_img)
image = resize(image, (512, 512))
image_byte = base64.b64encode(image.tobytes())
data = {"shape": image.shape, "image": image_byte.decode()}
response = requests.get('http://127.0.0.1:8000/myapp/v1/filter/a', data=json.dumps(data))
并且,这是我的服务器代码:
import json
import base64
import uvicorn
import model_loader
import numpy as np
from fastapi import FastAPI
from typing import Optional
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/myapp/v1/filter/a")
async def style_transfer(data: dict):
image_byte = data.get('image').encode()
image_shape = tuple(data.get('shape'))
image_array = np.frombuffer(base64.b64decode(image_byte)).reshape(image_shape)
if __name__ == '__main__':
uvicorn.run(app, port='8000', host="127.0.0.1")
请检查我的代码并给我一些建议。 我真的不知道我错过了什么。
推荐答案
如前所述here和here,应该使用UploadFile从客户端接收文件数据。例如:
服务器端
@app.post("/upload")
async def upload(files: List[UploadFile] = File(...)):
# in case you need the files saved, once they are uploaded
for file in files:
contents = await file.read()
with open(file.filename, 'wb') as f:
f.write(contents)
return {"Uploaded Filenames": [file.filename for file in files]}
客户端
url = 'http://127.0.0.1:8000/upload'
files = [('files', open('images/1.png', 'rb')), ('files', open('images/2.png', 'rb'))]
resp = requests.post(url=url, files = files)
但是,如果您仍然需要发送Base64编码的图像,您可以按照前面介绍的here进行。在客户端,您可以将图像编码为Base64并使用POST请求发送,如下所示:
with open("photo.png", "rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
payload ={"filename": "photo.png", "filedata": encoded_string}
resp = requests.post(url=url, data=payload)
在服务器端,使用Form(...)字段接收图像,并按如下方式解码图像:
@app.post("/upload")
async def upload(filename: str = Form(...), filedata: str = Form(...)):
image_as_bytes = str.encode(filedata) # convert string to bytes
img_recovered = base64.b64decode(image_as_bytes) # decode base64string
with open("uploaded_" + filename, "wb") as f:
f.write(img_recovered)
return filename
这篇关于Python:基于FastAPI的映像I/O问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文