PyPylon API与Pylon Viewer协同:相机图像获取及连接控制咨询
关于PyPylon与Pylon Viewer同时访问相机的问题
核心结论
- 当Pylon Viewer已独占连接相机时,PyPylon无法直接获取图像——多数Basler相机默认采用独占访问模式,同一时间仅允许一个客户端建立有效连接。
- PyPylon没有提供主动断开Pylon Viewer连接的官方API,这是为了避免设备访问冲突、保障数据安全的设计逻辑。
可行解决方案
1. 切换相机至共享访问模式(推荐)
部分Basler相机支持共享访问模式(取决于型号和固件版本),开启后可允许Pylon Viewer与PyPylon同时连接:
- 通过Pylon Viewer设置:进入相机参数面板,找到
AccessControl组下的AccessMode,将其改为Shared - 通过PyPylon代码预设置(需确保无其他客户端连接时执行):
from pypylon import pylon # 初始化并打开相机 camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice()) camera.Open() # 修改为共享访问模式 camera.AccessControl.AccessMode.SetValue("Shared") camera.Close()
注意:共享模式下需避免两个客户端同时修改相机参数(如曝光时间、分辨率),否则可能引发配置冲突。
2. 临时暂停Pylon Viewer的图像采集
无需关闭Pylon Viewer,仅需点击Viewer工具栏的「Stop」按钮暂停图像流——此时相机连接会被保留,但不再独占采集资源,PyPylon可正常连接并获取单张图像。取图完成后,再在Viewer中点击「Start」恢复采集即可。
3. 脚本化整合对位与采集流程
如果调试阶段需频繁切换,可编写PyPylon脚本集成对位辅助功能,替代Pylon Viewer的部分操作,全程用代码控制相机:
from pypylon import pylon import cv2 # 初始化相机 camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice()) camera.Open() # 设置对位所需的相机参数 camera.ExposureTime.SetValue(10000) camera.Width.SetValue(1280) camera.Height.SetValue(720) # 启动实时预览用于对位 camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly) converter = pylon.ImageFormatConverter() converter.OutputPixelFormat = pylon.PixelType_BGR8packed print("对位完成后按q退出预览,将自动获取单张图像") while camera.IsGrabbing(): grab_result = camera.RetrieveResult(5000, pylon.TimeoutHandling_ThrowException) if grab_result.GrabSucceeded(): img = converter.Convert(grab_result).GetArray() # 添加对位标记(示例) cv2.putText(img, "对位参考点", (100, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,255,0), 2) cv2.imshow("对位预览", img) if cv2.waitKey(1) & 0xFF == ord('q'): break grab_result.Release() # 获取单张图像传入OpenCV camera.StartGrabbing(1) grab_result = camera.RetrieveResult(5000, pylon.TimeoutHandling_ThrowException) if grab_result.GrabSucceeded(): opencv_img = converter.Convert(grab_result).GetArray() print("成功获取图像,尺寸:", opencv_img.shape) # 此处可添加OpenCV处理逻辑 grab_result.Release() # 清理资源 camera.Close() cv2.destroyAllWindows()
注意事项
- 共享访问模式并非所有Basler相机都支持,需查阅对应型号的官方手册确认兼容性。
- 即使开启共享模式,两个客户端同时触发图像采集仍可能导致丢帧或数据异常,建议PyPylon取图时,让Viewer处于暂停状态。
内容的提问来源于stack exchange,提问作者sav8670
相关产品推荐
相关产品推荐

