setMouseCallback("image", mouse_callback, 0);
-> 이걸 미리 작동 시키면, 마우스 관련 이벤트가 발동하면 실행된다.
C++
1. 클릭하면 원하는 곳에 설정해서 도형 그리기(원, 사각형)
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
bool mouse_pressing = false;
bool drawing_mode = true;
//시작 좌표
int start_x = 50;
int start_y = 50;
int a, b, c;
//도형 내부 색
Scalar color(0, 255, 0);
Mat img;
RNG rng(543210);
void mouse_callback(int event, int x, int y, int flag, void *userdata)
{
if(event == EVENT_LBUTTONDOWN)
{
cout << "원하는 색깔 입력" << endl;
cin >> a >> b >> c;
color = Scalar(a, b, c);
cout << "원하는 시작 좌표" << endl;
cin >> start_x >> start_y;
cout << " 끝좌표 " << endl;
cin >> x >> y;
mouse_pressing = false;
if (drawing_mode == true)
{
//사각형
rectangle(img, Point(start_x, start_y), Point(x, y), color, -1);
}
else
{
//원
circle(img, Point(start_x, start_y), max(abs(start_x - x), abs(start_y - y)), color, -1);
}
}
else if (event == EVENT_RBUTTONDOWN)
{
// 우클릭시 그림 모드 바꾸기
drawing_mode = !drawing_mode;
}
}
int main()
{
int width = 500;
int height = 500;
img = Mat(height, width, CV_8UC3, Scalar(0, 0, 0));
namedWindow("image");
setMouseCallback("image", mouse_callback, 0);
while (1)
{
imshow("image", img);
int key = waitKey(1);
if (key == 27)
break;
}
return 0;
}
2. 드래그로 도형 그리기
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
bool mouse_pressing = false;
bool drawing_mode = true;
//시작 좌표
int start_x = 50;
int start_y = 50;
int a, b, c;
//도형 내부 색
Scalar color(0, 255, 0);
Mat img;
RNG rng(543210);
void mouse_callback(int event, int x, int y, int flag, void *userdata)
{
if (event == EVENT_MOUSEMOVE)
{
if (mouse_pressing == true)
{
if (drawing_mode == true)
{
//사각형
rectangle(img, Point(start_x, start_y), Point(x, y), color, -1);
}
else
{
//원
circle(img, Point(start_x, start_y), max(abs(start_x - x), abs(start_y - y)), color, -1);
}
}
}
else if (event == EVENT_LBUTTONDOWN)
{
color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
mouse_pressing = true;
start_x = x;
start_y = y;
}
else if (event == EVENT_LBUTTONUP)//마우스 손 때면
{
mouse_pressing = false;
if (drawing_mode == true)
{
//사각형
rectangle(img, Point(start_x, start_y), Point(x, y), color, -1);
}
else
{
//원
circle(img, Point(start_x, start_y), max(abs(start_x - x), abs(start_y - y)), color, -1);
}
}
else if (event == EVENT_RBUTTONDOWN)
{
// 우클릭시 그림 모드 바꾸기
drawing_mode = !drawing_mode;
}
}
int main()
{
int width = 500;
int height = 500;
img = Mat(height, width, CV_8UC3, Scalar(0, 0, 0));
namedWindow("image");
setMouseCallback("image", mouse_callback, 0);
while (1)
{
imshow("image", img);
int key = waitKey(1);
if (key == 27)
break;
}
return 0;
}
'OpenCV > c++' 카테고리의 다른 글
OpenCV 기본 제공 GUI (0) | 2021.05.29 |
---|---|
OpenCV 영상처리 기본 개념 (0) | 2021.05.28 |
OpenCV 기본 동작 (0) | 2021.05.28 |