C# OpenCV 강좌 : 제 3강 - 카메라 출력
프로젝트 구성
도구상자에서 PictureBoxIpl
, Timer
을 Form1에 생성합니다.
위 이미지와 같이 배치합니다.
도구 상자 속성
속성을 아래와 같이 설정합니다.
- PictureBoxIpl
- size : 640, 480
- Timer
- Enable : True
- Interval : 33
Camera 출력
using OpenCvSharp;
namespace
에 OpenCvSharp2
를 사용할 수 있도록 선언합니다.
CvCapture capture;
IplImage src;
카메라의 영상을 받아올 CvCapture
와 영상을 출력해 줄 IplImage
를 선언합니다.
private void Form1_Load(object sender, EventArgs e)
{
try
{
capture = CvCapture.FromCamera(CaptureDevice.DShow, 0);
capture.SetCaptureProperty(CaptureProperty.FrameWidth, 640);
capture.SetCaptureProperty(CaptureProperty.FrameHeight, 480);
}
catch
{
timer1.Enabled = false;
}
}
try~catch
를 이용하여 카메라가 인식되지 않았을 때 오류가 발생하지 않도록 합니다.
CvCapture.FromCamera(CaptureDevice.DShow, 0);
에서 0
은 카메라의 장치 번호입니다. 웹캠이 달려있는 노트북의 경우 0이 노트북 카메라
입니다.
capture.SetCaptureProperty
는 영상의 너비
와 높이
를 설정합니다. 장치가 인식되지 않을 경우 catch
로 넘어가며 timer1
를 사용하지 않게됩니다.
-
Tip : 카메라를 2개 이상 이용한다면
0
이 아닌1
로 입력하면외부 카메라로 인식
되어 출력됩니다. -
Tip : 동영상 파일 사용시
CvCapture.FromFile("경로")
를 사용하여동영상
을 재생시킬 수 있습니다.
private void timer1_Tick(object sender, EventArgs e)
{
src = capture.QueryFrame();
pictureBoxIpl1.ImageIpl = src;
}
src
에 현재의 영상 프레임을 받아오게 되고 pictreuBoxIpl1
에 해당 영상을 출력하게 됩니다.
timer1
은 33ms 마다 실행되며 그 때마다 영상을 출력합니다.
Interval
값을 수정하면 프레임의 수가 바뀌게 됩니다.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Cv.ReleaseImage(src);
if(src != null) src.Dispose();
}
메모리 관리
를 위하여 폼이 닫힐 때 ReleaseImage()
와 Dispose()
를 이용하여 메모리 할당을 해제합니다.
-
Tip :
ReleaseImage()
는이미지의 메모리 할당을 해제
합니다. -
Tip :
Dispose()
는클래스등의 메모리 할당을 해제
합니다.
전체 코드
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenCvSharp;
namespace Project
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
CvCapture capture;
IplImage src;
private void Form1_Load(object sender, EventArgs e)
{
try
{
capture = CvCapture.FromCamera(CaptureDevice.DShow, 0);
capture.SetCaptureProperty(CaptureProperty.FrameWidth, 640);
capture.SetCaptureProperty(CaptureProperty.FrameHeight, 480);
}
catch
{
timer1.Enabled = false;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
src = capture.QueryFrame();
pictureBoxIpl1.ImageIpl = src;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Cv.ReleaseImage(src);
if(src != null) src.Dispose();
}
}
}
공유하기


댓글 남기기