Allen's 데이터 맛집
C#과 Basler Pylon을 사용한 비전 코딩: 비동기 이미지 그랩 및 처리 본문
C#과 Basler Pylon .NET API를 사용하여 비동기로 이미지를 그랩하고 처리하는 방법에 대해 설명하겠습니다. 이 샘플 코드는 카메라에서 이미지를 비동기적으로 수집하고, 수집된 이미지를 처리하는 과정을 보여줍니다. 비동기 처리를 통해 이미지를 수집하는 동안 다른 작업을 병렬로 수행할 수 있어 효율성을 높일 수 있습니다.
코드 설명
1. 코드 개요
이 샘플 프로그램은 카메라에서 이미지를 비동기적으로 수집하고, 이미지를 처리하는 과정을 보여줍니다. 프로그램은 여러 개의 버퍼를 사용하여 이미지를 수집하고, 수집된 이미지를 비동기적으로 처리합니다.
using System;
using Basler.Pylon;
namespace Grab
{
class Grab
{
internal static void Main()
{
// The exit code of the sample application.
int exitCode = 0;
try
{
// Create a camera object that selects the first camera device found.
// More constructors are available for selecting a specific camera device.
using (Camera camera = new Camera())
{
// Print the model name of the camera.
Console.WriteLine("Using camera {0}.", camera.CameraInfo[CameraInfoKey.ModelName]);
// Set the acquisition mode to free running continuous acquisition when the camera is opened.
camera.CameraOpened += Configuration.AcquireContinuous;
// Open the connection to the camera device.
camera.Open();
// The parameter MaxNumBuffer can be used to control the amount of buffers
// allocated for grabbing. The default value of this parameter is 10.
camera.Parameters[PLCameraInstance.MaxNumBuffer].SetValue(5);
// Start grabbing.
camera.StreamGrabber.Start();
// Grab a number of images.
for (int i = 0; i < 10; ++i)
{
// Wait for an image and then retrieve it. A timeout of 5000 ms is used.
IGrabResult grabResult = camera.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException);
using (grabResult)
{
// Image grabbed successfully?
if (grabResult.GrabSucceeded)
{
// Access the image data.
Console.WriteLine("SizeX: {0}", grabResult.Width);
Console.WriteLine("SizeY: {0}", grabResult.Height);
byte[] buffer = grabResult.PixelData as byte[];
Console.WriteLine("Gray value of first pixel: {0}", buffer[0]);
Console.WriteLine("");
// Display the grabbed image.
ImageWindow.DisplayImage(0, grabResult);
}
else
{
Console.WriteLine("Error: {0} {1}", grabResult.ErrorCode, grabResult.ErrorDescription);
}
}
}
// Stop grabbing.
camera.StreamGrabber.Stop();
// Close the connection to the camera device.
camera.Close();
}
}
catch (Exception e)
{
Console.Error.WriteLine("Exception: {0}", e.Message);
exitCode = 1;
}
finally
{
// Comment the following two lines to disable waiting on exit.
Console.Error.WriteLine("\nPress enter to exit.");
Console.ReadLine();
}
Environment.Exit(exitCode);
}
}
}
2. 주요 구성 요소 및 기능
a. 카메라 객체 생성 및 초기화
using (Camera camera = new Camera())
{
// Print the model name of the camera.
Console.WriteLine("Using camera {0}.", camera.CameraInfo[CameraInfoKey.ModelName]);
// Set the acquisition mode to free running continuous acquisition when the camera is opened.
camera.CameraOpened += Configuration.AcquireContinuous;
// Open the connection to the camera device.
camera.Open();
- 카메라 객체 생성: Camera 객체를 생성하여 첫 번째로 발견된 카메라를 선택합니다.
- 카메라 모델명 출력: 선택된 카메라의 모델 이름을 출력합니다.
- 연속 촬영 모드 설정: 카메라가 열리면 연속 촬영 모드로 설정합니다.
- 카메라 연결 열기: 카메라와의 연결을 엽니다.
b. 버퍼 설정 및 이미지 그랩 시작
// The parameter MaxNumBuffer can be used to control the amount of buffers
// allocated for grabbing. The default value of this parameter is 10.
camera.Parameters[PLCameraInstance.MaxNumBuffer].SetValue(5);
// Start grabbing.
camera.StreamGrabber.Start();
- 버퍼 수 설정: 그랩을 위해 할당된 버퍼의 수를 설정합니다. 기본값은 10이지만, 여기서는 5로 설정합니다.
- 이미지 그랩 시작: 이미지 수집을 시작합니다.
c. 이미지 수집 및 처리
// Grab a number of images.
for (int i = 0; i < 10; ++i)
{
// Wait for an image and then retrieve it. A timeout of 5000 ms is used.
IGrabResult grabResult = camera.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException);
using (grabResult)
{
// Image grabbed successfully?
if (grabResult.GrabSucceeded)
{
// Access the image data.
Console.WriteLine("SizeX: {0}", grabResult.Width);
Console.WriteLine("SizeY: {0}", grabResult.Height);
byte[] buffer = grabResult.PixelData as byte[];
Console.WriteLine("Gray value of first pixel: {0}", buffer[0]);
Console.WriteLine("");
// Display the grabbed image.
ImageWindow.DisplayImage(0, grabResult);
}
else
{
Console.WriteLine("Error: {0} {1}", grabResult.ErrorCode, grabResult.ErrorDescription);
}
}
}
- 이미지 수집: 10개의 이미지를 수집합니다. 각 이미지에 대해 5000ms의 타임아웃을 설정하여 이미지 수집을 기다립니다.
- 이미지 처리: 이미지가 성공적으로 수집되었는지 확인하고, 이미지 데이터를 접근하여 출력합니다. 첫 번째 픽셀의 그레이 값을 출력합니다.
- 이미지 표시: 수집된 이미지를 표시합니다.
d. 이미지 그랩 중지 및 카메라 연결 종료
// Stop grabbing.
camera.StreamGrabber.Stop();
// Close the connection to the camera device.
camera.Close();
- 이미지 그랩 중지: 이미지 수집을 중지합니다.
- 카메라 연결 종료: 카메라와의 연결을 종료합니다.
3. 에러 처리 및 종료
catch (Exception e)
{
Console.Error.WriteLine("Exception: {0}", e.Message);
exitCode = 1;
}
finally
{
// Comment the following two lines to disable waiting on exit.
Console.Error.WriteLine("\nPress enter to exit.");
Console.ReadLine();
}
Environment.Exit(exitCode);
- 에러 처리: 이미지 수집 중 에러가 발생하면 에러 메시지를 출력합니다.
- 프로그램 종료: 사용자 입력을 기다린 후 프로그램을 종료합니다.
이 샘플 코드는 Basler Pylon .NET API를 사용하여 비동기로 이미지를 수집하고 처리하는 방법을 보여줍니다. 비동기 이미징을 통해 이미지 수집과 처리를 병렬로 수행하여 효율성을 높일 수 있습니다. 이를 통해 실시간 모니터링 시스템이나 산업 자동화 시스템에서 매우 유용하게 사용할 수 있습니다.
해시태그
#CSharp #BaslerPylon #비동기처리 #이미지처리 #비전코딩 #프로그래밍 #오픈소스 #GitHub #코딩팁 #개발자
728x90