Skip to content

Instantly share code, notes, and snippets.

@mjul
Created July 2, 2014 19:27
Show Gist options
  • Select an option

  • Save mjul/32d697b734e7e9171cdb to your computer and use it in GitHub Desktop.

Select an option

Save mjul/32d697b734e7e9171cdb to your computer and use it in GitHub Desktop.

Revisions

  1. mjul renamed this gist Jul 2, 2014. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. mjul created this gist Jul 2, 2014.
    4 changes: 4 additions & 0 deletions form.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,4 @@
    <form method="POST" enctype="multipart/form-data" action="/TARGET/URL/FOR/UPLOAD">
    <input type="file" name="photo" />
    <input type="submit" />
    </form>
    33 changes: 33 additions & 0 deletions form_to_opencv.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    #
    # Example from code built on the Flask web framework (and Werkzeug)
    # Accepts uploading a photo file in the 'photo' form member, then
    # copies it into a memory byte array and converts it to a numpy array
    # which in turn can be decoded by OpenCV.
    #
    # Beware that this increases the memory pressure and you should
    # configure a max request size before doing so.
    #
    # It saves a round-trip to a temporary file, though.

    import flask
    from flask import render_template, json, jsonify, request
    import numpy as np
    import cv2

    # ...

    # Remember to set a max content length
    app = flask.Flask(__name__)
    app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16 MB

    # ...

    # Here is the code to convert the post request to an OpenCV object

    if request.method == 'POST' and 'photo' in request.files:
    photo = request.files['photo']
    in_memory_file = io.BytesIO()
    photo.save(in_memory_file)
    data = np.fromstring(in_memory_file.getvalue(), dtype=np.uint8)
    color_image_flag = 1
    img = cv2.imdecode(data, color_image_flag)