#include <opencv/cv.h> #include <opencv/highgui.h> #include <stdio.h> //#include <atlstr.h> #include <opencv2\core\core.hpp> #include <opencv2\highgui\highgui.hpp> //opencv申明 #include <opencv2\imgproc\imgproc.hpp> #include <opencv2/opencv.hpp> #include < iostream> #include <stdio.h> #include "cstring" using namespace cv; using namespace std; vector<Point> points; IplImage* src = 0; IplImage* dst = 0; int i = 0 ,j=0; //两点间距离公式 float getDistance(CvPoint pointO, CvPoint pointA) { float distance; distance = powf((pointO.x - pointA.x), 2) + powf((pointO.y - pointA.y), 2); distance = sqrtf(distance); //屏幕分辨率为1366*768,一个像素约为0.214mm,所以这里乘以0.214转化为实际尺寸,当然分辨率不同,一个像素表示的实际长度也不同 return distance; } //两条直线间的夹角 float angle(Point pt1, Point pt0, Point pt2) { double dx1 = (pt1.x - pt0.x); double dy1 = (pt1.y - pt0.y); double dx2 = (pt2.x - pt0.x); double dy2 = (pt2.y - pt0.y); double angle_line = (dx1*dx2 + dy1 * dy2) / sqrt((dx1*dx1 + dy1 * dy1)*(dx2*dx2 + dy2 * dy2) + 1e-10); double a = acos(angle_line) * 180 / 3.141592653; return a; } void on_mouse( int event, int x, int y, int flags, void* ustc) { static CvPoint pre_pt = (-1,-1); static CvPoint cur_pt = (-1,-1); CvFont font; cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, 0.5, 0.5, 0, 1, CV_AA); char temp[16]; if( event == CV_EVENT_LBUTTONDOWN ) { cvCopy(dst,src); sprintf(temp,"(%d,%d)",x,y); pre_pt = cvPoint(x,y); points.push_back(pre_pt); //cvPutText(src,temp, pre_pt, &font, cvScalar(0,0,255)); cvCircle( src, pre_pt,3,cvScalar(255,0,0,0) ,CV_FILLED, CV_AA, 0 ); int k = points.size(); if(k>1) { cvLine(src,points.at(i),points.at(i+1),cvScalar(0,255,60),1,8,0); float Dis = getDistance(points.at(i),points.at(i+1)); //转换字节数组到float数据 char m_Dis[50]; sprintf(m_Dis,"%.2f",Dis);//如果用sprintf函数小数点后会有6位 cvPutText(src,m_Dis,(points.at(i)+points.at(i+1))/2, &font, cvScalar(0,0,255)); i++; } if(k>2) { float m_angle = angle(points.at(j), points.at(j+1), points.at(j+2)); char m_angle1[50]; sprintf(m_angle1,"%.2f",m_angle);//如果用sprintf函数小数点后会有6位 //将角度保留两位小数 // double aaa = floor(m_angle * 100.000f + 0.5) / 100.000f; cvPutText(src,m_angle1,points.at(j+1), &font, cvScalar(255,0,255)); j++; } cvShowImage( "src", src ); cvCopy(src,dst); } else if( event == CV_EVENT_MOUSEMOVE && !(flags & CV_EVENT_FLAG_LBUTTON)) { cvCopy(dst,src); sprintf(temp,"(%d,%d)",x,y); cur_pt = cvPoint(x,y); cvPutText(src,temp, cur_pt, &font, cvScalar(255,0,255)); cvShowImage( "src", src ); } } int main() { src=cvLoadImage("D:\\Data\\1.jpg",1); dst=cvCloneImage(src); cvNamedWindow("src",1); cvSetMouseCallback( "src", on_mouse, 0 ); cvShowImage("src",src); cvWaitKey(0); cvDestroyAllWindows(); cvReleaseImage(&src); cvReleaseImage(&dst); return 0; }