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

Patricia Arquette
发布: 2024-10-24 02:10:01
原创
211 人浏览过

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中文网其他相关文章!

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