샘플 코드#
Single Image Snapshot#
단일 이미지를 캡처하고 처리합니다.
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)
Continuous Acquisition Loop#
이미지를 연속적으로 처리합니다.
camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly)
while camera.IsGrabbing():
with camera.RetrieveResult(5000) as grab_result:
if grab_result.GrabSucceeded():
process(grab_result.Array)
Saving Image to Disk#
Configuring Software Trigger#
pylon.SoftwareTriggerConfiguration.ApplyConfiguration(camera.NodeMap)
camera.ExecuteSoftwareTrigger()
Configuring Hardware Trigger#
pylon.ConfigurationHelper.DisableAllTriggers(camera.NodeMap)
camera.TriggerSelector.Value = "FrameStart"
camera.TriggerMode.Value = "On"
camera.TriggerSource.Value = "Line1"
Configuring Exposure and Gain#
camera.ExposureAuto.Value = "Off"
camera.ExposureTime.Value = 3000
camera.GainAuto.Value = "Off"
camera.Gain.Value = 5
Specifying a Region Of Interest (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()
Converting Image to OpenCV Format#
converter = pylon.ImageFormatConverter()
converter.OutputPixelFormat = pylon.PixelType_BGR8packed
image = converter.Convert(grab_result).GetArray()
Displaying Image with OpenCV#
정보
또는 다음을 사용할 수 있습니다. 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")
주요 내용 요약#
- 샘플 코드는 개발 속도를 높여줍니다.
- 코드 조각을 조합하여 더 복잡한 애플리케이션을 구축할 수 있습니다.
- 특정 유스케이스에 맞게 샘플 코드를 조정하세요.