├── README.md ├── send.py └── receive.py /README.md: -------------------------------------------------------------------------------- 1 | # Simple Webcam Streaming 2 | 3 | OpenCV and UDP 4 | 5 | Test with Python 3.7.3, OpenCV 4.1.0 6 | 7 | I understand this is not the best way to do video streaming but it works for me. 8 | 9 | There are still some issues: 10 | 11 | 1. a flicker at second frame ??? 12 | 2. flickering when draging the frame window for the first time??? 13 | 3. not tolerable to data lost (should generate packet loss to simulate the test) 14 | -------------------------------------------------------------------------------- /send.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import numpy as np 3 | import cv2 as cv 4 | 5 | 6 | addr = ("127.0.0.1", 65534) 7 | buf = 512 8 | width = 640 9 | height = 480 10 | cap = cv.VideoCapture(0) 11 | cap.set(3, width) 12 | cap.set(4, height) 13 | code = 'start' 14 | code = ('start' + (buf - len(code)) * 'a').encode('utf-8') 15 | 16 | 17 | if __name__ == '__main__': 18 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 19 | while(cap.isOpened()): 20 | ret, frame = cap.read() 21 | if ret: 22 | s.sendto(code, addr) 23 | data = frame.tostring() 24 | for i in range(0, len(data), buf): 25 | s.sendto(data[i:i+buf], addr) 26 | # cv.imshow('send', frame) 27 | # if cv.waitKey(1) & 0xFF == ord('q'): 28 | # break 29 | else: 30 | break 31 | # s.close() 32 | # cap.release() 33 | # cv.destroyAllWindows() 34 | -------------------------------------------------------------------------------- /receive.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import numpy as np 3 | import cv2 as cv 4 | 5 | 6 | addr = ("127.0.0.1", 65534) 7 | buf = 512 8 | width = 640 9 | height = 480 10 | code = b'start' 11 | num_of_chunks = width * height * 3 / buf 12 | 13 | if __name__ == '__main__': 14 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 15 | s.bind(addr) 16 | while True: 17 | chunks = [] 18 | start = False 19 | while len(chunks) < num_of_chunks: 20 | chunk, _ = s.recvfrom(buf) 21 | if start: 22 | chunks.append(chunk) 23 | elif chunk.startswith(code): 24 | start = True 25 | 26 | byte_frame = b''.join(chunks) 27 | 28 | frame = np.frombuffer( 29 | byte_frame, dtype=np.uint8).reshape(height, width, 3) 30 | 31 | cv.imshow('recv', frame) 32 | if cv.waitKey(1) & 0xFF == ord('q'): 33 | break 34 | 35 | s.close() 36 | cv.destroyAllWindows() 37 | --------------------------------------------------------------------------------