目录
服务端(发送端)
import pyrealsense2 as rs
import socket
import cv2
import numpy as np
import struct
# 配置 RealSense 相机
pipeline = rs.pipeline()
config = rs.config()
config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)
# 开始捕获视频
pipeline.start(config)
# 配置 UDP 服务器
UDP_IP = "127.0.0.1" # 目标计算机的 IP 地址
UDP_PORT = 5005
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
# 获取帧
frames = pipeline.wait_for_frames()
color_frame = frames.get_color_frame()
# 将帧转换为 OpenCV 图像
color_image = np.asanyarray(color_frame.get_data())
# 显示图像
cv2.imshow('RealSense server', color_image)
# 将图像转换为字符串并发送到目标计算机
# data = color_image.tostring()
# 将图像转换为JPEG格式
_, jpeg_image = cv2.imencode('.jpg', color_image)
data = jpeg_image.tobytes()
# 【定义文件头、数据】
fread = struct.pack('i', len(data))
# 【发送文件头、数据】
sock.sendto(fread, (UDP_IP, UDP_PORT))
# 每次发送x字节,计算所需发送次数
pack_size = 65507
send_times = len(data) // pack_size + 1
for count in range(send_times):
if count < send_times - 1:
sock.sendto(data[pack_size * count:pack_size * (count + 1)], (UDP_IP, UDP_PORT))
else:
sock.sendto(data[pack_size * count:],(UDP_IP, UDP_PORT))
# sock.sendto(data, (UDP_IP, UDP_PORT))
# 按下 ESC 键退出循环
if cv2.waitKey(1) == 27:
break
# 停止捕获视频并关闭窗口
pipeline.stop()
cv2.destroyAllWindows()
客户端(接收端)
import socket
import struct
import cv2
import numpy as np
ip_port = ('127.0.0.1', 5005)
BUFSIZE = 65507
udp_server_client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_server_client.bind(ip_port)
def receive():
# while True:
try:
while True:
# 获取数据头信息,第一个参数为信息,第二个参数是发送方ip地址
buffer, _ = udp_server_client.recvfrom(BUFSIZE)
# print(buffer)
# print(len(buffer)) # 可能为4或60000+
if len(buffer) == 4:
# print(buffer) # b';\xfb\x00\x00' # 每次都不一样的
# 解包,看看有多大(unpack返回的是只有一个元素的元组,如(64282,),元素个数貌似取决于fmt)
data_size = struct.unpack('i', buffer)[0]
# data_size = struct.unpack('i', buf)[0]
print(data_size) # 64315
else:
print('不是struct头,继续下次循环!')
# cv2.destroyAllWindows()
continue
# 重写接收程序
recv_times = data_size // BUFSIZE + 1
print(recv_times) # 按目前的BUFSIZE,为1或2,大部分为2
data_total = b''
recvd_size = 0
for count in range(recv_times):
data, _ = udp_server_client.recvfrom(BUFSIZE)
recvd_size += len(data)
data_total += data
# 判断data_total长度是否等于图片长度,不是就继续下次循环
# print(len(data_total))
if len(data_total) != data_size:
print('一定又是哪接收出错了,导致没接收上,继续下轮循环!')
continue
print('received!')
nparr = np.fromstring(data_total, np.uint8)
# print(nparr) # [255 216 255 ... 15 255 217] # 每次不一样的
img_decode = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
cv2.imshow('RealSense client', img_decode)
# 保存截图
# cv2.imwrite('{}.jpg'.format(time.clock()), img_decode)
if cv2.waitKey(1) == 27:
# cv2.destroyAllWindows()
break
except:
print('出现异常,继续调用receive()函数!')
if __name__ == '__main__':
receive()
发送端和接收端图像