LoginSignup
24
28

More than 5 years have passed since last update.

Flaskでアップロードされた画像ファイルをOpenCVで読み込む方法

Posted at

参考: https://qiita.com/miyahan/items/7d629d00429c9f032a27

  • Flaskのrequest.filesから取得したファイル情報は、WerkzeugのFileStorageオブジェクトになっている
  • FileStorageのstreamはPythonの基本的なバイナリストリームであるio.BufferedIOBaseを継承している
  • これは要するにopen(FILE_NAME, "rb")した時に得られるものと同じと考えればいい

OpenCVでこのストリームを読み込むには、次のようにする。

import cv2
import numpy as np
from flask import Flask, request
app = Flask(__name__)

@app.route("/upload", methods = ["POST"])
def upload():
  stream = request.files['file'].stream
  img_array = np.asarray(bytearray(stream.read()), dtype=np.uint8)
  img = cv2.imdecode(img_array, 1)

ちなみにimdecodeの第二引数はimreadのそれと同じ意味だが、なぜかこちらは省略できない。

24
28
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
24
28