1

I am capturing an image through webcam using opencv(python 2.7) in my flask application.I want to display this image to the client in the frontend to get coordinates of image on mouseclick.How can i write the functions to send and receive the image via flask and javascript respectively.

flask server code:

from flask import Flask,render_template
import cv2

app = Flask(__name__)

@app.route('/')
def capture_image(self):
    self.cam = cv2.VideoCapture(0)
    self.img = self.cam.read()
    self.cam.release()
    render_template(index.html,ob=self.img)

@app.route('/index')
#display image in html

if __name__=='__main__':
    app.run()

javascript code:

<html>
<head>
<title> image </title>
</head>
<body>
<img src = "{{ url_for('imagefield') }}">
</body>
</html>

2 Answers2

4

My suggestion is to save the image using imwrite in "static/filename.jpg". Then send the URL rather than the actual image and have your div that is using the image file reload it. I have sent the whole image and it took around 10 second to load when I check on POSTMAN, however, it did not laod at all in the browser. If you insist on sending the file, please see flask return image created from database

I'm doing something like this:

flask:
return jsonify({'image_url': imgPath})

part of ajax request:
success: function (data) {
      console.log(data);
      $('#myimg').html('<img class="img-responsive"  src="'+data.image_url+'"/>');
    }

Hope this helps.

Community
  • 1
  • 1
matchifang
  • 5,190
  • 12
  • 47
  • 76
3

I spent sooooo many hours trying to figure this out. Sorry its 6 years too late. You need to read your image on the flask side, encode it to base64, then decode it to utf. From here, it will be json serializable so that your javascript can pull it it in using jquery.ajax().

Python side

@app.route("/getimage", methods=["GET", "POST"])
def getimage():
    if os.path.isfile("path-to-file.png"):
        import base64
        with open("path-to-file.png", "rb") as img_file:
            my_string = base64.b64encode(img_file.read()).decode("utf-8")
        return json.dumps({"success": 1, "image":my_string})

    else:
        return json.dumps({"success":0})

javascript side

jQuery.ajax({
        url: "/getimage",
        type: "GET",
        success: function(returned_data){
            returned_data = JSON.parse(returned_data)
            if (returned_data['success'] > 0){ // generation is done
                const byteCharacters = atob(returned_data['image']);
                const byteNumbers = new Array(byteCharacters.length);
                for (let i = 0; i < byteCharacters.length; i++) {
                    byteNumbers[i] = byteCharacters.charCodeAt(i);
                }
                const byteArray = new Uint8Array(byteNumbers);
                document.getElementById("image-result").src = URL.createObjectURL(new Blob([byteArray], { type: 'image/png' }));
            }
            else{
                console.log("could not find image");
            }
        }
    });
AJ Bensman
  • 550
  • 4
  • 11