title: Webcam Live Streaming using Flask
body: <p>I want to access my webcams via a browser by multiple clients. I tried the following source code:</p>
  
  <p>main.py:</p>
  
  <pre><code>#!/usr/bin/env python
  from flask import Flask, render_template, Response
  
  # emulated camera
  from webcamvideostream import WebcamVideoStream
  
  import cv2
  
  app = Flask(__name__, template_folder='C:\coding\streamingserver\templates')
  
  @app.route('/')
  def index():
      """Video streaming home page."""
      return render_template('streaming.html')
  
  
  def gen(camera):
      """Video streaming generator function."""
      while True:
          frame = camera.read()
          ret, jpeg = cv2.imencode('.jpg', frame)
  
          # print("after get_frame")
          if jpeg is not None:
              yield (b'--frame\r\n'
                     b'Content-Type: image/jpeg\r\n\r\n' + jpeg.tobytes() + b'\r\n')
          else:
              print("frame is none")
  
  
  
  @app.route('/video_feed')
  def video_feed():
      """Video streaming route. Put this in the src attribute of an img tag."""
      return Response(gen(WebcamVideoStream().start()),
                      mimetype='multipart/x-mixed-replace; boundary=frame')
  
  
  if __name__ == '__main__':
      app.run(host='0.0.0.0', port=5010, debug=True, threaded=True)
  </code></pre>
  
  <p>webcamvideostream.py:</p>
  
  <pre><code># import the necessary packages
  from threading import Thread
  import cv2
  
  class WebcamVideoStream:
  
      def __init__(self, src=0):
          # initialize the video camera stream and read the first frame
          # from the stream
          print("init")
          self.stream = cv2.VideoCapture(src)
          (self.grabbed, self.frame) = self.stream.read()
  
          # initialize the variable used to indicate if the thread should
          # be stopped
          self.stopped = False
  
  
      def start(self):
          print("start thread")
          # start the thread to read frames from the video stream
          t = Thread(target=self.update, args=())
          t.daemon = True
          t.start()
          return self
  
      def update(self):
          print("read")
          # keep looping infinitely until the thread is stopped
          while True:
              # if the thread indicator variable is set, stop the thread
              if self.stopped:
                  return
  
  
              # otherwise, read the next frame from the stream
              (self.grabbed, self.frame) = self.stream.read()
  
      def read(self):
          # return the frame most recently read
          return self.frame
  
      def stop(self):
          # indicate that the thread should be stopped
          self.stopped = True
  </code></pre>
  
  <p>This works - except that threads are never stopped.. so if I refresh my browser or open further tabs accessing the stream, the number of threads will increase.
  I don't know where to call the stop function..
  Can someone help me?</p>
  
  <p>Best, 
  Hanna</p>