如何在 FastAPI 中將 NumPy 陣列顯示為映像?

Barbara Streisand
發布: 2024-10-24 03:42:02
原創
411 人瀏覽過

How to Display NumPy Arrays as Images in FastAPI?

在 FastAPI 中將 NumPy 陣列渲染為映像

簡介

FastAPI 是用於建立 API 的熱門 Python 框架。它提供了一種處理 HTTP 請求和回應的便捷方法。本文示範如何在 FastAPI 中將 NumPy 陣列渲染為映像。

選項1:以位元組形式傳回影像

使用PIL

<code class="python">from PIL import Image
from io import BytesIO

@app.get("/image", response_class=Response)
def get_image():
    arr = np.zeros((512, 512, 3), dtype=np.uint8)
    arr[0:256, 0:256] = [255, 0, 0]  # Red patch in the upper left
    im = Image.fromarray(arr)

    with io.BytesIO() as buf:
        im.save(buf, format='PNG')
        im_bytes = buf.getvalue()

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

使用OpenCV

<code class="python">import cv2

@app.get("/image", response_class=Response)
def get_image():
    arr = np.zeros((512, 512, 3), dtype=np.uint8)
    arr[0:256, 0:256] = [255, 0, 0]  # Red patch in the upper left
    arr = cv2.cvtColor(arr, cv2.COLOR_RGB2BGR)  # OpenCV uses BGR

    success, im = cv2.imencode('.png', arr)
    headers = {'Content-Disposition': 'inline; filename="test.png"'}
    return Response(im.tobytes(), headers=headers, media_type='image/png')</code>
登入後複製

選項2:將影像作為JSON編碼的NumPy 陣列傳回

注意:僅使用此選項將影像轉換為JavaScript 物件。

使用 PIL

<code class="python">import json

@app.get("/image")
def get_image():
    im = Image.open('test.png')
    arr = np.asarray(im)
    return json.dumps(arr.tolist())</code>
登入後複製

使用 OpenCV

<code class="python">@app.get("/image")
def get_image():
    arr = cv2.imread('test.png')
    return json.dumps(arr.tolist())</code>
登入後複製

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

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!