import pyzed.sl as sl
import time
import cv2

zed = sl.Camera()
init = sl.InitParameters()
init.set_from_stream("127.0.0.1", 30000)
init.depth_mode = sl.DEPTH_MODE.NEURAL

print("尝试连接...")
err = zed.open(init)
print(f"结果: {err}")

if err == sl.ERROR_CODE.SUCCESS:
    print("连接成功！等待流就绪...")
    image_left = sl.Mat()
    image_depth = sl.Mat()

    for i in range(30):
        if zed.grab() == sl.ERROR_CODE.SUCCESS:
            zed.retrieve_image(image_left, sl.VIEW.LEFT)
            zed.retrieve_image(image_depth, sl.VIEW.DEPTH)

            left = image_left.get_data()
            depth = image_depth.get_data()

            cv2.imwrite("left_2i.png", left)
            cv2.imwrite("depth_2i.png", depth)
            print(f"已保存 left.png 和 depth.png，分辨率: {left.shape[1]}x{left.shape[0]}")
            break
        else:
            print(f"  等待中... ({i+1}/30)")
            time.sleep(0.5)
    else:
        print("超时：无法获取图像帧")

    image_left.free()
    image_depth.free()
    time.sleep(0.5)
    zed.close()
