使用 Fast API 接收图像,使用 cv2 处理然后返回

epi*_*icz 5 python opencv fastapi

我正在尝试构建一个 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,
    }
Run Code Online (Sandbox Code Playgroud)

epi*_*icz 9

@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,
    }
Run Code Online (Sandbox Code Playgroud)