週末副業記

土日は副業エンジニアのブログです。副業に関することを投稿します。

二値化アプリ「nichica」【Python×Flask】


f:id:aisakakun:20180805203944p:plain

二値化処理をするサイトを作成しました。

htmlとPythonの連携

f:id:aisakakun:20180805211349j:plain
flaskチュートリアル(
4. Flaskを使いこなす1 — study flask 1 ドキュメント
)でいう
「views.py」で基本的なPythonプログラムを書き込んで
「show_entries.html」に受け渡し、
「show_entries.html」で受け渡された変数を使用。
そうすることで、「layout.html」に表示され
Pythonスクリプトの内容が表示されます。

views.py
show_entries.html
layout.html

上記の三つのファイルそれぞれ

##views.py

@app.route('/test')
def test():
    s = "abc"
    lis = ["a1","a2","a3"]
    dic = {"name":"John", "age":24}
    bl = True

    return render_template('show_entries.html',s=s,lis=lis,dic=dic,bl=bl)
<!-- show_entries.html -->

{% extends "layout.html" %}
{% block body %}
<!-- ----------省略------- -->
{% endblock %}
{% block body %}{% endblock %}

これらでつながっています。

二値化処理

f:id:aisakakun:20180805211541j:plain
肝心の二値化処理は
infoaisaka.hatenablog.com
これをごっそり使いました。

HTMLから画像データを読み込みPythonに受け渡す

{% block nichica %}
  <form action="{{ url_for('nichica_process') }}" method=post class=nichica-process enctype="multipart/form-data">
    <dl>
      <dt>image:
      <dd><input type="file" name="img_file" id="img_file" accept="image/">
      <dd><input type="submit" name="submit" value="送信">
    </dl>
  </form>
  {% if img_url %}
  <p><img src="{{ img_url }}"></p>
  {% endif %}
def nichica_process():
    if request.method == 'POST':
        img_file = request.files['img_file']
        if img_file and allowed_file(img_file.filename):
            filename = secure_filename(img_file.filename)
            
            """二値化(2018.08.05)aisaka hiroshi"""

            # BytesIOで読み込んでOpenCVで扱える型にする (2018.08.05)aisaka hiroshi
            f = img_file.stream.read()
            bin_data = io.BytesIO(f)
            file_bytes = np.asarray(bytearray(bin_data.read()), dtype=np.uint8)
            raw_img = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
            
            # BytesIOで読み込んでOpenCVで扱える型にする (2018.08.05)aisaka hiroshi

            #生データの保存(2018.08.05)aisaka hiroshi
            raw_img_url = os.path.join(app.config['UPLOAD_FOLDER'], 'raw_'+filename)
            cv2.imwrite(raw_img_url, raw_img)

            #生データの保存(2018.08.05)aisaka hiroshi

            raw_img_gray = cv2.cvtColor(raw_img, cv2.COLOR_BGR2GRAY)
            raw_img_blur = cv2.GaussianBlur(raw_img_gray, (5, 5), 0)
            raw_img_gray_blue = cv2.adaptiveThreshold(raw_img_blur, 255, 
            cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
            cv2.THRESH_BINARY, 11, 2)
            gray_img_url = os.path.join(app.config['UPLOAD_FOLDER'], 'gray_'+filename)
            cv2.imwrite(gray_img_url, raw_img_gray_blue)

            """二値化(2018.08.05)aisaka hiroshi"""
            print(gray_img_url)
            return render_template('nichica.html', img_url=gray_img_url)
        else:
            return '''<p>許可されていない拡張子です</p>'''
    else:
        return redirect(url_for('index'))

参考サイト;
HTMLから画像をアップロードするためのinput type="file"とHTML Media Capture - 理系学生日記
Flaskで画像アップローダー - Qiita

「nichica」操作方法

https://nichica-web.herokuapp.com
f:id:aisakakun:20180814144650p:plain

「ファイルを選択」をクリック

f:id:aisakakun:20180815075452p:plain

ファイルを選択

pngまたはjpgのみです
f:id:aisakakun:20180815075749p:plain:w400

「send」をクリック

f:id:aisakakun:20180815080335p:plain

画像処理後(二値化処理後)画像の表示

f:id:aisakakun:20180815080446p:plain
白黒画像になります。画像の雰囲気を少し変えたいときなどご利用ください。

使用イメージ
加工前
f:id:aisakakun:20180815080958p:plain:w500
加工後
f:id:aisakakun:20180815081015p:plain:w500

よろしくおねがいします!