from io import BytesIO import cv2 from PIL import Image class Camera: capture: cv2.VideoCapture def __init__(self): self.capture = cv2.VideoCapture(0) def generate_images(self): try: while True: return_code, image = self.capture.read() if not return_code: continue image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) jpg = Image.fromarray(image_rgb) byte_stream = BytesIO() jpg.save(byte_stream, 'JPEG') yield bytes(byte_stream.getbuffer()) finally: self.capture.release() def mjpeg_stream(self, boundary: bytes): for frame in self.generate_images(): if not frame: break yield b''.join([ b'--', boundary, b'\r\n', b'Content-Type: image/jpeg\r\n\r\n', frame, b'\r\n'])