Basler 相机是工业机器视觉领域常用的高性能相机,其控制编程通常通过 Basler 提供的 Pylon SDK 实现。下面我将为你提供一个基于 Python 的 Basler 相机控制程序示例,实现相机的基本操作。
# Basler相机控制程序
# 需安装pylon SDK及pypylon库
# 安装命令: pip install pypylon
from pypylon import pylon
import cv2
import numpy as np
import time
class BaslerCameraController:
def __init__(self):
self.camera = None
self.converter = pylon.ImageFormatConverter()
# 转换为OpenCV格式
self.converter.OutputPixelFormat = pylon.PixelType_BGR8packed
self.converter.OutputBitAlignment = pylon.OutputBitAlignment_MsbAligned
self.is_running = False
def connect_camera(self, index=0):
"""连接相机,默认连接第0个相机"""
try:
# 枚举所有可用相机
devices = pylon.TlFactory.GetInstance().EnumerateDevices()
if not devices:
raise Exception("未找到任何Basler相机")
print(f"找到{len(devices)}个相机:")
for i, device in enumerate(devices):
print(f" 相机{i}: {device.GetFriendlyName()}")
# 创建相机实例并连接
self.camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateDevice(devices[index]))
self.camera.Open()
print(f"已连接相机: {self.camera.GetDeviceInfo().GetFriendlyName()}")
return True
except Exception as e:
print(f"连接相机失败: {str(e)}")
return False
def set_camera_parameters(self, exposure_time=None, gain=None, width=None, height=None):
"""设置相机参数"""
if not self.camera or not self.camera.IsOpen():
print("请先连接相机")
return False
try:
# 设置曝光时间 (单位: 微秒)
if exposure_time:
if self.camera.ExposureTimeEnable.GetValue():
self.camera.ExposureTime.SetValue(exposure_time)
print(f"已设置曝光时间: {exposure_time} μs")
# 设置增益 (单位: dB)
if gain is not None:
self.camera.Gain.SetValue(gain)
print(f"已设置增益: {gain} dB")
# 设置图像宽度
if width:
self.camera.Width.SetValue(width)
print(f"已设置图像宽度: {width}")
# 设置图像高度
if height:
self.camera.Height.SetValue(height)
print(f"已设置图像高度: {height}")
return True
except Exception as e:
print(f"设置相机参数失败: {str(e)}")
return False
def start_grabbing(self, num_images=10, save_path=None):
"""开始采集图像"""
if not self.camera or not self.camera.IsOpen():
print("请先连接相机")
return False
try:
self.is_running = True
self.camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly)
for i in range(num_images):
if not self.is_running:
break
def stop_grabbing(self):
"""停止采集图像"""
if self.camera and self.camera.IsGrabbing():
self.camera.StopGrabbing()
self.is_running = False
print("已停止图像采集")
cv2.destroyAllWindows()
def close_camera(self):
"""关闭相机连接"""
self.stop_grabbing()
if self.camera and self.camera.IsOpen():
self.camera.Close()
print("已关闭相机连接")
self.camera = None
if __name__ == "__main__":
# 创建相机控制器实例
camera_controller = BaslerCameraController()
try:
# 连接相机
if camera_controller.connect_camera():
# 设置相机参数
camera_controller.set_camera_parameters(
exposure_time=5000, # 曝光时间5000微秒
gain=0, # 增益0dB
# width=1280, # 可根据需要设置图像宽度
# height=960 # 可根据需要设置图像高度
)
# 开始采集10张图像,保存到当前目录
camera_controller.start_grabbing(num_images=10, save_path=".")
except KeyboardInterrupt:
print("用户中断程序")
finally:
# 关闭相机连接
camera_controller.close_camera()
这个 Basler 相机控制程序实现了以下功能:
使用说明:
如果需要更复杂的功能,如触发控制、序列采集或高级参数设置,可以参考 Basler 官方的 Pylon SDK 文档进行扩展。