Skip to content

Instantly share code, notes, and snippets.

@robobe
Created August 23, 2019 07:20
Show Gist options
  • Save robobe/afe2a04d5d50a63f773aad99eafaccd3 to your computer and use it in GitHub Desktop.
Save robobe/afe2a04d5d50a63f773aad99eafaccd3 to your computer and use it in GitHub Desktop.
recieve image over udp socket, decode from jpeg work with sample from udp_sender gist
import socket
import sys
import struct
import cv2
import numpy as np
BUFFER_SIZE = 1024
ADDR = ("127.0.0.1", 5252)
HEADER_START = b"START"
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(ADDR)
buf = b""
while True:
data, address = sock.recvfrom(BUFFER_SIZE)
#Check for header packet
#todo: marge header with data in the first packet
if HEADER_START in data:
header_index = data.index(HEADER_START)
pk = data[header_index+len(HEADER_START): header_index+len(HEADER_START)+4]
size = struct.unpack("@I", pk)[0]
buf = b""
#read data
while size > 0:
data, address = sock.recvfrom(BUFFER_SIZE)
buf += data
size -= BUFFER_SIZE
# print(len(buf))
np_array = np.fromstring(buf, dtype=np.uint8)
frame = cv2.imdecode(np_array, -1)
cv2.imshow("dest", frame)
if cv2.waitKey(1)== 27:
break
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment