各个vector
放了一个vector容器,子容器里放点
vector<vector<Point>>
放了4维int向量
vector<Vec4i>
像素width * height from 位置(x*y)
vector<Rect>
矩形偏移角度、中心、大小
vector<RotatedRect>
轮廓周围绘制矩形框
刚开始学OpenCV没多久遇到这些个东西不知道是什么,搞得很不舒服。
通过给轮廓绘制矩形框弄明白了这些东西。
代码如下:
#include <iostream> #include <math.h> #include <opencv2/opencv.hpp> #include<opencv2/highgui.hpp> #include <opencv2/highgui/highgui_c.h> using namespace std; using namespace cv; int main() { Mat src, gray_src, drawImg, bin_output; src = imread("./shape.png"); namedWindow("input", CV_WINDOW_AUTOSIZE); namedWindow("output", CV_WINDOW_AUTOSIZE); imshow("input", src); cvtColor(src, gray_src, CV_BGR2GRAY); // 灰度图 blur(gray_src, gray_src, Size(10, 10), Point(-1, -1), BORDER_DEFAULT); //这些个类型 vector<vector<Point>> contours; // 存轮廓 vector<Vec4i> hierarchy; // 轮廓关系向量 threshold(gray_src, bin_output, 144, 255, 0); // 二值化 findContours(bin_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0)); // 找轮廓 //这些个类型 vector<vector<Point>> contours_poly(contours.size()); vector<Rect> poly_rects(contours.size()); vector<RotatedRect> minRect(contours.size()); //取点 for (size_t i = 0; i < contours.size(); i++) { approxPolyDP(Mat(contours[i]), contours_poly[i], 3, true); //减少轮廓点数 poly_rects[i] = boundingRect(contours_poly[i]);//获取绘制矩形数据 if (contours_poly[i].size() > 5) { minRect[i] = minAreaRect(contours_poly[i]);//获取绘制旋转矩形数据 } } // 开始绘制 src.copyTo(drawImg); Point2f pst[4]; // 储存单个旋转矩形的四个点 cout << "----------Point2f pst[4]:输出每个旋转矩形的四个点坐标------------" << endl; for (size_t i = 0; i < contours.size(); i++) { rectangle(drawImg, poly_rects[i], Scalar(255, 0, 0), 2, 8);//绘制矩形框 minRect[i].points(pst);//用线段画矩形,将RotatedRect类型转化为四个点 for (size_t u = 0; u < 4; u++) { line(drawImg, pst[u], pst[(u + 1) % 4], Scalar(0, 255, 0), 2, 8); cout << pst[u]; // 显示pst的数据 } cout << endl; Rect brect = minRect[i].boundingRect(); //返回包含旋转矩形的最小矩形 rectangle(drawImg, brect, Scalar(0, 0, 255)); } cout << endl; imshow("output", drawImg); cout << "----------vector<vector<Point>> contours_poly:------------" << endl; for (size_t i = 0; i < contours_poly.size(); i++) { cout << "第" << i << "行:"; for (size_t j = 0; j < contours_poly[i].size(); j++) { cout << contours_poly[i][j]; } cout << endl; } cout << endl; cout << "----------vector<Vec4i> hierarchy:输出轮廓间关系------------" << endl; for (size_t i = 0; i < hierarchy.size(); i++) { cout << hierarchy[i] << endl; } cout << endl; cout << "----------vector<Rect> poly_rects------------" << endl; for (size_t i = 0; i < poly_rects.size(); i++) { cout << poly_rects[i] << endl; } cout << endl; cout << "---------vector<RotatedRect> minRect------------" << endl; for (size_t i = 0; i < minRect.size(); i++) //显示一下点minRect { cout << "angle:" << minRect[i].angle << " center:" << minRect[i].center << " size:" << minRect[i].size << endl; } cout << endl; waitKey(0); return 0; }
运行结果为: