Created
May 2, 2023 19:30
-
-
Save jmpinit/9465d04e735fcb77fdee4c2ca479a806 to your computer and use it in GitHub Desktop.
Very simple low latency camera streaming in Python with OpenCV and ZeroMQ.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import cv2 | |
import zmq | |
import base64 | |
import numpy as np | |
context = zmq.Context() | |
footage_socket = context.socket(zmq.SUB) | |
footage_socket.connect('tcp://localhost:5555') | |
footage_socket.setsockopt_string(zmq.SUBSCRIBE, '') | |
while True: | |
try: | |
try: | |
frame = footage_socket.recv_string(zmq.NOBLOCK) | |
img = base64.b64decode(frame) | |
npimg = np.frombuffer(img, dtype=np.uint8) | |
source = cv2.imdecode(npimg, cv2.IMREAD_COLOR) | |
cv2.imshow('Receiver', source) | |
except zmq.ZMQError: | |
pass | |
if cv2.waitKey(1) & 0xFF == ord('q'): break | |
except KeyboardInterrupt: | |
cv2.destroyAllWindows() | |
break |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import cv2 | |
import zmq | |
import base64 | |
context = zmq.Context() | |
footage_socket = context.socket(zmq.PUB) | |
footage_socket.bind('tcp://*:5555') | |
# Reduce the high water mark to prevent buffering | |
footage_socket.setsockopt(zmq.SNDHWM, 10) | |
footage_socket.setsockopt(zmq.RCVHWM, 10) | |
camera = cv2.VideoCapture(0) | |
while True: | |
try: | |
# Read a frame from the camera | |
ret, frame = camera.read() | |
frame = cv2.resize(frame, (640, 480)) # resize the frame | |
encoded, buffer = cv2.imencode('.jpg', frame) | |
jpg_as_text = base64.b64encode(buffer) | |
footage_socket.send(jpg_as_text) | |
# Display the resulting frame | |
cv2.imshow('Sender', frame) | |
if cv2.waitKey(1) & 0xFF == ord('q'): | |
break | |
except KeyboardInterrupt: | |
camera.release() | |
cv2.destroyAllWindows() | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment