FastAPI를 사용하여 NumPy 배열을 이미지로 반환하는 방법은 무엇입니까?

DDD
풀어 주다: 2024-10-24 05:47:02
원래의
546명이 탐색했습니다.

How to Return NumPy Arrays as Images Using FastAPI?

FastAPI에서 NumPy 배열을 이미지로 렌더링하는 방법

문제: FastAPI에서 NumPy 배열을 이미지로 표시

해결책:

FastAPI에서 NumPy 배열을 이미지로 표시하려면 두 가지 주요 옵션이 있습니다.

옵션 1: 이미지를 바이트로 반환

이 접근 방식에는 변환이 포함됩니다. PIL 또는 OpenCV 라이브러리를 사용하여 NumPy 배열을 바이트로 변환한 다음 해당 바이트를 적절한 헤더와 함께 사용자 정의 응답으로 반환합니다.

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>
로그인 후 복사

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>
로그인 후 복사

옵션 2: 이미지를 JSON 인코딩 NumPy 배열로 반환

이 접근 방식은 표시 목적으로는 권장되지 않지만 데이터 전송에 사용할 수 있습니다.

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>
로그인 후 복사

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>
로그인 후 복사

위 내용은 FastAPI를 사용하여 NumPy 배열을 이미지로 반환하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!