使用Fast API接收图像,然后使用cv2处理它,然后将其返回 [英] Receiving an image with Fast API, processing it with cv2 then returning it

查看:246
本文介绍了使用Fast API接收图像,然后使用cv2处理它,然后将其返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个API,该API可以接收图像并对其进行一些基本处理,然后使用Open CV和Fast API返回其更新副本.到目前为止,我的接收器工作正常,但是当我尝试对已处理的图像进行base64编码并将其发送回我的移动前端时,超时了.

I am trying to build an API which receives an image and does some basic processing on it, then returns an updated copy of it using Open CV and Fast API. So far, I have the receiver working just fine, but when I try to base64 encode the processed image and send it back my mobile front end times out.

作为调试实践,我尝试仅打印编码的字符串并使用Insomnia进行API调用,但是在打印数据5分钟后,我终止了该应用程序.返回base64编码的字符串在这里正确吗?有没有更简单的方法可以通过Fast API发送Open CV图像?

As a debugging practice I've tried just printing the encoded string and making the API call using Insomnia, but after 5 solid minutes of printing data I killed the application. Is returning a base64 encoded string the right move here? Is there an easier way to send an Open CV image via Fast API?

class Analyzer(BaseModel):
    filename: str
    img_dimensions: str
    encoded_img: str

@app.post("/analyze", response_model=Analyzer)
async def analyze_route(file: UploadFile = File(...)):
    contents = await file.read()
    nparr = np.fromstring(contents, np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

    img_dimensions = str(img.shape)
    return_img = processImage(img)

    encoded_img = base64.b64encode(return_img)

    return{
        'filename': file.filename,
        'dimensions': img_dimensions,
        'encoded_img': endcoded_img,
    }

推荐答案

@ZdaR的注释对我有用.通过将其重新编码为PNG,然后再将其编码为base64字符串,我能够使API调用正常工作.

@ZdaR 's comment did it for me. I was able to get the API call to work by re-encoding it to a PNG prior to encoding it to a base64 string.

工作代码如下:

class Analyzer(BaseModel):
    filename: str
    img_dimensions: str
    encoded_img: str

@app.post("/analyze", response_model=Analyzer)
async def analyze_route(file: UploadFile = File(...)):
    contents = await file.read()
    nparr = np.fromstring(contents, np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

    img_dimensions = str(img.shape)
    return_img = processImage(img)

    # line that fixed it
    _, encoded_img = cv2.imencode('.PNG', return_img)

    encoded_img = base64.b64encode(encoded_img)

    return{
        'filename': file.filename,
        'dimensions': img_dimensions,
        'encoded_img': endcoded_img,
    }

这篇关于使用Fast API接收图像,然后使用cv2处理它,然后将其返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆