跳至內容
測試伺服器
開發伺服器

範例程式碼#

本章節提供了適用於常見 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)#

如需更多詳細資訊,請參閱「設定攝影機參數」。

從攝影機取得左上角的位置。

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")

重點摘要#

  • 範例程式碼能加快開發速度。
  • 將程式碼片段組合起來,以建構更複雜的應用程式。
  • 請根據您的具體使用情境調整範例程式碼。