콘텐츠로 건너뛰기
STAGING SERVER
DEVELOPMENT SERVER

Python 프로그래머 가이드#

이 토픽에서는 Basler blaze 및 Smart blaze 카메라와 관련된 구체적인 정보를 제공하며 pypylon에 대한 포괄적인 개요를 제공하지는 않습니다.

Basler pylon의 공식 Python 언어 바인딩은 pypylon 프로젝트입니다. pypylon은 GitHub에 호스팅된 오픈 소스 프로젝트입니다. Basler 3D 카메라를 사용하려면 버전 4.0 이상을 사용해야 합니다.

공식 Python 래퍼의 대안으로 Python Harvester 라이브러리를 통해 카메라를 조작할 수 있습니다. Harvesters는 컴퓨터 비전 애플리케이션에서 이미지 취득 프로세스를 단순화하도록 설계된 Python 라이브러리입니다. GenTL Producer를 통한 이미지 취득이 가능합니다.

정보

이 항목의 모든 정보는 모든 blaze 및 Smart blaze 카메라 모델에 적용됩니다. 간결함을 위해 모든 모델을 통틀어 "blaze"로 지칭합니다.

pypylon#

pypylon 설치하기#

Python 프로그래밍 샘플#

pylon Supplementary Package for blaze에는 Python 및 pypylon을 사용하여 blaze 카메라에 액세스하는 방법을 보여주는 몇 가지 Python 프로그래밍 샘플이 포함되어 있습니다.

To open the folder containing the programming samples for blaze cameras, press the Win key, go to the Basler folder, and choose blaze Samples. A File Explorer window opens. The Python programming samples are located in the Python folder.

The Python samples are located in the /opt/pylon/share/pylon/Samples/blaze/Python/pypylon folder.

정보

샘플을 빌드하기 전에 쓰기 권한이 있는 원하는 위치에 샘플이 포함된 폴더를 복사하십시오.

각 샘플에는 샘플의 기능과 실행 요구 사항에 대한 정보를 제공하는 README.md 파일이 있습니다.

pypylon을 사용하여 blaze 카메라에 액세스하기#

SimpleGrab/simple_grab.py를 참조하거나 다음 스니펫을 사용하십시오.

from pypylon import pylon

dc = pylon.DeviceInfo()
dc.SetDeviceClass("BaslerGTC/Basler/GenTL_Producer_for_Basler_blaze_101_cameras")
camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice(dc))
camera.Open()

camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly)

while camera.IsGrabbing():
    grabResult = camera.RetrieveResult(1000, pylon.TimeoutHandling_ThrowException)

    if grabResult.GrabSucceeded():
        pylonDataContainer = grabResult.GetDataContainer()

        for componentIndex in range(pylonDataContainer.DataComponentCount):

            pylonDataComponent = pylonDataContainer.GetDataComponent(componentIndex)
            if pylonDataComponent.ComponentType == pylon.ComponentType_Intensity:
                intensity = pylonDataComponent.Array
                _2d_intensity = intensity.reshape(pylonDataComponent.Height, pylonDataComponent.Width)

            pylonDataComponent.Release()

    grabResult.Release()

camera.StopGrabbing()

Harvester#

Harvester 설치하기#

명령줄에서 다음 명령을 실행합니다.

pip3 install harvesters

Python Harvester 프로그래밍 샘플#

pylon Supplementary Package for blaze에는 Python 및 Harvester를 사용하여 blaze 카메라에 액세스하는 방법을 보여주는 몇 가지 Python 프로그래밍 샘플이 포함되어 있습니다.

To open the folder containing the programming samples for blaze cameras, press the Win key, go to the Basler folder, and choose blaze Samples. A File Explorer window opens. The Python programming samples are located in the Python folder.

The Python Harvester samples are located in the /opt/pylon/share/pylon/Samples/blaze/Python/Harvester folder.

정보

샘플을 빌드하기 전에 쓰기 권한이 있는 원하는 위치에 샘플이 포함된 폴더를 복사하십시오.

각 샘플에는 샘플의 기능과 실행 요구 사항에 대한 정보를 제공하는 README.md 파일이 있습니다.

Linux

pylon Software Suite 및 pylon Supplementary Package for blaze를 /opt/pylon이외의 위치에 설치한 경우, Harvester가 blaze 카메라용 GenTL Producer를 로드할 경로를 수정해야 합니다.

샘플 코드에서 다음 항목을 검색하십시오. /opt/pylon/lib/gentlproducer/gtl 그런 다음 경로를 조정하십시오.

Harvester를 사용하여 blaze 카메라에 액세스하기#

Harvester를 사용하여 사용 가능한 모든 blaze 카메라를 찾으려면 다음 단계를 수행하십시오.

  1. Harvester 모듈을 가져옵니다.
    from harvesters.core import Harvester
    
  2. Harvester 객체를 인스턴스화합니다.
    h = Harvester()
    
  3. blaze 카메라용 GenTL Producer를 로드합니다.

    h.add_file(r"C:\Program Files\Basler\pylon\Runtime\x64\ProducerBaslerBlazePylon.cti")
    
    h.add_file("/opt/pylon/lib/gentlproducer/gtl/ProducerBaslerBlazePylon.cti")
    
  4. 사용 가능한 장치 목록을 업데이트합니다.

    h.update()
    

  5. 사용 가능한 장치에 대한 정보를 가져옵니다.
    h.device_info_list
    

카메라에 연결하려면 다음을 사용하십시오. h.create() 함수입니다.

다음 구문은 사용 가능한 첫 번째 blaze 카메라에 연결합니다.

ia = h.create(0)

특정 카메라를 열려면 다음을 통해 제공되는 Property를 사용하여 지정할 수 있습니다. device_info_list Harvester 클래스 객체의 Property.

예:

ia = h.create(serial_number='9032635')

지정자는 열려는 장치를 고유하게 식별해야 합니다. 둘 이상의 카메라가 조건에 일치하는 경우 장치를 열 수 없습니다.

카메라 연결을 해제하려면 다음 명령을 실행합니다.

ia.destroy()

카메라 Property 액세스#

카메라 파라미터는 이미지 획득 장치의 remote_device Property를 통해 액세스할 수 있습니다. 원격 장치의 node_map Property는 모든 카메라 파라미터에 대한 액세스를 제공합니다.

예:

# Get a parameter.
operatingMode = ia.remote_device.node_map.OperatingMode.value
# Set a parameter.
ia.remote_device.node_map.OperatingMode.value = 'ShortRange'

사용 가능한 모든 카메라 파라미터 목록을 가져오려면 다음 명령을 사용하십시오.

dir(ia.remote_device.node_map)

blaze 카메라 파라미터 설정 및 가져오기 예제에 대해서는 SimpleGrab sample을 참조하십시오.

데이터 취득#

정보

Harvester는 GenICam GenDC 스트리밍 형식을 지원하지 않으므로, 데이터를 획득하기 전에 항상 GenDC 스트리밍 형식을 비활성화해야 합니다. GenDC 스트리밍 형식을 비활성화하려면 다음 명령을 사용하십시오.

ia.remote_device.node_map.GenDCStreamingMode.value = "Off"

blaze 카메라에서 획득한 버퍼에는 여러 구성 요소가 포함될 수 있습니다. Range, Intensity 및 Confidence 구성 요소가 있습니다.

다음 코드 조각은 사용 가능한 모든 구성 요소를 활성화하고 깊이 데이터가 포인트 클라우드로 제공되도록 Range 구성 요소의 Pixel Format을 구성합니다. 포인트 클라우드에서는 각 센서 픽셀에 x, y, z 좌표 삼중항이 할당됩니다.

ia.remote_device.node_map.ComponentSelector.value = "Range"
ia.remote_device.node_map.ComponentEnable.value = True
ia.remote_device.node_map.PixelFormat.value = "Coord3D_ABC32f"

ia.remote_device.node_map.ComponentSelector.value = "Intensity"
ia.remote_device.node_map.ComponentEnable.value = True
ia.remote_device.node_map.PixelFormat.value = "Mono16"

ia.remote_device.node_map.ComponentSelector.value = "Confidence"
ia.remote_device.node_map.ComponentEnable.value = True
ia.remote_device.node_map.PixelFormat.value = "Confidence16"

포인트 클라우드 대신 깊이 맵을 사용하려면 다음과 같이 Range 구성 요소를 구성하십시오.

ia.remote_device.node_map.ComponentSelector.value = "Range"
ia.remote_device.node_map.ComponentEnable.value = True
ia.remote_device.node_map.PixelFormat.value = "Coord3D_C16"

획득을 시작하려면 이미지 획득 장치의 start() 함수를 호출합니다.

ia.start()

일반적인 획득 루프는 다음과 같습니다.

ia.start()
while True:
    with ia.fetch() as buffer:
        # Do something with the buffer.
ia.stop()

정보

버퍼는 다음 내에서만 유효합니다. with statement이며 스코프를 벗어날 때 파기됩니다. 스코프 외부에서 버퍼를 사용하려면 with 을(를) 사용하여 np.copy() Deep Copy를 수행해야 합니다.

다음 코드 스니펫은 버퍼의 구성 요소에 액세스하는 방법을 보여줍니다.

with ia.fetch() as buffer:
      depth = buffer.payload.components[0]
      intensity = buffer.payload.components[1]
      confidence = buffer.payload.components[2]

Harvester는 구성 요소를 1차원 NumPy 배열로 반환합니다.

이후 처리를 위해 1D 배열을 2D 또는 3D 배열로 리셰이프(Reshape)하는 것이 편리할 수 있습니다.

depth_arr = depth.data.reshape(pointcloud.height, pointcloud.width,
                              int(pointcloud.num_components_per_pixel))

intenstiy_arr = intensity.data.reshape(intensity.height, intensity.width)

confidence_arr = confidence.data.reshape(confidence.height, confidence.width)

num_components_per_pixel 은(는) Range 구성 요소의 Pixel Format에 따라 다릅니다. Pixel Format이 다음 값과 같으면 Coord3D_ABC32f, Range 구성 요소는 포인트 클라우드(Point Cloud)로 표현되며, 즉 각 픽셀에 대해 3개의 부동 소수점 값이 존재합니다. 그 결과 각 픽셀의 x, y 및 z 좌표를 저장하는 3차원 배열이 생성됩니다.

Pixel Format이 다음 값과 같으면 Coord3D_C16, Range 구성 요소는 16비트 회조도 이미지로 표현되며, 즉 각 픽셀에 대해 하나의 16비트 정수 값이 존재합니다.

깊이 맵의 회조도를 mm 단위로 변환하는 방법에 대한 자세한 내용은 Processing Measurement Results 항목을 참조하십시오.

데이터 취득이 완료되면 다음을 호출합니다. stop() 함수를 호출합니다.

ia.stop()

위에서 설명한 그랩 루프 구현의 대안으로, Harvester는 그랩 루프를 구현하고 콜백을 발생시켜 애플리케이션에 알리는 백그라운드 스레드를 제공할 수 있습니다. 이 접근 방식은 SimpleGrab_Callback sample에 나와 있습니다.

응용 프로그램 디버깅 및 GigE Vision 하트비트 제어#

blaze 카메라와 같은 GigE Vision 카메라는 애플리케이션이 카메라에 특수 네트워크 패킷을 정기적으로 전송하여 주기적으로 카메라에 액세스할 것을 요구합니다. 카메라가 이러한 하트비트를 수신하지 못하면 연결이 끊어진 것으로 간주하고 애플리케이션의 명령을 더 이상 수락하지 않습니다.

애플리케이션을 실행할 때 blaze 카메라용 GenTL Producer는 일반적으로 이러한 하트비트를 생성합니다. 애플리케이션에 중단점(Breakpoint)을 설정하고 해당 중단점에 도달하면 디버거는 하트비트를 전송하는 스레드를 포함하여 모든 스레드를 일시 중단합니다. 따라서 애플리케이션을 디버깅하고 코드를 한 줄씩 실행(Single-stepping)하는 동안에는 카메라로 하트비트가 전송되지 않습니다. 결과적으로 카메라는 하트비트 타임아웃을 감지하고 연결을 닫습니다. 하트비트 타임아웃의 기본값은 3000 ms입니다.

이 문제를 해결하려면 개발 중에 하트비트 타임아웃을 늘려야 합니다. 다음과 같은 이름의 환경 변수를 설정하고 GEV_HEARTBEAT_TIMEOUT 원하는 타임아웃을 밀리초 단위로 지정하여 이 작업을 수행할 수 있습니다.

또는 다음과 같이 애플리케이션에서 하트비트 타임아웃을 설정할 수 있습니다.

ia.device.node_map.HeartbeatTimeout.value=600000

정보

하트비트 타임아웃을 높은 값으로 늘린 후 디바이스를 제대로 닫지 않고 애플리케이션을 중지하면, 카메라를 다시 열 수 없으며 디바이스가 현재 사용 중이라는 오류가 발생합니다. 이 상황은 디버거를 사용하여 애플리케이션을 중지하거나 애플리케이션이 예기치 않게 종료될 때 발생할 수 있습니다. 카메라를 다시 열려면 타임아웃이 경과할 때까지 기다리거나 카메라에서 네트워크 케이블을 분리해야 합니다.