opencv实战项目之角度检测--c++

发布时间:2022-12-10 15:00

opencv中的鼠标操作是通过一个中介函数配合一个回调函数来实现的,
回调函数SeMouseCallback(const string &winname,MouseCallback onMouse,void* userdata=0)
中介函数void mousponts(int event, int x, int y, int flags, void* param);event是EVENT_+变量之一,x,y是鼠标指针再图像坐标系中的坐标,flags是EVENT_FLAG的组合,param是用户定义的传递到回调函数时调用的参数

#include
#include
#include
#include
#include

using namespace std;
using namespace cv;

//全局变量
vector<Point2d>center;
bool g_bDraweingBox=false;
bool deletee = false;
Mat img = imread("triangle.png");

void mousponts(int event, int x, int y, int flags, void* param);//函数声明
void getangle(vector<Point2d>);
void mousponts(int event, int x, int y, int flags, void* param)
//event是EVENT_+变量之一,x,y是鼠标指针再图像坐标系中的坐标,flags是EVENT_FLAG的组合,param是用户定义的传递到
//setMouseCallback函数调用的参数
{
	switch (event)
	{
		case EVENT_LBUTTONDOWN:
		{
			g_bDraweingBox = true;
			deletee = false;
			circle(img, Point2d(x,y), 2, Scalar(0, 0, 255), 8, 0);
			if ((center.size() != 0) && center.size() % 3 != 0)
			{
				line(img,center[round((center.size() - 1) / 3) * 3], Point2d(x, y), Scalar(0, 0, 255), 4, 8, 0);
			}
			center.push_back(Point2d(x, y));
		}
		break;
		case EVENT_RBUTTONDOWN:
		{
			deletee = true;
			g_bDraweingBox = false;
			center.erase(center.begin(), center.end());
			cout << center << endl;
		}
	}
}

double gradient(Point2d pt1, Point2d pt2)
{
	return (pt2.y - pt1.y) / (pt2.x - pt1.x);
}

void getangle(vector<Point2d>vec) {
	Point2d pt1, pt2, pt3;
	pt1.x = (vec.end() - 3)->x;
	pt1.y = (vec.end() - 3)->y;
	pt2.x = (vec.end() - 2)->x;
	pt2.y = (vec.end() - 2)->y;
	pt3.x = (vec.end()-1)->x;
	pt3.y = (vec.end()-1)->y;
	double m1 = gradient(pt1, pt2);
	double m2 = gradient(pt1, pt3);
	double angle;
	angle = atan(abs((m2-m1)/(1+m2*m1)));
	angle=round(angle* 180/CV_PI);
	string ss = to_string(int(angle));
	putText(img, ss, Point(pt2.x + 20, pt1.y + 20), FONT_HERSHEY_SCRIPT_COMPLEX, 1.5, Scalar(0, 0, 255), 2);
}

int main()
{
	namedWindow("图片显示", 100 * 100);
	setMouseCallback("图片显示", mousponts, (void*)&img);
	while (1)
	{
	   imshow("图片显示", img);
	   if (center.size()!=0&&center.size() %3==0)
	   {
		   getangle(center);
	   }
	   if (deletee)
	   {
		  img = imread("triangle.png");
	   }
	   if (waitKey(10) == 27)break;
	}
	return 0;
}

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号