本代码可用于获取物体的坐标偏移量,旋转角度。
//if(thresholdValue) { Mat src = Mat(imHeight,imWidth,CV_8U,pImageBuffer); Mat mat; src.copyTo(mat); threshold(mat,mat,thresholdValue,1,CV_THRESH_BINARY); //寻找最外层轮廓 vector<vector<Point>> contours; vector<Vec4i> hierarchy; findContours(mat,contours,hierarchy,RETR_EXTERNAL,CHAIN_APPROX_NONE,Point()); Mat imageContours=Mat::zeros(mat.size(),CV_8UC1); //最小外接矩形画布 int toatal = 0; int index = 0; for(int i=0;i<contours.size();i++) { int length = contours[i].size(); if(length > 5000) { index = i; toatal++; //绘制轮廓 //drawContours(src,contours,i,Scalar(255),1,8,hierarchy); //绘制轮廓的最小外结矩形 RotatedRect rect=minAreaRect(contours[i]); Point2f P[4]; rect.points(P); for(int j=0;j<=3;j++) { line(src,P[j],P[(j+1)%4],Scalar(255),2); } double x0,y0,alpha; x0 = rect.center.x; // 中心位置 y0 = rect.center.y; alpha = -rect.angle*CV_PI/180; // 角度转换成弧度 int w =20;//十字叉的宽度 //绘制轮廓的中心 line(src,Point2f(x0-w,y0),Point2f(x0+w,y0),Scalar(0),2); line(src,Point2f(x0,y0-w),Point2f(x0,y0+w),Scalar(0),2); //绘制图像的中心 line(src,Point2f(imWidth/2-w,imHeight/2),Point2f(imWidth/2+w,imHeight/2),Scalar(0),2); line(src,Point2f(imWidth/2,imHeight/2-w),Point2f(imWidth/2,imHeight/2+w),Scalar(0),2); double x_offset, y_offset, angle; x_offset = x0-imWidth/2; y_offset = y0-imHeight/2; angle = -rect.angle*CV_PI/180; //emit SendRectInfo(x_offset, y_offset, angle, length); } } }