Files
WallE/control/camera.py

47 lines
1.3 KiB
Python

from io import BytesIO
from typing import Optional
import cv2
from PIL import Image
class Camera:
capture: cv2.VideoCapture
def __init__(self):
self.capture = cv2.VideoCapture(0)
def get_image(self) -> Optional[bytes]:
return_code, image = self.capture.read()
if not return_code:
return None
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
jpg = Image.fromarray(image_rgb)
byte_stream = BytesIO()
jpg.save(byte_stream, 'JPEG')
return bytes(byte_stream.getbuffer())
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'])