콘텐츠로 바로 가기
STAGING SERVER
DEVELOPMENT SERVER

OpenCV와의 통합#

이 주제에서는 시각화 및 이미지 처리를 위해 Pypylon 이미지 획득 기능을 OpenCV와 통합하는 방법을 설명합니다.

왜 OpenCV를 사용해야 할까요?#

OpenCV는 가장 널리 사용되는 컴퓨터 비전 라이브러리 중 하나입니다. 이 라이브러리는 다음과 같은 기능을 제공합니다:

  • 고속 이미지 처리 알고리즘
  • 시각화 도구
  • 특성 탐지, 필터링 및 분석 지원
  • NumPy와의 상호 운용성

pypylon 이미지는 이미 NumPy 배열이므로, 통합이 매끄럽게 이루어집니다.

기본 워크플로우#

Camera → pypylon → NumPy Array → OpenCV → Display/Processing

간단한 예시#

import cv2
from pypylon import pylon

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

            # Display using OpenCV
            cv2.imshow("image", image)
            cv2.waitKey(0)
            cv2.destroyAllWindows()

Color Format 고려 사항#

OpenCV는 BGR 형식의 이미지를 기대하지만, 카메라에서는 다음과 같은 형식으로 이미지가 출력될 수 있습니다:

  • 모노(회색조)
  • 바이엘
  • RGB

이미지를 OpenCV 호환 형식으로 변환하기#

라이브 루프의 경우, 다음을 선호합니다. converter.ConvertToArray(grab_result): 이 방법은 변환된 픽셀을 미리 할당된 NumPy 배열에 직접 기록하므로, converter.Convert(grab_result).Array (참조: 이미지 처리 (자세한 내용은).

converter = pylon.ImageFormatConverter()
converter.OutputPixelFormat = pylon.PixelType_BGR8packed
image = converter.ConvertToArray(grab_result)

라이브 디스플레이 루프#

import cv2
from pypylon import pylon

with pylon.InstantCamera(pylon.FirstFound) as camera:
    camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly)

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

                cv2.imshow("Live", image)

                if cv2.waitKey(1) == 27:  # ESC to exit
                    break

    cv2.destroyAllWindows()

일반적인 OpenCV 연산#

그레이스케일 변환#

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

에지 검출#

edges = cv2.Canny(image, 50, 150)

흐림/필터링#

blur = cv2.GaussianBlur(image, (5, 5), 0)

오버레이 그리기#

cv2.rectangle(image, (50, 50), (200, 200), (0, 255, 0), 2)

NumPy와 OpenCV의 결합#

이 예제는 pypylon, NumPy, OpenCV를 결합한 완전한 비전 파이프라인을 보여줍니다. 이 파이프라인은 카메라에서 지속적으로 이미지를 캡처하고, 고정된 관심 영역(ROI)을 추출하며, 간단한 통계량(평균 밝기)을 계산한 후, 그 결과를 라이브 이미지에 직접 시각화합니다.

단계는 다음과 같습니다:

  1. ROI는 NumPy 슬라이싱을 사용하여 정의 및 추출됩니다.
  2. ROI의 평균 강도가 계산됩니다.
  3. ROI는 OpenCV의 사각형 오버레이를 사용하여 시각화됩니다.
  4. 간단한 규칙에 기반한 판정 결과(“밝은 영역”)가 이미지에 표시됩니다.

이 패턴은 실제 환경에서 흔히 볼 수 있는 워크플로를 나타냅니다:

Acquire → Select ROI → Compute Feature → Visualize → Decide
import cv2
from pypylon import pylon
import numpy as np

with pylon.InstantCamera(pylon.FirstFound) as camera:
    camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly)

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

                # Define ROI coordinates
                y1, y2 = 100, 200
                x1, x2 = 200, 300

                # Extract ROI
                roi = image[y1:y2, x1:x2]

                # Compute statistics
                mean = np.mean(roi)

                # Draw rectangle around ROI
                cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)

                if mean > 100:
                    cv2.putText(image, "Bright Region", (50, 50),
                                cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)

                cv2.imshow("Live", image)

                if cv2.waitKey(1) == 27:
                    break

    cv2.destroyAllWindows()

주요 핵심 사항#

  • pypylon은 NumPy를 통해 OpenCV와 원활하게 연동됩니다.
  • 색상 변환이 필요한 경우가 많습니다.
  • OpenCV는 강력한 시각화 및 처리 도구를 제공합니다.
  • NumPy와 OpenCV를 결합하면 유연한 파이프라인을 구축할 수 있습니다.