首页  >  文章  >  后端开发  >  如何在 FastAPI 中将 NumPy 数组渲染为图像?

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

Patricia Arquette
Patricia Arquette原创
2024-10-24 02:10:01195浏览

How to Render NumPy Arrays as Images in FastAPI?

如何在 FastAPI 中渲染 NumPy 数组

您已成功实现自定义响应以将 NumPy 数组渲染为图像。以下是如何执行此操作的演示:

对于此演示,假设您已创建内存中的像素值 NumPy 数组。

使用 PIL

  1. 服务器端:
<code class="python">from PIL import Image
import numpy as np

def render_image(img):
    with io.BytesIO() as buf:
        img = Image.fromarray(img)
        img.save(buf, format="PNG")
        return buf.getvalue()</code>
  1. 客户端:
<code class="python">import requests

url = "http://example.com/image"
response = requests.get(url)
image_bytes = response.content
# You can now render the image using PIL or OpenCV</code>

使用 OpenCV

  1. 服务器端:
<code class="python">import cv2
import numpy as np

def render_image(img):
    ret, buf = cv2.imencode('.png', img)
    return buf.tobytes()</code>
  1. 客户端- Side:
<code class="python">import requests
import cv2
import numpy as np

url = "http://example.com/image"
response = requests.get(url)
image_bytes = response.content
# You can now render the image using PIL or OpenCV</code>

通过将这些代码片段合并到您的应用程序中,您将能够成功将 NumPy 数组渲染为图像并根据需要显示它们。

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

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