我想要使用如下代码实现UDP图传:
# coding=utf-8
import socket
import numpy as np
import cv2
UDP_IP = '192.168.1.157'
UDP_PORT = 12345
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))
# 初始化接收缓冲区
pkt_header_size = 8 # 4字节魔数 + 4字节长度
expected_size = 0
received_data = bytearray()
def smart_upscale(frame, scale):
return cv2.resize(
frame,
(frame.shape[1]*scale, frame.shape[0]*scale),
interpolation=cv2.INTER_NEAREST # 可替换为INTER_LINEAR获得更好质量
)
while True:
data, addr = sock.recvfrom(65535)
# 处理包头
if len(data) == pkt_header_size:
magic = int.from_bytes(data[:4], 'big')
if magic == 0xABCD1234:
expected_size = int.from_bytes(data[4:8], 'big')
received_data = bytearray()
continue
# 收集数据包
received_data.extend(data)
# 数据接收完成
if len(received_data) >= expected_size and expected_size > 0:
# 解码图像
img = cv2.imdecode(np.frombuffer(received_data[:expected_size], np.uint8), cv2.IMREAD_COLOR)
big_img = smart_upscale(img, 4)
if img is not None:
cv2.imshow("Receiver Preview", big_img)
# 重置状态
expected_size = 0
received_data = bytearray()
if cv2.waitKey(1) == 27:
break
cv2.destroyAllWindows()
windows中运行该程序,同时连接摄像头的开发板上运行相应的程序,程序在正常的运行但是没有图像出现,由于没有报错,IP地址应该是没问题的