>  기사  >  백엔드 개발  >  FastAPI에서 NumPy 배열을 이미지로 렌더링하는 방법은 무엇입니까?

FastAPI에서 NumPy 배열을 이미지로 렌더링하는 방법은 무엇입니까?

Patricia Arquette
Patricia Arquette원래의
2024-10-24 02:10:01195검색

How to Render NumPy Arrays as Images in FastAPI?

FastAPI에서 NumPy 배열을 렌더링하는 방법

NumPy 배열을 이미지로 렌더링하는 사용자 정의 응답을 성공적으로 구현했습니다. 다음은 그 방법을 보여주는 데모입니다.

이 데모에서는 픽셀 값의 메모리 내 NumPy 배열을 생성했다고 가정합니다.

PIL 사용

  1. 서버측:
<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. 클라이언트측:
<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>

OpenCV 사용

  1. 서버측:
<code class="python">import cv2
import numpy as np

def render_image(img):
    ret, buf = cv2.imencode('.png', img)
    return buf.tobytes()</code>
  1. 클라이언트- 측면:
<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>

이러한 코드 조각을 애플리케이션에 통합하면 NumPy 배열을 이미지로 성공적으로 렌더링하고 원하는 대로 표시할 수 있습니다.

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

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.