OpenCV 데이터 종류
- Vector, 벡터
- Point, 포인트
- Scala, 스칼라
- Size, 사이즈
- Range, 범위
- Rect, 직사각형
- RoatatedRect, 회전 직사각형
- Mat, 2차원 배열
1) Vector
- Vector 구조체
2) Point
- Point 구조체
3) Scalar
- scalar 구조체
4) Size
- Size 구조체
5) Range
- Range 구조체
6) Rect
- Rect 구조체
7) RotatedRect
- RotatedRect 구조체
8) Mat
- Mat 데이터 클래스
- Mat 데이터 클래스 - 요소 접근
- 이미지 불러오기
- 이미지 출력하기
- 마우스 콜백
1) 콜백 이란?
2) Delegate와 Event의 차이점
3) 마우스 콜백 (이벤트)
이미지 위에 마우스로 그리기
- MouseEventCallback 사용
- Event 메소드의 입력 값인 마우스 좌표 활용
- Cv2.Circle() 활용
using System;
using System.Windows;
using OpenCvSharp;
namespace Ex_1
{
public partial class MainWindow : System.Windows.Window
{
private static bool isDrawing = false;
private static Mat image;
public MainWindow()
{
InitializeComponent();
string imgPath = @"F:\\pepe.jpg";
image = Cv2.ImRead(imgPath);
Cv2.Resize(image, image, new OpenCvSharp.Size(500, 500), interpolation: InterpolationFlags.Linear); // 이미지 크기 조정
Cv2.ImShow("board", image);
// 마우스 콜백 설정
Cv2.SetMouseCallback("board", MyMouseEvent);
Cv2.WaitKey();
Cv2.DestroyAllWindows();
}
// 마우스 이벤트 핸들러
private static void MyMouseEvent(MouseEventTypes @event, int x, int y, MouseEventFlags flags, IntPtr userdata)
{
// 마우스 왼쪽 버튼 클릭
if (@event == MouseEventTypes.LButtonDown)
{
isDrawing = true;
DrawCircle(x, y);
}
// 마우스 왼쪽 버튼 클릭 중 드래그
else if (@event == MouseEventTypes.MouseMove && isDrawing)
{
DrawCircle(x, y);
}
// 마우스 왼쪽 버튼 업
else if (@event == MouseEventTypes.LButtonUp)
{
isDrawing = false;
}
}
// 원(점)을 그리는 함수
private static void DrawCircle(int x, int y)
{
int brushSize = 3;
Scalar brushColor = Scalar.Black;
// 원 그리기
Cv2.Circle(image, new OpenCvSharp.Point(x, y), brushSize, brushColor, -1);
// 화면에 업데이트
Cv2.ImShow("board", image);
}
}
}
동영상 출력하기
- VideoCapture 클래스
- 동영상 재생 구조
FPS(Frame Per Second)
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using OpenCvSharp;
namespace opencv_6
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : System.Windows.Window
{
public MainWindow()
{
InitializeComponent();
string fileName = "F:\\sample_video";
VideoCapture capture = new VideoCapture(fileName + ".mp4");
Mat frame = new Mat();
double time_stamp = capture.Get(VideoCaptureProperties.PosMsec);
double fram_now = capture.Get(VideoCaptureProperties.PosFrames);
double frame_width = capture.Get(VideoCaptureProperties.FrameWidth);
double frame_height = capture.Get(VideoCaptureProperties.FrameHeight);
double frame_cout = capture.Get(VideoCaptureProperties.FrameCount);
double fps = capture.Get(VideoCaptureProperties.Fps);
textBox.Text = time_stamp + "\r\n";
textBox.Text += fram_now + "\r\n";
textBox.Text += frame_width + "\r\n";
textBox.Text += frame_height + "\r\n";
textBox.Text += frame_cout + "\r\n";
textBox.Text += fps + "\r\n";
while (true)
{
if (capture.PosFrames == capture.FrameCount)
{
capture.Open(fileName + ".mp4");
}
capture.Read(frame);
Cv2.ImShow("F:\\sample_video.mp4", frame);
if (Cv2.WaitKey(33) == 'q') break;
}
capture.Release();
Cv2.DestroyAllWindows();
}
}
}
카메라 출력하기
using System;
using System.Windows;
using OpenCvSharp;
namespace opencv_7
{
public partial class MainWindow : System.Windows.Window
{
public MainWindow()
{
InitializeComponent();
VideoCapture capture = new VideoCapture(0); // 기본 웹캠 (0번 장치)
// 웹캠 열기 확인
if (!capture.IsOpened())
{
MessageBox.Show("웹캠을 열 수 없습니다. 장치 연결 상태를 확인하세요.");
Application.Current.Shutdown();
return;
}
// 해상도 설정
capture.Set(VideoCaptureProperties.FrameWidth, 640);
capture.Set(VideoCaptureProperties.FrameHeight, 480);
Mat frame = new Mat();
// 영상 스트리밍 루프
while (true)
{
capture.Read(frame);
if (!frame.Empty())
{
Cv2.ImShow("Camera View", frame);
}
else
{
MessageBox.Show("프레임을 읽을 수 없습니다.");
break;
}
// 'q' 키를 누르면 종료
if (Cv2.WaitKey(33) == 'q')
{
break;
}
}
// 자원 해제
capture.Release();
Cv2.DestroyAllWindows();
}
}
}
※ 카메라 연결 제한 확인
마우스 포인터 위치 표시
- 카메라 영상 위에 마우스 포인터를 올리고 왼쪽 클릭을 누르고 있으면, 커서 위치가 빨간 원으로 표시되도록 만들기
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using OpenCvSharp;
using Point = OpenCvSharp.Point;
namespace Ex_4
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : System.Windows.Window
{
private static OpenCvSharp.Point mousePosition = new Point(0, 0); // 마우스 위치 저장
private static bool isMousePressed = false; // 마우스 클릭 여부 저장
public MainWindow()
{
InitializeComponent();
VideoCapture capture = new VideoCapture(0); // 기본 웹캠 (0번 장치)
// 웹캠 열기 확인
if (!capture.IsOpened())
{
MessageBox.Show("웹캠을 열 수 없습니다. 연결 상태를 확인하세요.");
Application.Current.Shutdown();
return;
}
// 해상도 설정
capture.Set(VideoCaptureProperties.FrameWidth, 640);
capture.Set(VideoCaptureProperties.FrameHeight, 480);
Mat frame = new Mat();
// 마우스 콜백 함수 등록
Cv2.NamedWindow("Camera View");
Cv2.SetMouseCallback("Camera View", OnMouseEvent);
// 영상 스트리밍 루프
while (true)
{
capture.Read(frame);
if (!frame.Empty())
{
// 마우스 클릭 상태일 때, 마우스 위치에 빨간 원 그리기
if (isMousePressed)
{
Cv2.Circle(frame, mousePosition, 10, new Scalar(0, 0, 255), -1); // 빨간색 원
}
Cv2.ImShow("Camera View", frame);
}
else
{
MessageBox.Show("프레임을 읽을 수 없습니다.");
break;
}
// 'q' 키를 누르면 종료
if (Cv2.WaitKey(33) == 'q')
{
break;
}
}
// 자원 해제
capture.Release();
Cv2.DestroyAllWindows();
}
private static void OnMouseEvent(MouseEventTypes eventType, int x, int y, MouseEventFlags flags, IntPtr userdata)
{
if(eventType == MouseEventTypes.LButtonDown)
{
isMousePressed = true;
mousePosition = new Point(x, y); // 클릭한 위치 저장
}else if (eventType == MouseEventTypes.LButtonUp)
{
isMousePressed = false; // 마우스 클릭 해제 시
}else if(eventType == MouseEventTypes.MouseMove && isMousePressed)
{
mousePosition = new Point(x, y);
}
}
}
}
'Computer Vision > OpenCv' 카테고리의 다른 글
OpenCV 이미지 검출 (1) (0) | 2025.02.12 |
---|---|
Scalar와 Vector 비교 (0) | 2025.02.12 |
OpenCV 소개 및 설치 (0) | 2025.02.12 |
머신 비전 기초(2) (0) | 2025.02.12 |
머신 비전 기초 (1) (0) | 2025.02.12 |