Home  >  Article  >  Backend Development  >  How to Render NumPy Arrays as Images in FastAPI?

How to Render NumPy Arrays as Images in FastAPI?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-24 02:10:01195browse

How to Render NumPy Arrays as Images in FastAPI?

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

  1. Server-Side:
<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. Client-Side:
<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

  1. Server-Side:
<code class="python">import cv2
import numpy as np

def render_image(img):
    ret, buf = cv2.imencode('.png', img)
    return buf.tobytes()</code>
  1. Client-Side:
<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn