2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

OpenCVで読み込んだ画像をFastAPIで返したいとき

Posted at

結論: エンコードしたあとstarletteのStreamingResponseを使いましょう。

サンプルコード
import io
import cv2
from fastapi import FastAPI
from starlette.responses import StreamingResponse

app = FastAPI()

@app.get("/image/jpg")
def image_jpg():
    image_path = "C:\\publc\\image.jpg"  
    im = cv2.imread(image_path)
    byte_image = cv2.imencode(".jpg", im)
    return StreamingResponse(io.BytesIO(byte_image.tobytes()), media_type="image/jpg")

# jpgじゃなくてpngがいい場合は以下
@app.get("/image/png")
def image_png():
    image_path = "C:\\publc\\image.png"
    im = cv2.imread(image_path)
    byte_image = cv2.imencode(".png", im)
    return StreamingResponse(io.BytesIO(byte_image.tobytes()), media_type="image/png")

補足

フロントエンド側は以下のようにすれば画像を読み込むことができる。

画像アクセスのサンプルコード
<img src="http://localhost:8000/image/jpg" />
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?