샘플 코드#
단일 이미지 스냅샷#
단일 이미지를 촬영하고 처리합니다.
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)
이미지를 디스크에 저장하기#
소프트웨어 트리거 구성#
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를 사용하여 이미지 표시하기#
정보
또는 다음을 사용할 수도 있습니다. pylonDisplay 이미지 함수.
타임아웃 처리를 포함한 캡처#
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")
주요 내용#
- 샘플 코드는 개발 속도를 높여줍니다.
- 코드 스니펫을 결합하여 더 복잡한 애플리케이션을 구축하세요.
- 샘플 코드를 구체적인 사용 사례에 맞게 수정하십시오.