opencv提取旋转矩形区域的图像(将旋转矩形区域图像旋转成水平)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/flyyufenfei/article/details/79781194

自己一个需求:给4个点,求最小外接矩形,然后提取矩形内的图片。但是最小外接矩形一般都是倾斜的,那么如何把倾斜的矩形转换成水平呢?在网上找了老半天没找到简单的方法,貌似也没有现成的opencv函数(如果说知道麻烦告诉一声。。)。

网上能查到的是一种漫水填充法,但是貌似挺复杂。所以自己稍微鼓捣了一下,凑合能用。

步骤:

  1. 找到外接矩形之后,这个外接矩形的中心、长宽、旋转角度是知道的。所以把原图以外界矩形的中心为轴心,旋转相应的度数。
  2. 然后选取ROI区域,提取就行了。具体ROI怎么选的,看代码。
#include "highgui/highgui.hpp"    
#include "imgproc/imgproc.hpp"    
#include "iostream"  

using namespace std;
using namespace cv;

int main(int argc, char *argv[])
{
	Mat imageSource = imread("1.jpg", 0);
	imshow("Source Image", imageSource);
	vector<Point> contour;
	Point p1(800,400), p2(1100,605), p3(902,970), p4(802,780);//随意给了4个点
	contour.push_back(p1);
	contour.push_back(p2);
	contour.push_back(p3);
	contour.push_back(p4);
	RotatedRect rect = minAreaRect(contour);//外接矩形
	Point2f vertices[4];
	rect.points(vertices);//外接矩形的4个顶点
	for (int i = 0; i < 4; i++)//画矩形
		line(imageSource, vertices[i], vertices[(i + 1) % 4], Scalar(255, 0, 0));

	/*Rect brect = rect.boundingRect();
	rectangle(imageSource, brect, Scalar(255, 0, 0));*/
	imshow("Source Image1", imageSource);
	Point2f center = rect.center;//外接矩形中心点坐标
	Mat rot_mat = getRotationMatrix2D(center, rect.angle, 1.0);//求旋转矩阵
	Mat rot_image;
	Size dst_sz(imageSource.size());
	warpAffine(imageSource, rot_image, rot_mat, dst_sz);//原图像旋转
	imshow("rot_image", rot_image);
	Mat result1 = rot_image(Rect(center.x - (rect.size.width / 2), center.y - (rect.size.height/2), rect.size.width, rect.size.height));//提取ROI
	imshow("result", result1);

	waitKey(0);
	return 0;
}

效果:


可能提取完了有点错位偏移,如果需要精确提取的话就自己改改吧。

猜你喜欢

转载自blog.csdn.net/flyyufenfei/article/details/79781194