首頁  >  文章  >  後端開發  >  如何在 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>
客戶端:
<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
伺服器端:
<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>
客戶端- Side:

透過將這些程式碼片段合併到您的應用程式中,您將能夠成功將NumPy 陣列渲染為圖像並根據需要顯示它們。

以上是如何在 FastAPI 中將 NumPy 陣列渲染為映像?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn