Skip to content

Instantly share code, notes, and snippets.

@t-34400
Created February 18, 2024 16:40
Show Gist options
  • Save t-34400/63f5560c4b994df5ae34c6c756cf62a7 to your computer and use it in GitHub Desktop.
Save t-34400/63f5560c4b994df5ae34c6c756cf62a7 to your computer and use it in GitHub Desktop.
Python / Video socket stream decoder
import cv2
import socket
import numpy as np
import time
import argparse
def main(host, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
sock.settimeout(5)
decode_flag = False
while True:
try:
data = sock.recv(1024)
frame = cv2.imdecode(np.frombuffer(data, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
cv2.imshow('Frame', frame)
decode_flag = True
if cv2.waitKey(1) & 0xFF == 27:
break
except socket.timeout:
if decode_flag:
cv2.imshow('Frame', frame)
decode_flag = False
time.sleep(1)
sock.close()
cv2.destroyAllWindows()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Decode and render H264 data from a socket.")
parser.add_argument("--host", type=str, default="127.0.0.1", help="Host IP address")
parser.add_argument("--port", type=int, default=12345, help="Port number")
args = parser.parse_args()
main(args.host, args.port)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment