我正在使用树莓派进行研究。我想将树莓派(客户端)的视频流传输到项目的笔记本电脑(服务器)。经过两天的研究,我发现了以下代码。
客户
import socket
import cv2
import pickle
import struct
device = cv2.VideoCapture(-1)
ok, frame = device.read()
host = '192.168.1.4'
port = 12345
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((host, port))
while True:
ok, frame = device.read()
data = pickle.dumps(frame)
client_socket.sendall(struct.pack("L", len(data)) + data)
cv2.imshow("",frame)
if cv2.waitKey(1) == 27:
break
device.release()
cv2.destroyAllWindows()
服务器
import socket
import cv2
import numpy as np
import time
import pickle
import struct
host = '192.168.1.4'
port = 12345
client_socket = None
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(5)
conn, addr = server_socket.accept()
data = b''
payload_size = struct.calcsize("L")
while True:
while len(data) < payload_size:
#data += conn.recv(90456)
data += conn.recv(4096)
packed_msg_size = data[:payload_size]
data = data[payload_size:]
msg_size = struct.unpack("L", 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.size)
cv2.imshow('frame', frame)
cv2.waitKey(1)
但是有很大的滞后。我想要的是实时流式传输(如果可能)或尽可能接近实时流式传输(最小延迟)。有人可以建议UDP,但由于它不能保证获得所有帧。
有人可以建议我改进我的代码吗?有帮助吗? 提前非常感谢您!