'Close OpenCV camera stream at page close (Flask)

I'm making a simple video stream to browser app on my Rpi. I would like to know if there is a way to open a camera only when access the flask page and close the camera if page is not seen anymore. I don't want to let camera open whole time.

I was trying something like this, but it would involve button press (POST request) to flask server every time I want to close the tab what is little bit awkward.

from flask import Flask, render_template, Response, request
import cv2
from time import sleep

app = Flask(__name__)

CAMERA = None


def gen_frames():
    global CAMERA
    CAMERA = cv2.VideoCapture(0)
    sleep(3)
    CAMERA.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
    CAMERA.set(cv2.CAP_PROP_FRAME_HEIGHT, 960)
    while True:
        success, frame = CAMERA.read()
        if not success:
            break
        else:
            _, buffer = cv2.imencode('.jpg', frame)
            frame = buffer.tobytes()

            # concat frame one by one and show result
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') 



@app.route('/video_feed')
def video_feed():
    return Response(gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')



@app.route('/', methods = ['POST', 'GET'])
def index():
    global CAMERA
    if request.method == 'POST':
        if request.form['webcam']:
            if CAMERA != None and CAMERA.isOpened():
                CAMERA.release()

    return render_template('index.html')



if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source