示例一:
使用Basler Pylon Python 接口库(pypylon)来实现相机图像采集的功能。 主要实现了从相机中实时抓取图像并显示,通过这种方式进行图像采集。集成了 Basler Pylon Python 接口库,提供了用于相机设备控制和图像处理的功能。
#引入了相机模块和通用相机访问模块,并引入了时间模块。
from pypylon import pylon
from pypylon import genicam
import time
# 在 try 块中进行相机图像采集:
try:
# 创建了一个 PylonImageWindow 对象 imageWindow,用于显示图像。
imageWindow = pylon.PylonImageWindow()
imageWindow.Create(1)
# # 创建了一个 InstantCamera 对象 camera,并连接到第一个找到的相机设备。
camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice())
# # 打印相机设备的型号名称。
print("Using device ", camera.GetDeviceInfo().GetModelName())
# 调用 StartGrabbingMax 方法开始连续抓取图像,参数设置为最大 10000 张图像以及最新图像模式。
camera.StartGrabbingMax(10000, pylon.GrabStrategy_LatestImageOnly)
# 进入循环,检查是否正在抓取图像,如果是,等待图像并获取结果。
while camera.IsGrabbing():
# Wait for an image and then retrieve it. A timeout of 5000 ms is used.
grabResult = camera.RetrieveResult(5000, pylon.TimeoutHandling_ThrowException)
# 如果成功获取图像,则在图像窗口中显示图像。
# 如果获取过程出现错误,则打印错误信息。
# 释放采集结果,并等待一段时间后继续下一个循环。
if grabResult.GrabSucceeded():
imageWindow.SetImage(grabResult)
imageWindow.Show()
else:
print("Error: ",
grabResult.ErrorCode)
grabResult.Release()
time.sleep(0.05)
# 如果图像窗口不可见,则停止图像抓取。
if not imageWindow.IsVisible():
camera.StopGrabbing()
# 最后需手动关闭相机和图像窗口。
camera.Close()
imageWindow.Close()
# 在 except genicam.GenericException as e 块中处理异常情况,打印异常信息。
except genicam.GenericException as e:
# Error handling.
print("An exception occurred.")
print(e.GetDescription())
示例二:
使用Basler Pylon Python 接口库(pypylon)来实现相机图像采集的功能。
from pypylon import pylon
# import cv2
from datetime import date, datetime
# search device and get device
def search_get_device():
tl_factory = pylon.TlFactory.GetInstance()
for dev_info in tl_factory.EnumerateDevices():
print("DeviceClass:", dev_info.GetDeviceClass())
if dev_info.GetDeviceClass() == 'BaslerGigE': # 千兆网(GigE)
print(f"ModelName:{dev_info.GetModelName()}\n"f"IP:{dev_info.GetIpAddress()}")
camera = pylon.InstantCamera(tl_factory.CreateDevice(dev_info))
break
else:
raise EnvironmentError("no GigE device found")
return camera
def save_multi_image():
cam = search_get_device()
img = pylon.PylonImage()
num_img_to_save = 5
cam.Open()
cam.StartGrabbing() # Starts the grabbing for a maximum number of images.
for i in range(num_img_to_save):
with cam.RetrieveResult(2000) as result:
# Calling AttachGrabResultBuffer creates another reference to the
# grab result buffer. This prevents the buffer's reuse for grabbing.
img.AttachGrabResultBuffer(result)
# print("Img reference:",img)
# print("Result reference",result)
# The JPEG format that is used here supports adjusting the image
# quality (100 -> best quality, 0 -> poor quality).
ipo = pylon.ImagePersistenceOptions()
quality = 100 - i * 20
# quality = 100
ipo.SetQuality(quality)
filename = f"saved_pypylon_img_{quality}.jpeg"
img.Save(pylon.ImageFileFormat_Jpeg, filename)#, ipo)
img.Release()
cam.StopGrabbing()
cam.Close()
def grab_show_image():
cam = search_get_device()
cam.Open()
# Grabing Continusely (video) with minimal delay
cam.StartGrabbing(pylon.GrabStrategy_LatestImageOnly)
converter = pylon.ImageFormatConverter()
# converting to opencv bgr format
converter.OutputPixelFormat = pylon.PixelType_BGR8packed
converter.OutputBitAlignment = pylon.OutputBitAlignment_MsbAligned
# Wait for an image and then retrieve it. A timeout of 5000 ms is used.
grabResult = cam.RetrieveResult(5000, pylon.TimeoutHandling_ThrowException)
# Image grabbed successfully?
# print(dir(grabResult))
if grabResult.GrabSucceeded():
# Access the image data.
print("SizeX: ", grabResult.Width)
print("SizeY: ", grabResult.Height)
# img type class 'numpy.ndarray', shape 1944*2592*2
img = grabResult.Array
print("Gray value of first pixel: ", img[0, 0])
# After convert to image(ndarray) shape 1944*2592*3
image = converter.Convert(grabResult)
weld_img = image.GetArray()
# cv2.namedWindow('test', cv2.WINDOW_NORMAL)
# cv2.imshow('test', weld_img)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
print('weld_img_type',type(weld_img))
print('img_type', type(img))
print(weld_img[weld_img[:,:,1] != img[:,:,0]])
else:
print("Error: ", grabResult.ErrorCode, grabResult.ErrorDescription)
grabResult.Release()
cam.Close()
# grab_show_image()
def grab_image_save():
cam = search_get_device()
cam.Open()
save_img = pylon.PylonImage()
# Grabing Continusely (video) with minimal delay
cam.StartGrabbing(pylon.GrabStrategy_LatestImageOnly)
# Wait for an image and then retrieve it. A timeout of 5000 ms is used.
grabResult = cam.RetrieveResult(5000, pylon.TimeoutHandling_ThrowException)
# Image grabbed successfully
# print(dir(grabResult))
if grabResult.GrabSucceeded():
# save image
filename = f"Image{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.jpeg"
save_img.AttachGrabResultBuffer(grabResult)
ipo = pylon.ImagePersistenceOptions()
ipo.SetQuality(quality=100)
save_img.Save(pylon.ImageFileFormat_Jpeg, filename, ipo)
save_img.Release()
# Access the image data.
# img type class 'numpy.ndarray', shape 1944*2592*2
img = grabResult.Array
print('img_type', type(img))
else:
print("Error: ", grabResult.ErrorCode, grabResult.ErrorDescription)
grabResult.Release()
cam.Close()
return img
grab_image_save()
示例三:
#导入需要的库
from pypylon import pylon
#创建一个相机实例
camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice())
#打开相机
camera.Open()
# demonstrate some feature access
new_width = camera.Width.GetValue() - camera.Width.GetInc()
if new_width >= camera.Width.GetMin():
camera.Width.SetValue(new_width)
numberOfImagesToGrab = 100
#开始图像采集
camera.StartGrabbingMax(numberOfImagesToGrab)
#进行图像采集
while camera.IsGrabbing():
grabResult = camera.RetrieveResult(5000, pylon.TimeoutHandling_ThrowException)
if grabResult.GrabSucceeded():
# Access the image data.
#在这里可以对获取到的图像进行处理
#例如保存到本地或进行图像处理
print("SizeX: ", grabResult.Width)
print("SizeY: ", grabResult.Height)
img = grabResult.Array
print("Gray value of first pixel: ",img[0, 0])
grabResult.Release()
#停止图像采集
camera.StopGrabbing()
#关闭相机
camera.Close()