How to Render NumPy Arrays as Images in FastAPI?

Patricia Arquette
Release: 2024-10-24 02:10:01
Original
211 people have browsed it

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>
Copy after login
  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>
Copy after login

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>
Copy after login
  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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!