求外接矩形及旋转角度

本文探讨了使用OpenCV处理图像时遇到的问题,包括在图像上绘制最小外接矩形以及如何计算物体的旋转角度。通过链接分享了两种不同的代码实现,但指出它们存在未知问题,无法正确显示矩形图像。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述 加入blur(image, image, Size(3, 3));就变成了下面的情况
不知道为什么
在这里插入图片描述

代码

// #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 input binary image


	Mat image = imread("test.jpg", 0);
	if (!image.data) { printf("读取图片错误,请确定目录下是否有imread函数指定图片存在~! \n"); return false; }
    //blur(image, image, Size(3, 3));//加上变为两倍??
	imshow("Image", image);
	// 转为2值图
	threshold(image, image, 200, 255, THRESH_BINARY_INV);

	imshow("binary", image);
	imwrite("binary.jpg", image);

	vector<vector<Point>> contours;//保存所有轮廓数据save all contours data
	vector<Vec4i> hierarchy;
	findContours(image, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);//find contours
	
	cout << "Contours: " << contours.size() << endl;
	

    Mat imageContours = Mat::zeros(image.size(), CV_8UC1);	//最小外接矩形画布
    
	for (int i = 0; i<contours.size(); i++)
   {
	//绘制轮廓
	drawContours(imageContours, contours, i, Scalar(255), 1, 8, hierarchy);
	//绘制轮廓的最小外结矩形
	RotatedRect resultRect;
	resultRect = minAreaRect(contours[i]);//获取轮廓的最小外接矩形
	Point2f P[4];
	resultRect.points(P);//获取最小外接矩形的四个顶点坐标 
	for (int j = 0; j <= 3; j++)
	    {
		line(imageContours, P[j], P[(j + 1) % 4], Scalar(255), 2);
		
     	}
    cout << "X:" << resultRect.center.x << "Y:" << resultRect.center.y << "Angle:" << resultRect.angle << endl;
	}
	
    imshow("MinAreaRect", imageContours);
    
    waitKey(0);
	return 0;
}

另一种代码,但是不知道哪里有问题,画不出矩形图。

//cout << "Contours: " <&
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值