首页  >  文章  >  后端开发  >  如何使用 FastAPI 将 NumPy 数组作为图像返回?

如何使用 FastAPI 将 NumPy 数组作为图像返回?

DDD
DDD原创
2024-10-24 05:47:02545浏览

How to Return NumPy Arrays as Images Using FastAPI?

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

问题:在 FastAPI 中将 NumPy 数组显示为图像

解决方案:

要在 FastAPI 中将 NumPy 数组显示为图像,您有两个主要选项:

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

此方法涉及转换使用 PIL 或 OpenCV 库将 NumPy 数组转换为字节,然后将字节作为具有适当标头的自定义响应返回。

使用 PIL:

<code class="python"># Convert NumPy array to bytes using PIL
from PIL import Image
import io

arr = np.zeros((512, 512, 3), dtype=np.uint8)  # Sample RGB image
buf = BytesIO()
im = Image.fromarray(arr)
im.save(buf, format='PNG')
im_bytes = buf.getvalue()

# Return bytes as a Response with appropriate headers
from fastapi import Response

headers = {'Content-Disposition': 'inline; filename="test.png"'}
return Response(im_bytes, headers=headers, media_type='image/png')</code>

使用 OpenCV:

<code class="python"># Convert NumPy array to bytes using OpenCV
import cv2

arr = np.zeros((512, 512, 3), dtype=np.uint8)  # Sample RGB image
arr = cv2.cvtColor(arr, cv2.COLOR_RGB2BGR)
success, im = cv2.imencode('.png', arr)

# Return bytes as a Response with appropriate headers
from fastapi import Response

headers = {'Content-Disposition': 'inline; filename="test.png"'}
return Response(im.tobytes(), headers=headers, media_type='image/png')</code>

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

不建议将此方法用于显示目的,但可用于数据传输。

使用 PIL:

<code class="python">import numpy as np
import json

# Convert NumPy array to JSON-encoded string
arr = np.zeros((512, 512, 3), dtype=np.uint8)  # Sample RGB image
json_data = json.dumps(arr.tolist())</code>

使用 OpenCV:

<code class="python">import numpy as np
import cv2
import json

# Convert NumPy array to JSON-encoded string
arr = np.zeros((512, 512, 3), dtype=np.uint8)  # Sample RGB image
json_data = json.dumps(arr.tolist()).replace('-1', '255')</code>

以上是如何使用 FastAPI 将 NumPy 数组作为图像返回?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn