Skip to content

Instantly share code, notes, and snippets.

@tehmas
Created December 4, 2016 16:55
Show Gist options
  • Save tehmas/4a1b600e7bc95ee3d48b6fae85e5fad9 to your computer and use it in GitHub Desktop.
Save tehmas/4a1b600e7bc95ee3d48b6fae85e5fad9 to your computer and use it in GitHub Desktop.
Sending OpenCV frames using Python TCP sockets
import cv2
import cPickle
import socket
import struct
TCP_IP = '127.0.0.1'
TCP_PORT = 9501
server_address = (TCP_IP, TCP_PORT)
i = 0
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((TCP_IP,TCP_PORT))
data = ''
payload_size = struct.calcsize("I")
while True:
while len(data) < payload_size:
data += sock.recv(4096)
packed_msg_size = data[:payload_size]
data = data[payload_size:]
msg_size = struct.unpack("I", packed_msg_size)[0]
while len(data) < msg_size:
data += sock.recv(4096)
frame_data = data[:msg_size]
data = data[msg_size:]
if frame_data=='':
break
frame=cPickle.loads(frame_data)
print i
i += 1
sock.close()
import cv2
import cPickle
import socket
import struct
TCP_IP = '127.0.0.1'
TCP_PORT = 9501
video_file = 'some_file.MP4'
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # establishing a tcp connection
sock.bind((TCP_IP, TCP_PORT))
sock.listen(5)
while True:
(client_socket, client_address) = sock.accept() # wait for client
print 'connection established with ' +str(client_address)
cap = cv2.VideoCapture(video_file)
pos_frame = cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
while True:
flag, frame = cap.read()
if flag:
frame = cPickle.dumps(frame)
size = len(frame)
p = struct.pack('I', size)
frame = p + frame
client_socket.sendall(frame)
else:
cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, pos_frame-1)
if cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES) == cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT):
size = 10
p = struct.pack("I", size)
client_socket.send(p)
client_socket.send('')
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment