【问题标题】:Receiving an image with Fast API, processing it with cv2 then returning it使用 Fast API 接收图像,使用 cv2 处理它然后返回它
【发布时间】:2020-04-20 23:49:45
【问题描述】:

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

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

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,
    }

【问题讨论】:

  • 您是否在processImage 方法中将图像编码为.png.jpg 压缩格式?
  • 您可以在 fastapi 中发送其他类型的响应,也许 StreamingResponse 或文件响应可能更合适?看看fastapi.tiangolo.com/advanced/custom-response

标签: python opencv fastapi


【解决方案1】:

@ZdaR 的评论帮我做了。我能够通过在将其编码为 base64 字符串之前将其重新编码为 PNG 来使 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)

    # 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,
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-22
    • 1970-01-01
    • 2023-03-15
    • 2020-04-26
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    相关资源
    最近更新 更多