0

I need to display 2 images, one is input and other is the opencv processed image. After searching online, I found this. So I run a simple flask prog --

from flask import Flask, make_response, render_template, Response
app = Flask(__name__)

@app.route('/')
def simple():
    import cv2
    img = cv2.imread('fruit.jpg')
    ret, jpeg = cv2.imencode('.jpg', img)
    response = make_response(jpeg.tobytes())
    response.headers['Content-Type'] = 'image/png'
    return response
if __name__ == "__main__":
    app.run()

This worked fine.

For displaying two images, I followed the link, that I posted above. That looks like --

from flask import Flask, make_response, render_template, Response
app = Flask(__name__)

@app.route('/gallery')
def get_gallery():
    import cv2
    im_names = []
    img = cv2.imread('fruit.jpg')
    im = cv2.imread('adapt.png')
    ret, jpeg = cv2.imencode('.jpg', img)
    ret1, jpeg1 = cv2.imencode('.png', im)
    print(im_names)
    im_names.append(jpeg.tobytes())
    im_names.append(jpeg1.tobytes())
    return render_template("gallery.html", image_names=im_names)

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

Where I have copied gallery.html from above link. I got no output. It says internal server error. How can I solve this problem?(I am new to flask).

Ujjal Kumar Das
  • 191
  • 3
  • 15

1 Answers1

0

First create a folder named "static". Put your images in that folder. And try this :

from flask import Flask, make_response, render_template, Response

app = Flask(__name__)
@app.route('/gallery')
def get_gallery():
    return "<img src='static/fruit.jpg'/> <img src='static/adapt.png'>"

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

Note that you could use your template gallery.html, and put the html code directly in the template.

Loïc
  • 11,804
  • 1
  • 31
  • 49
  • 1
    Can you display the image `jpeg.tobytes()` in browser using html as like you displayed using the path specified? I don't want to save an image to static folder and then display it. You can also direct me to some blog or tutorial related to the above. – Ujjal Kumar Das Sep 01 '17 at 19:06
  • cv2.imwrite('static/cv2_image.png',img) You need to save the image on the disk before serving it. – Loïc Sep 01 '17 at 21:42