跳转到内容
STAGING SERVER
DEVELOPMENT SERVER

示例代码#

本章为常见的 pypylon 任务提供了实用且开箱即用的代码片段。这些示例代码可用作构建实际应用程序的基础模块。

单幅图像快照#

捕获单幅图像并进行处理。

from pypylon import pylon

def process(image):
    print(image.shape)

with pylon.InstantCamera(pylon.FirstFound) as camera:
    camera.StartGrabbingMax(1)

    with camera.RetrieveResult(5000) as grab_result:
        if grab_result.GrabSucceeded():
            image = grab_result.Array
            process(image)

连续采集循环#

连续处理图像。

camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly)

while camera.IsGrabbing():
    with camera.RetrieveResult(5000) as grab_result:
        if grab_result.GrabSucceeded():
            process(grab_result.Array)

保存图像到磁盘#

import cv2

pylon.ImagePersistence.Save(pylon.ImageFileFormat_Png, "image.png", grab_result)

配置软件触发#

pylon.SoftwareTriggerConfiguration.ApplyConfiguration(camera.NodeMap)
camera.ExecuteSoftwareTrigger()

配置硬件触发#

pylon.ConfigurationHelper.DisableAllTriggers(camera.NodeMap)
camera.TriggerSelector.Value = "FrameStart"
camera.TriggerMode.Value = "On"
camera.TriggerSource.Value = "Line1"

配置曝光和增益#

camera.ExposureAuto.Value = "Off"
camera.ExposureTime.Value = 3000

camera.GainAuto.Value = "Off"
camera.Gain.Value = 5

指定感兴趣区域 (ROI)#

有关更多详细信息,请参阅 Configuring Camera Parameters。

获取相机的左上角区域。

camera.StopGrabbing()

camera.Width.Value = 640
camera.Height.Value = 480
camera.OffsetX.Value = 0
camera.OffsetY.Value = 0

camera.StartGrabbing()

获取相机的中心区域。

camera.StopGrabbing()

camera.Width.Value = 640
camera.Height.Value = 480
camera.OffsetX.Value = (camera.MaxWidth - camera.Width) / 2
camera.OffsetY.Value = (camera.MaxHeight - camera.Height) / 2

camera.StartGrabbing()

将图像转换为 OpenCV 格式#

converter = pylon.ImageFormatConverter()
converter.OutputPixelFormat = pylon.PixelType_BGR8packed

image = converter.Convert(grab_result).GetArray()

使用 OpenCV 显示图像#

import cv2

cv2.imshow("Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

信息

或者,您可以使用 pylonDisplay image 函数。

带超时处理的采集#

from pypylon import pylon

try:
    with camera.RetrieveResult(
        1000,
        pylon.TimeoutHandling_ThrowException
    ) as grab_result:
        if grab_result.GrabSucceeded():
            process(grab_result.Array)

except Exception as e:
    log_error(e)

多相机设置#

使用 多个相机 的高效操作最好通过 InstantCameraArray来实现。它允许在一个循环中从所有相机进行抓取。

from pypylon import pylon

RETRIEVE_TIMEOUT_MS = 5000

factory = pylon.TlFactory.GetInstance()
devices = factory.EnumerateDevices()
camera_count = len(devices)

with pylon.InstantCameraArray(camera_count) as cameras:
    # Attach devices
    for i, camera in enumerate(cameras):
        camera.Attach(factory.CreateDevice(devices[i]))
        print("Using device:", camera.DeviceInfo.ModelName)

    # Start acquisition
    cameras.StartGrabbing()

    while cameras.IsGrabbing():
        with cameras.RetrieveResult(
            RETRIEVE_TIMEOUT_MS,
            pylon.TimeoutHandling_ThrowException
        ) as grab_result:

            if grab_result.GrabSucceeded():

                # Identify source camera
                camera_index = grab_result.CameraContext
                camera_name = cameras[camera_index].DeviceInfo.ModelName

                # Access image data (GenDC-safe)
                image = grab_result.Array

                print(
                    f"Camera {camera_index}: {camera_name}"
                    f" SizeX: {grab_result.Width} SizeY: {grab_result.Height} "
                    f" First pixel: {image[0, 0]}"
                )

            else:
                print("Error:", grab_result.ErrorCode, grab_result.ErrorDescription)

多线程处理#

import threading
import queue

image_queue = queue.Queue()

def grab_loop():
    while camera.IsGrabbing():
        with camera.RetrieveResult(5000) as grab_result:
            if grab_result.GrabSucceeded():
                image_queue.put(grab_result.Array)


def process_loop():
    while True:
        image = image_queue.get()
        process(image)
        image_queue.task_done()

安全关闭模式#

import threading

stop_event = threading.Event()

while not stop_event.is_set():
    # processing loop
    pass

stop_event.set()
camera.StopGrabbing()

录制视频#

import cv2

fourcc = cv2.VideoWriter_fourcc(*"XVID")
out = cv2.VideoWriter("output.avi", fourcc, 30, (640, 480))

out.write(image)

基础处理示例(ROI + 判定)#

import numpy as np

roi = image[100:200, 200:300]
mean = np.mean(roi)

if mean > 100:
    print("OK")
else:
    print("NOK")

核心要点#

  • 示例代码可加速开发。
  • 组合代码片段以构建更复杂的应用程序。
  • 根据您的特定用例调整示例代码。