How to Render NumPy Array in FastAPI
You have successfully implemented a custom Response to render a NumPy array as an image. Here's a demonstration of how to do so:
For this demonstration, assume you have created an in-memory NumPy array of pixel values.
Using 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>
Using OpenCV
<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>
By incorporating these code snippets into your application, you will be able to successfully render NumPy arrays as images and display them as desired.
The above is the detailed content of How to Render NumPy Arrays as Images in FastAPI?. For more information, please follow other related articles on the PHP Chinese website!