ホームページ  >  記事  >  バックエンド開発  >  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. クライアント-サイド:
<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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。