콘텐츠로 건너뛰기
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 형식의 이미지를 예상하지만, 카메라는 다음과 같은 형식을 출력할 수 있습니다:

  • Mono (그레이스케일)
  • Bayer
  • 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)

Edge Detection#

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를 결합한 완전한 비전 파이프라인을 보여줍니다. 카메라에서 이미지를 지속적으로 획득하고, 고정된 Image ROI를 추출하며, 간단한 통계(평균 밝기)를 계산하고, 라이브 이미지에 결과를 직접 시각화합니다.

단계는 다음과 같습니다.

  1. NumPy 슬라이싱을 사용하여 Image ROI를 정의하고 추출합니다.
  2. Image ROI의 평균 밝기가 계산됩니다.
  3. OpenCV 사각형 오버레이를 사용하여 Image ROI가 시각화됩니다.
  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를 결합하면 유연한 파이프라인을 구축할 수 있습니다.