Home  >  Article  >  Backend Development  >  How to Return NumPy Arrays as Images Using FastAPI?

How to Return NumPy Arrays as Images Using FastAPI?

DDD
DDDOriginal
2024-10-24 05:47:02545browse

How to Return NumPy Arrays as Images Using FastAPI?

How to Render a NumPy Array as an Image in FastAPI

Issue: Displaying a NumPy array as an image in FastAPI

Solution:

To display a NumPy array as an image in FastAPI, you have two main options:

Option 1: Return Image as Bytes

This approach involves converting the NumPy array into bytes using either the PIL or OpenCV library and then returning the bytes as a custom Response with the appropriate headers.

Using PIL:

<code class="python"># Convert NumPy array to bytes using PIL
from PIL import Image
import io

arr = np.zeros((512, 512, 3), dtype=np.uint8)  # Sample RGB image
buf = BytesIO()
im = Image.fromarray(arr)
im.save(buf, format='PNG')
im_bytes = buf.getvalue()

# Return bytes as a Response with appropriate headers
from fastapi import Response

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

Using OpenCV:

<code class="python"># Convert NumPy array to bytes using OpenCV
import cv2

arr = np.zeros((512, 512, 3), dtype=np.uint8)  # Sample RGB image
arr = cv2.cvtColor(arr, cv2.COLOR_RGB2BGR)
success, im = cv2.imencode('.png', arr)

# Return bytes as a Response with appropriate headers
from fastapi import Response

headers = {'Content-Disposition': 'inline; filename="test.png"'}
return Response(im.tobytes(), headers=headers, media_type='image/png')</code>

Option 2: Return Image as JSON-encoded NumPy Array

This approach is not recommended for display purposes but can be used for data transfer.

Using PIL:

<code class="python">import numpy as np
import json

# Convert NumPy array to JSON-encoded string
arr = np.zeros((512, 512, 3), dtype=np.uint8)  # Sample RGB image
json_data = json.dumps(arr.tolist())</code>

Using OpenCV:

<code class="python">import numpy as np
import cv2
import json

# Convert NumPy array to JSON-encoded string
arr = np.zeros((512, 512, 3), dtype=np.uint8)  # Sample RGB image
json_data = json.dumps(arr.tolist()).replace('-1', '255')</code>

The above is the detailed content of How to Return NumPy Arrays as Images Using 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