Skip to content

Instantly share code, notes, and snippets.

@cjdenio
Last active March 30, 2021 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cjdenio/1521ab22a3566587d5c829e8b4821e8c to your computer and use it in GitHub Desktop.
Save cjdenio/1521ab22a3566587d5c829e8b4821e8c to your computer and use it in GitHub Desktop.
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