OpenCV:繪製旋轉矩形區域
阿新 • • 發佈:2018-12-01
問題:
給定4個點,求最小外接矩形,然後在影象中繪製出旋轉矩形區域。
程式:
Point p1(800,400), p2(1100,605), p3(902,970), p4(802,780);//4個點 vector<Point> vec_pts; vec_pts.push_back(p1); vec_pts.push_back(p2); vec_pts.push_back(p3); vec_pts.push_back(p4); RotatedRect rect = minAreaRect(vec_pts);//外接矩形 Point2f vertices[4]; rect.points(vertices);//外接矩形的4個頂點 for (int i = 0; i < 4; i++)//繪製外接矩形 line(dst, vertices[i], vertices[(i + 1) % 4], Scalar(255, 0, 0));
示例:
#include <opencv2/opencv.hpp> #include <iostream> using namespace std; using namespace cv; int main() { Mat image_source = imread("1.bmp", 0); imshow("source image", image_source ); vector<Point> vec_pts; Point p1(800,400), p2(1100,605), p3(902,970), p4(802,780);//隨意給了4個點 vec_pts.push_back(p1); vec_pts.push_back(p2); vec_pts.push_back(p3); vec_pts.push_back(p4); RotatedRect rect = minAreaRect(vec_pts);//外接矩形 Point2f vertices[4]; rect.points(vertices);//外接矩形的4個頂點 for (int i = 0; i < 4; i++)//畫矩形 line(image_source , vertices[i], vertices[(i + 1) % 4], Scalar(255, 0, 0)); imshow("rotation rect", 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; }
參考文章
1. https://blog.csdn.net/flyyufenfei/article/details/79781194