我正在尝试将用相机捕获的实时视频帧发送到服务器并进行处理。我使用usig opencv进行图像处理,使用python进行语言处理。这是我的代码
client_cv.py
import cv2 import numpy as np import socket import sys import pickle cap=cv2.VideoCapture(0) clientsocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) clientsocket.connect(('localhost',8089)) while True: ret,frame=cap.read() print sys.getsizeof(frame) print frame clientsocket.send(pickle.dumps(frame))
server_cv.py
import socket import sys import cv2 import pickle import numpy as np HOST='' PORT=8089 s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) print 'Socket created' s.bind((HOST,PORT)) print 'Socket bind complete' s.listen(10) print 'Socket now listening' conn,addr=s.accept() while True: data=conn.recv(80) print sys.getsizeof(data) frame=pickle.loads(data) print frame cv2.imshow('frame',frame)
这段代码给了我文件结尾错误,这是合乎逻辑的,因为数据总是不断到达服务器,而pickle不知道何时完成。我在互联网上进行的搜索使我使用了泡菜,但到目前为止还不能用。
注意 :我设置conn.recv为80,因为那是我说时得到的数字print sys.getsizeof(frame)。
conn.recv
print sys.getsizeof(frame)
几样东西:
sendall
send
pickle
recv
sys.getsizeof
协议示例:
import cv2 import numpy as np import socket import sys import pickle import struct ### new code cap=cv2.VideoCapture(0) clientsocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) clientsocket.connect(('localhost',8089)) while True: ret,frame=cap.read() data = pickle.dumps(frame) ### new code clientsocket.sendall(struct.pack("H", len(data))+data) ### new code
import socket import sys import cv2 import pickle import numpy as np import struct ## new HOST='' PORT=8089 s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) print 'Socket created' s.bind((HOST,PORT)) print 'Socket bind complete' s.listen(10) print 'Socket now listening' conn,addr=s.accept() ### new data = "" payload_size = struct.calcsize("H") while True: while len(data) < payload_size: data += conn.recv(4096) packed_msg_size = data[:payload_size] data = data[payload_size:] msg_size = struct.unpack("H", packed_msg_size)[0] while len(data) < msg_size: data += conn.recv(4096) frame_data = data[:msg_size] data = data[msg_size:] ### frame=pickle.loads(frame_data) print frame cv2.imshow('frame',frame)
您可能可以对所有这些进行很多优化(减少复制,使用缓冲区接口等),但至少您可以理解。