用最小外界矩形求零件角度,位置偏差

minAreaRect函数
函数作用:主要求得包含点集最小面积的矩形,这个矩形是可以有偏转角度的,可以与图像的边界不平行
RotatedRect minAreaRect(InputArray points) ; InputArray points:表示输入的点集
RotatedRect
它的返回值是矩形的四个顶点,中心点坐标,矩形角度
通过轮廓点找到轮廓的最小外接矩形,同时返回上面的关于矩形的信息
下面给出一个例子:

#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>  //opencv申明
#include <opencv2\imgproc\imgproc.hpp>
#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;


Mat caculate(Mat img)
{
	int sum = 0;
	Mat dst,dst1,src,grayimg,imag,dst_image;
	
	int u1 = img.rows;
	int u2 = img.cols;
	for (int i = 0; i < img.rows; i++)
	{
		for (int j = 0; j < img.cols; j++)
		{
			
	        sum = sum + img.at<uchar>(i, j);
		}
	}
	int u = u1*u2;
	int average = (int)sum/u*2;
	threshold(img, src, average, 255, CV_THRESH_BINARY);
	Canny(src,dst_image,50,50);  
	return dst_image;
}


int main()
{
	vector<vector<Point>> contours;
	vector<vector<Point>> contours1;
	Mat image = imread("C:\\Users\\Administrator\\Desktop\\tp_01.bmp");//读入模板图
	Mat image1 = imread("C:\\Users\\Administrator\\Desktop\\tp_03.bmp");
	Mat temp_img = caculate(image);
	findContours(temp_img, contours, CV_RETR_TREE, CV_CHAIN_APPROX_NONE, Point(0, 0));
	drawContours(image, contours, -1, Scalar(0, 255,0), 1.5, 8);
	RotatedRect temp_r= minAreaRect(contours[0]);
	int temp_angle = temp_r.angle;
	int temp_x = temp_r.center.x;
	int temp_y = temp_r.center.y;
	Size2i temp_size = temp_r.size;
	Point2f fourPoint2f[4];
	//将rectPoint变量中存储的坐标值放到 fourPoint的数组中 
    temp_r.points(fourPoint2f);
	//根据得到的四个点的坐标  绘制矩形
	for (int i = 0; i < 3; i++)
	{
	  line(image, fourPoint2f[i], fourPoint2f[i + 1], Scalar(55, 100, 195), 2, CV_AA);
	}
	line(image, fourPoint2f[0], fourPoint2f[3], Scalar(55, 100, 195), 2, CV_AA);
	

	Mat dst_img = caculate(image1);
	findContours(dst_img, contours1, CV_RETR_TREE, CV_CHAIN_APPROX_NONE, Point(0, 0));
	drawContours(image1, contours1, -1, Scalar(0, 255,0), 1.5, 8);
	RotatedRect dst_r= minAreaRect(contours1[0]);
	int dst_angle = dst_r.angle;
	int dst_x = dst_r.center.x;
	int dst_y = dst_r.center.y;
	Size2i dst_size = dst_r.size;
	Point2f fourPoint2f1[4];
	//将rectPoint变量中存储的坐标值放到 fourPoint的数组中 
    dst_r.points(fourPoint2f1);
	//根据得到的四个点的坐标  绘制矩形
	for (int i = 0; i < 3; i++)
	{
	  line(image1, fourPoint2f1[i], fourPoint2f1[i + 1], Scalar(55, 100, 195), 2, CV_AA);
	}
	line(image1, fourPoint2f1[0], fourPoint2f1[3], Scalar(55, 100, 195), 2, CV_AA);
	
	cout<<"旋转角度:"<<dst_angle-temp_angle<<endl;
	cout<<"中心x偏移量:"<<dst_x-temp_x<<endl;
	cout<<"中心y偏移量:"<<dst_y-temp_y<<endl;
	imshow("模板图",image);
    waitKey(0);
	imshow("旋转图",image1);
    waitKey(0);

	
}

运行结果如下:
在这里插入图片描述
还在学习中,代码中有不妥之处或有好的想法,还希望大神们不吝赐教

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值