Skip to content

Instantly share code, notes, and snippets.

@simgt
Last active June 15, 2018 07:51
Show Gist options
  • Save simgt/daed1f021aee8d89b62d50f44a884301 to your computer and use it in GitHub Desktop.
Save simgt/daed1f021aee8d89b62d50f44a884301 to your computer and use it in GitHub Desktop.
A simple and pythonic video streaming server with OpenCV and Flask
import threading
import time
import flask
import cv2
class CameraThread(threading.Thread):
def __init__(self):
super().__init__()
self.capture = cv2.VideoCapture(0)
self.condition = threading.Condition()
def iter_frames(self):
while True:
with self.condition:
self.condition.wait()
frame = self.frame
yield (b'--FRAME\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + self.frame + b'\r\n')
def run(self):
while True:
__, frame = self.capture.read()
__, img = cv2.imencode('.jpg', frame)
with self.condition:
self.frame = img.tobytes()
self.condition.notify_all()
time.sleep(0)
app = flask.Flask(__name__)
camera_thread = CameraThread()
@app.route("/")
def index():
return flask.render_template('index.html')
@app.route("/stream")
def stream():
return flask.Response(camera_thread.iter_frames(),
mimetype='multipart/x-mixed-replace; boundary=FRAME')
if __name__ == '__main__':
camera_thread.start()
app.run(host='0.0.0.0', threaded=True, debug=True)
<html>
<head>
<title>MJPEG streaming</title>
</head>
<body>
<img src="stream" width="800" height="600" />
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment