引自免费微信小程序:皆我百晓生
要实现将摄像头视频流及检测到的目标(如圆圈)的坐标传输到上位机,你需要在客户端(ZED相机)上进行编码处理,并在服务器端(Windows 10主机)上解码接收。这里是一个详细的步骤指南,包括客户端和服务器端的代码示例。
首先,确保在客户端和服务器端都安装了OpenCV、numpy和json库。在Python环境中可以使用pip install opencv-python numpy json命令进行安装。
客户端(ZED相机)代码:
import cv2
import numpy as np
import socket
import struct
import json
# 配置目标 Windows 10 主机的 IP 地址和端口
HOST = 'Windows10_IP_ADDRESS' # 请替换为实际IP地址
PORT = 12345
server_address = (HOST, PORT)
# 创建 UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 假设这是你的圆圈检测函数
def detect_circles(image):
# 这里是你的圆圈检测代码,返回格式如[(center_x, center_y), ...]
pass
while True:
# 获取摄像头帧
frame = get_frame_from_camera() # 请替换为实际获取帧的方法
# 检测圆圈
circles = detect_circles(frame)
if circles is not None:
# 处理发现的圆圈
for i, circle in enumerate(circles):
center_x, center_y = circle
# 根据需求计算世界坐标或其他相关信息...
world_x, world_y, world_z, distance = calculate_world_coordinates(circle) # 请替换为实际计算方法
# 将目标信息打包成 JSON
target_info = {
'center_x': center_x,
'center_y': center_y,
'world_x': world_x,
'world_y': world_y,
'world_z': world_z,
'distance': distance
}
target_info_json = json.dumps(target_info)
# 发送目标信息
sock.sendto(target_info_json.encode(), server_address)
# 编码和发送视频帧
_, frame_jpeg = cv2.imencode('.jpg', frame)
sock.sendto(frame_jpeg.tobytes(), server_address)
sock.close()
服务器端(Windows 10主机)代码:
import socket
import struct
import json
import cv2
import numpy as np
# 配置监听的端口
PORT = 12345
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(('localhost', PORT))
while True:
data, address = server_socket.recvfrom(4096)
# 解析目标信息
target_info_json = data.decode()
target_info = json.loads(target_info_json)
# 解析视频帧
frame_data = data[len(target_info_json):]
# 从字节序列恢复图像
frame = np.frombuffer(frame_data, dtype=np.uint8)
frame = cv2.imdecode(frame, cv2.IMREAD_COLOR)
# 在此处处理接收到的视频帧和目标信息
print(f"Received target info: {target_info}")
cv2.imshow("Video Feed", frame)
key = cv2.waitKey(1)
if key == ord('q'):
break
cv2.destroyAllWindows()
server_socket.close()
注意:以上代码只是一个基本框架,具体实现可能需要根据你的ZED相机驱动和圆圈检测算法进行调整。在服务器端,你需要根据实际情况处理接收到的视频帧和目标信息,例如显示视频流、存储数据等。
