# 安装opencv
pip install opencv-python
服务端:
import numpy as np
import cv2
from socket import *
s = socket(AF_INET, SOCK_DGRAM) # 创建UDP套接字
addr = ('0.0.0.0', 8081) # 0.0.0.0表示本机
s.bind(addr)
s.setblocking(0) # 设置为非阻塞模式
while True:
data = None
try:
data, _ = s.recvfrom(921600)
receive_data = np.frombuffer(data, dtype='uint8')
r_img = cv2.imdecode(receive_data, 1)
cv2.putText(r_img, "server", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
cv2.imshow('server', r_img)
except BlockingIOError as e:
pass
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
客户端:
import numpy as np
import cv2
from socket import *
# 127.0.0.1表示本机的IP,用于测试,使用时需要改为服务端的ip
addr = ('127.0.0.1', 8081)
cap = cv2.VideoCapture(0)
# 设置镜头分辨率,默认是640x480
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
s = socket(AF_INET, SOCK_DGRAM) # 创建UDP套接字
while True:
_, img = cap.read()
img = cv2.flip(img, 1)
# 压缩图片
_, send_data = cv2.imencode('.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, 50])
s.sendto(send_data, addr)
print(f'正在发送数据,大小:{img.size} Byte')
cv2.putText(img, "client", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
cv2.imshow('client', img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
s.close()
cv2.destroyAllWindows()
第一种情况:如果在本机上进行测试服务端和客户端IP地址都要写成127.0.0.1
第二种情况:如果将本机的视频流通过UPD传输给另外一台主机,本机作为客户端,另外一台主机作为服务端,客户端代码写入服务端主机的IP地址,服务端IP地址写0.0.0.0