opencv12-计算物体旋转角度

求取的角度是负值,我在图中画了一个垂直的形状,得出的结果是0 ,原因大家自己去理解。

废话不多说,直接上代码:

#include <iostream>
#include <vector>
#include <opencv2/opencv.hpp> 
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace std;
using namespace cv;

int main()
{
	// Read image
	RNG rng(12345);
	Mat pSrcImage = imread("11.jpg", CV_LOAD_IMAGE_UNCHANGED);
	if (!pSrcImage.data)
		return 0;
	imshow("Image", pSrcImage);

	// 转为2值图
	threshold(pSrcImage, pSrcImage, 200, 255, cv::THRESH_BINARY_INV);
	
	imwrite("binary.jpg", pSrcImage);

	vector<std::vector<cv::Point>> contours;
	Mat canny_output;
	Canny(pSrcImage, canny_output, 80, 255, 3);
	imshow("Canny Image",canny_output);
	
	vector<Vec4i> hierarchy;
	findContours(canny_output, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));

	/// 对每个找到的轮廓创建可倾斜的边界框和椭圆
	vector<RotatedRect> minRect(contours.size());
	for (unsigned int i = 0; i < contours.size(); i++)
	{
		minRect[i] = minAreaRect(Mat(contours[i]));
	}
	
	/// 绘出轮廓及其可倾斜的边界框
	CvBox2D  End_Rage2D;
	CvPoint2D32f rectpoint[4];
	Point2f rect_points[4];
	
	Mat drawing = Mat::zeros(canny_output.size(), CV_8UC3);
	for (unsigned int i = 0; i< contours.size(); i++)
	{
		
		End_Rage2D = minAreaRect(Mat(contours[i]));
		Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
		// contour
		drawContours(drawing, contours, i, color, 1, 8, vector<Vec4i>(), 0, Point());
		// rotated rectangle
		Point2f rect_points[4]; minRect[i].points(rect_points);
		for (unsigned int j = 0; j < 4; j++)
		{
         line(drawing, rect_points[j], rect_points[(j + 1) % 4], color, 1, 8);
		 cout << "坐标点:"<<rect_points[j] << "........" << rect_points[(j + 1) % 4] << endl;
		}
		
		
		int a = 0, b = 0, k = 0;
		a = (int)sqrt((pow((rect_points[0].x - rect_points[1].x), 2) + pow((rect_points[0].y - rect_points[1].y), 2)));
		b = (int)sqrt((pow((rect_points[0].x - rect_points[3].x), 2) + pow((rect_points[0].y - rect_points[3].y), 2)));

		if (a<b)
			{
				k = a;
				a = b;
				b = k;
			}
		printf("最小外接矩形的长为:%d,宽为:%d。\n\n", a, b);
		cout << " angle:\n" << 90+(float)End_Rage2D.angle << std::endl;      //旋转角度 
	}    

	namedWindow("Contours1", CV_WINDOW_AUTOSIZE);
	imshow("Contours1", drawing);
	
	waitKey(0);
	return 0;

}
实验图:

实验结果:



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值