Skip to content

Instantly share code, notes, and snippets.

@cjdenio

cjdenio/mjpeg.py

Last active Mar 30, 2021
Embed
What would you like to do?
Tiny MJPEG implementation for Python + OpenCV
from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
import numpy as np
import cv2
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""Handle requests in a separate thread."""
class MjpegStream(ThreadedHTTPServer):
def __init__(self, addr, shape):
super().__init__(addr, MjpegHandler)
self.frame = np.zeros(shape)
def start(self):
super().serve_forever()
def write(self, img):
self.frame = img
class MjpegHandler(BaseHTTPRequestHandler):
def do_GET(self):
print(self.path)
self.send_response(200)
self.send_header(
'Content-type', 'multipart/x-mixed-replace; boundary=--jpgboundary')
self.end_headers()
while True:
try:
r, buf = cv2.imencode(".jpg", self.server.frame)
self.wfile.write("--jpgboundary\r\n".encode())
self.end_headers()
self.wfile.write(bytearray(buf))
except KeyboardInterrupt:
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment