6
10

More than 5 years have passed since last update.

Flaskでデータのラベリングサイトを作成する

Last updated at Posted at 2018-04-07

復習がてら「Pythonによるスクレイピング&機械学習」の7章を読んでいる。
すると画像データのラベリングをする部分があった。
よく見るとphpで書かれていたのでまあせっかくだしpythonで書いてみようと思ったので作ってみた。

環境

  • python 3.6.0
  • Flask 0.12.2

ディレクトリ構造

.
├── labelling.py : Flaskファイル
├── static
│   ├── gyudon : まだラベリングしていない画像フォルダ
│   └── labeled : ラベリングした画像フォルダ
│       ├── beni
│       ├── cheese
│       ├── kimuti
│       ├── negi
│       ├── normal
│       └── other
└── templates
    └── index.html

HTML

とりあえず雑なHTMLを書いてみる。

templates/index.html
<!DOCTYPE html>
<html lang="jp">
<head>
    <meta charset="UTF-8">
    <title>画像ラベリングサイト</title>
</head>
<body>
    <h1>画像を分類してください</h1>
    <img src="{{ img }}" style="width: 500px;">
    <form action="{{ url_for('labelling')  }}" method="POST">
      <input type="hidden" name="img_path" value="{{ img }}">

      {% if category_list %}

      {% for category in category_list %}
      <input type="radio" name="category" value="{{ category }}">
      {{ category }}
      <br/>
      {% endfor %}

      {% else %}
      static/labeledにカテゴリーフォルダを作成してください。

      {% endif %}

      <input type="submit" value="送信">
    </form>
</body>
</html>

表示されている画像を見て分類を行うformを作成。
フォームで送信するのは分類するカテゴリと画像のファイルパス

Flask

labelling.py
from flask import Flask, render_template, request, redirect, url_for
import glob
import os
import shutil


app = Flask(__name__)

@app.route("/")
def index():

    # 画像ファイルパスを取得
    img_path = glob.glob("static/gyudon/*")
    # 分類するフォルダ名を取得
    category_path = [os.path.basename(path) for path in glob.glob("static/labeled/*")]
    return render_template('index.html', img=img_path[0], category_list=category_path)

@app.route("/labelling", methods=['POST'])
def labelling():

    # 分類するフォルダパスを取得
    category_path = os.path.join("static", os.path.join("labeled", request.form['category']))
    # ファイルの移動
    shutil.move(request.form['img_path'], category_path)
    return redirect("/")

if __name__ == "__main__":
    app.debug = True
    app.run()

実行

実行してみるとこんな感じ
スクリーンショット 2018-04-08 0.12.03.png

感想

Flaskはファイル構造も容易であったり、一つのファイルで管理できるのがいいなぁと実感。

6
10
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
6
10