如何在 FastAPI 中渲染 NumPy 陣列
您已成功實現自訂回應以將 NumPy 陣列渲染為映像。以下是如何執行此操作的演示:
對於此演示,假設您已建立記憶體中的像素值 NumPy 數組。
使用PIL
<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>
<code class="python">import cv2 import numpy as np def render_image(img): ret, buf = cv2.imencode('.png', img) return buf.tobytes()</code>
<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中文網其他相關文章!