#include
#include
void on_mouse(int event, int x, int y, int flags, void* ustc);
void drawRectangle(cv::Mat src, cv::Point pt1, cv::Point pt2);
void drawCircle(cv::Mat src, cv::Point pt_center, int pt_radius);
void drawLine(cv::Mat src, cv::Point pt1, cv::Point pt2, cv::Scalar color);
cv::Point pre_pt= cv::Point(-1,-1), cur_pt= cv::Point(-1, -1);//鼠标点
#define WINDOW_NAME "image"
int main()
{
cv::Mat srcImage;
cv::Point center;
int radius=0;
cv::VideoCapture capture(0);
capture.set(CV_CAP_PROP_FRAME_WIDTH, 640);
capture.set(CV_CAP_PROP_FRAME_HEIGHT, 480);
cv::namedWindow(WINDOW_NAME, cv::WINDOW_AUTOSIZE);
if (!capture.isOpened())//判断摄像头是否打开
{
std::cout << "视频加载失败 !" << std::endl;
}
while (true)
{
capture >> srcImage;
if (srcImage.empty())
{
std::cout << "视频加载失败 !" << std::endl;
return -1;
}
cv::setMouseCallback(WINDOW_NAME, on_mouse, 0);
if (cur_pt.x!=-1&& cur_pt.y != -1)
{
drawLine(srcImage, pre_pt, cur_pt, cv::Scalar(0,255,0));
drawRectangle(srcImage, pre_pt, cur_pt);
drawCircle(srcImage, center, radius);
}
imshow(WINDOW_NAME, srcImage);
if (cv::waitKey(25)==27)
{
break;
}
}
capture.release();
//按ESC退出时销毁所有窗口
cv::destroyAllWindows();
return 0;
}
//画线
void drawLine(cv::Mat src, cv::Point pt1, cv::Point pt2, cv::Scalar color)
{
cv::line(src, pt1, pt2, color, 1, CV_AA);
}
//画框
void drawRectangle(cv::Mat src, cv::Point pt1, cv::Point pt2)
{
cv::rectangle(src, pt1, pt2, cv::Scalar(0, 255, 0), 1, CV_AA, 0);
}
//画圆
void drawCircle(cv::Mat src, cv::Point pt_center, int pt_radius)
{
pt_center.x = (pre_pt.x < cur_pt.x) ? pre_pt.x + abs(cur_pt.x - pre_pt.x) / 2 : cur_pt.x + abs(cur_pt.x - pre_pt.x) / 2;
pt_center.y = (pre_pt.y < cur_pt.y) ? pre_pt.y + abs(cur_pt.y - pre_pt.y) / 2 : cur_pt.y + abs(cur_pt.y - pre_pt.y) / 2;
pt_radius = std::sqrt((cur_pt.x- pre_pt.x)*(cur_pt.x - pre_pt.x)+ (cur_pt.y - pre_pt.y)*(cur_pt.y - pre_pt.y))/2;
cv::circle(src, pt_center, pt_radius, cv::Scalar(0, 255, 0), 1, CV_AA, 0);
}
//鼠标操作
void on_mouse(int event, int x, int y, int flags, void* ustc)
{
//左键按下
if (event == CV_EVENT_LBUTTONDOWN)
{
cv::Point pt= cv::Point(x, y);
pre_pt = pt;
}
//左键按下并且鼠标移动
else if (event == cv::EVENT_MOUSEMOVE && (flags & cv::EVENT_FLAG_LBUTTON))
{
cv::Point pt = cv::Point(x, y);
cur_pt = pt;
}
//左键弹起
else if (event == CV_EVENT_LBUTTONUP)
{
cv::Point pt = cv::Point(x, y);
cur_pt = pt;
}
}