Leap Motion Controller手势采集Python代码无法连接LMC且输出空文件问题
问题根因
- 代码初始化
Leap.Controller()后立刻读取帧数据,未预留控制器与LMC设备的连接握手时间,此时获取的frame为无效空帧,序列化后数据长度为0,最终生成的frame.data文件为空 - 无设备连接状态校验逻辑,无法确认LMC是否被系统正常识别
修正方案
添加连接等待和有效帧判断逻辑即可,修正后代码如下:
import sys import os import Leap import ctypes import time controller = Leap.Controller() # 等待设备连接,最多等待10秒 wait_time = 0 while not controller.is_connected and wait_time < 10: time.sleep(1) wait_time += 1 if not controller.is_connected: print("LMC设备连接超时,请检查设备和驱动状态") sys.exit(1) # 等待获取有效帧,可根据需求调整是否需要检测到手再采集 while True: frame = controller.frame() if frame.is_valid: break time.sleep(0.1) hands = frame.hands pointables = frame.pointables fingers = frame.fingers tools = frame.tools serialized_tuple = frame.serialize serialized_data = serialized_tuple[0] serialized_length = serialized_tuple[1] data_address = serialized_data.cast().__long__() buffer = (ctypes.c_ubyte * serialized_length).from_address(data_address) with open(os.path.realpath('frame.data'), 'wb') as data_file: data_file.write(buffer) print("帧数据已成功写入frame.data")
额外检查项
- 运行代码前需先启动Leap Motion控制面板,确认面板内设备状态显示为已连接
- 确认Anaconda Python2环境中安装的Leap库版本与设备使用的SDK版本匹配,不要混用V2和V4版本SDK
- 若仍提示连接失败,打开系统设备管理器,检查Leap Motion驱动是否正常安装,无异常黄色感叹号标识
内容的提问来源于stack exchange,提问作者kimia
相关产品推荐
相关产品推荐

