如何在 FastAPI 中渲染 NumPy 图像数组?

Linda Hamilton
发布: 2024-10-24 02:40:02
原创
753 人浏览过

How Do You Render a NumPy Image Array in FastAPI?

在 FastAPI 中渲染 NumPy 数组

而文章“如何使用 FastAPI 将 numpy 数组作为图像返回?”提供有用的信息,但它不直接解决显示图像的问题。为了解决这个问题,让我们更深入地研究底层技术:

选项 1:以字节形式返回图像

此方法需要使用 PIL 或 OpenCV 等库将图像数据转换为字节。然后,生成的字节可以用作具有适当内容类型和标头的自定义响应。

使用 PIL:

<code class="python">from PIL import Image
import io

@app.get('/image', response_class=Response)
def get_image():
    im = Image.open('test.png')
    with io.BytesIO() as buf:
        im.save(buf, format='PNG')
        im_bytes = buf.getvalue()
    headers = {'Content-Disposition': 'inline; filename=&quot;test.png&quot;'}
    return Response(im_bytes, headers=headers, media_type='image/png')</code>
登录后复制

使用 OpenCV:

<code class="python">import cv2

@app.get('/image', response_class=Response)
def get_image():
    arr = cv2.imread('test.png', cv2.IMREAD_UNCHANGED)
    success, im = cv2.imencode('.png', arr)
    headers = {'Content-Disposition': 'inline; filename=&quot;test.png&quot;'}
    return Response(im.tobytes(), headers=headers, media_type='image/png')</code>
登录后复制

选项 2:将图像返回为 JSON 编码的 NumPy 数组

虽然不建议使用此方法显示图像,但它可以用于将图像转换为 JSON 编码numpy 数组,稍后可以在客户端转换回图像。

使用 PIL:

<code class="python">from PIL import Image
import numpy as np

@app.get('/image')
def get_image():
    im = Image.open('test.png')
    arr = np.asarray(im)
    return json.dumps(arr.tolist())</code>
登录后复制

使用 OpenCV:

<code class="python">import cv2

@app.get('/image')
def get_image():
    arr = cv2.imread('test.png', cv2.IMREAD_UNCHANGED)
    return json.dumps(arr.tolist())</code>
登录后复制

要使用此方法显示图像,您需要在客户端将接收到的字节或 JSON 编码数据转换回图像格式。

以上是如何在 FastAPI 中渲染 NumPy 图像数组?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!