原创文章,未经作者允许,请勿转载,谢谢!
一开始想的是传统的水漫法,但是想着矩形这么规则,应该可以有别的方法,于是想到了下面这种小trick。
1.首先计算rotatedRect的四个顶点。
RotatedRect rRect(Point2f(100, 100), Size2f(100, 50), 30);
Point2f vertices[4]; //定义矩形的4个顶点
rRect.points(vertices); //计算矩形的4个顶点
2,然后根据旋转角度和中点位置计算旋转矩阵
cv::Mat rot_mat = cv::getRotationMatrix2D(Point2f(100, 100), 30, 1.0);
3.然后将顶点乘以旋转矩阵,进行旋转变换,用于生成一个规则的水平矩形Rect,然后就方便填充了
Mat background = Mat::zeros(back.size(), CV_8UC1);
for (int i = 0; i < 4; i++){
Mat point_mat = (Mat_(3, 1) << vertices[i].x, vertices[i].y, 1.0);
Mat point_rot = rot_mat * point_mat;
Point2f p(point_rot.ptr(0)[0], point_rot.ptr(1)[0]);
pp.push_back(p);
}
Rect rrr = boundingRect(pp);
background(rrr) = 255;
4.最后再根据旋转矩阵,将矩形框仿射变换回去就行了。
rot_mat = cv::getRotationMatrix2D(Point2f(100, 100), -30, 1.0);
cv::warpAffine(background, background, rot_mat, Size2f(200, 200));
img.copyTo(back, background);
完整代码如下:
#include
#include
#include
using namespace std;
using namespace cv;
int main()
{
Mat img = Mat(200,200,CV_8UC3,Scalar(255,255,255));
Mat back = Mat(200, 200, CV_8UC3, Scalar(0, 0, 0));
Mat background = Mat::zeros(back.size(), CV_8UC1);
RotatedRect rRect(Point2f(100, 100), Size2f(100, 50), 30);
Point2f vertices[4]; //定义矩形的4个顶点
Point2d vertices_d[4];
rRect.points(vertices); //计算矩形的4个顶点
//Rect brect = rRect.boundingRect2f();
//back(brect) = 255;
//ellipse(back, rRect, cv::Scalar(0, 255, 255), 2, 8);
for (int i = 0; i < 4; i++){
line(back, vertices[i], vertices[(i + 1) % 4], Scalar(0, 255, 0));
}
cv::Mat rot_mat = cv::getRotationMatrix2D(Point2f(100, 100), 30, 1.0);
cout << rot_mat< pp;
//根据旋转矩阵进行仿射变换
imshow("1", back);
Mat dst;
cv::warpAffine(back, dst, rot_mat, Size2f(200, 200));
imshow("2",dst);
for (int i = 0; i < 4; i++){
Mat point_mat = (Mat_(3, 1) << vertices[i].x, vertices[i].y, 1.0);
cout << point_mat <(0)[0], point_rot.ptr(1)[0]);
circle(dst, p, 2, Scalar(0, 255, 0));
pp.push_back(p);
}
Rect rrr = boundingRect(pp);
background(rrr) = 255;
imshow("3", background);
rot_mat = cv::getRotationMatrix2D(Point2f(100, 100), -30, 1.0);
Mat temp1;
cv::warpAffine(background, background, rot_mat, Size2f(200, 200));
img.copyTo(back, background);
imshow("4", back);
waitKey(0);
return 0;
}
MMP,突然发现,opencv里面有现成的函数可以用!!!
drawContours!!
fine,此帖煞笔,此帖终结。。。。。
tips:该函数的输入数据为int型