C# OpenCV 강좌 : 제 39강 - 카메라 출력 (Mat)
프로젝트 구성
도구상자에서 PictureBoxIpl
, Timer
을 Form1에 생성합니다. 위의 이미지와 같이 배치합니다.
속성을 아래와 같이 설정합니다.
- PictureBoxIpl
- size : 640, 480
- Timer
- Enable : True
- Interval : 33
카메라 출력
using OpenCvSharp;
using OpenCvSharp.CPlusPlus;
namespace
에 OpenCV
와 CPlusPlus
사용할 수 있도록 선언합니다.
VideoCapture video;
Mat frame = new Mat();
카메라의 영상을 받아올 VideoCapture
와 영상을 출력해 줄 frame
를 선언합니다.
VideoCapture
는 Mat
형식을 사용하여 영상을 출력합니다.
private void Form1_Load(object sender, EventArgs e)
{
try
{
video = new VideoCapture(0);
video.FrameWidth = 640;
video.FrameHeight = 480;
}
catch
{
timer1.Enabled = false;
}
}
try~catch
를 이용하여 카메라가 인식되지 않았을 때 오류가 발생하지 않도록 합니다.
VideoCapture(0);
에서 0
은 카메라의 장치 번호입니다. 웹캠이 달려있는 노트북의 경우 0이 노트북 카메라
입니다.
- Tip : 카메라를 2개 이상 이용한다면
0
이 아닌1
로 입력하면외부 카메라로 인식
되어 출력됩니다.
video.FrameWidth
.video.FrameHeight
는 영상의 너비
와 높이
를 설정합니다. 장치가 인식되지 않을 경우 catch
로 넘어가며 timer1
를 사용하지 않게됩니다.
private void timer1_Tick(object sender, EventArgs e)
{
video.Read(frame);
pictureBoxIpl1.ImageIpl = frame.ToIplImage();
}
video.Read()
를 이용하여 카메라의 영상을 받아오게 되고, frame
에 저장하게 됩니다.
pictreuBoxIpl1
에 해당 영상을 출력하며, frame
의 형식은 Mat
형식이므로 *.ToIplImage()
를 이용하여 형식을 변환합니다.
- Tip :
timer1
은 33ms 마다 실행되며 그 때마다 영상을 출력합니다.Interval
값을 수정하면 프레임의 수가 바뀌게 됩니다.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
frame.Dispose();
}
메모리 관리
를 위하여 폼이 닫힐 때 Dispose()
를 이용하여 메모리 할당을 해제합니다.
- 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;
using OpenCvSharp.CPlusPlus;
namespace Project
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
VideoCapture video;
Mat frame = new Mat();
private void Form1_Load(object sender, EventArgs e)
{
try
{
video = new VideoCapture(0);
video.FrameWidth = 640;
video.FrameHeight = 480;
}
catch
{
timer1.Enabled = false;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
video.Read(frame);
pictureBoxIpl1.ImageIpl = frame.ToIplImage();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
frame.Dispose();
}
}
}
공유하기


댓글 남기기