# 导入 socket、sys 模块 import socket import numpy as np import cv2 import time def read_and_process_txt(file_path): processed_data = [] with open(file_path, "r") as file: for line in file: # 去除每行末尾的换行符 line = line.strip() # 按空格分割每行 items = line.split() # 这里简单地将分割后的数据作为一个列表加入到结果列表中 # 实际应用中,你可能需要根据具体数据结构进行更复杂的处理 processed_data.append(items) # 如果你确实需要将这些数据转换为JSON,可能需要构造一个合适的结构 # 例如,如果你的文本文件每行代表一个对象的属性,你可能需要构建字典 # 下面是一个假设的例子,将每行转换为字典并尝试转为JSON字符串 json_data = {items[0]: items[1] for items in processed_data} try: return json_data except TypeError as e: print(f"Error converting to JSON: {e}") baseConfig = read_and_process_txt("./base.txt") print(baseConfig) # 创建 socket 对象 socketlocal = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 设置本地主机名 host = "127.0.0.1" # 设置端口号 port = int(baseConfig["udpPngPort1"]) # 1.创建一个udp套接字 udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) local_addr = (host, port) udp_socket.bind(local_addr) prev_frame_time = 0 new_frame_time = 0 count = 0 countTotal = 0 while True: # 接收数据: data = udp_socket.recv(1219112 * 2) # print("recv data",data) # 解码 nparr = np.frombuffer(data, np.uint8) # 解码成图片numpy img_decode = cv2.imdecode(nparr, cv2.IMREAD_COLOR) # 帧率计算 new_frame_time = time.time() if new_frame_time - prev_frame_time < 1: count += 1 else: countTotal = count count = 0 prev_frame_time = new_frame_time if count != 0: countTotal = max([countTotal, count]) cv2.putText( img_decode, "FPS:{}".format(countTotal), (30, 45), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1, ) if img_decode is not None and img_decode.shape[0] > 0 and img_decode.shape[1] > 0: cv2.imshow("result1", img_decode) if cv2.waitKey(1) & 0xFF == ord("q"): break