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!