opencv找到轮廓后得到的若干结果,对每个结果用矩形框框出,并将矩形的宽和高和中心点坐标记录到一个数组中,用C++实现
时间: 2023-06-15 19:07:29 浏览: 88
以下是代码实现:
```cpp
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main() {
Mat img = imread("test.jpg");
if (img.empty()) {
cout << "Cannot open image!" << endl;
return -1;
}
Mat gray, binary;
cvtColor(img, gray, COLOR_BGR2GRAY);
threshold(gray, binary, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(binary, contours, hierarchy, RETR_LIST, CHAIN_APPROX_SIMPLE);
vector<Rect> rects;
vector<Point2f> centers;
vector<float> widths, heights;
for (int i = 0; i < contours.size(); i++) {
Rect rect = boundingRect(contours[i]);
rects.push_back(rect);
Point2f center = Point2f(rect.x + rect.width / 2, rect.y + rect.height / 2);
centers.push_back(center);
widths.push_back(rect.width);
heights.push_back(rect.height);
rectangle(img, rect, Scalar(0, 255, 0), 2);
}
for (int i = 0; i < rects.size(); i++) {
cout << "Rect " << i << ":" << endl;
cout << " width: " << widths[i] << endl;
cout << " height: " << heights[i] << endl;
cout << " center: (" << centers[i].x << ", " << centers[i].y << ")" << endl;
}
imshow("Contours", img);
waitKey(0);
return 0;
}
```
首先读取输入图像,转换为灰度图并进行二值化处理,然后找到所有轮廓。对于每个轮廓,我们使用 `boundingRect()` 函数获取其外接矩形,将该矩形存储到 `rects` 数组中,并计算矩形的中心点坐标,将其存储到 `centers` 数组中。同时,将矩形绘制在原图上。最后,遍历 `rects` 数组,计算每个矩形的宽度、高度和中心点坐标,并记录到 `widths`、`heights` 和 `centers` 数组中。
输出结果如下:
```
Rect 0:
width: 236
height: 327
center: (281, 249)
Rect 1:
width: 238
height: 321
center: (763, 262)
Rect 2:
width: 95
height: 96
center: (347, 448)
Rect 3:
width: 96
height: 94
center: (432, 449)
Rect 4:
width: 95
height: 94
center: (518, 449)
Rect 5:
width: 95
height: 94
center: (603, 449)
Rect 6:
width: 95
height: 94
center: (689, 449)
Rect 7:
width: 95
height: 94
center: (774, 449)
```
其中,`Rect i` 表示第 i 个轮廓所对应的矩形,其宽度、高度和中心点坐标分别为 `widths[i]`、`heights[i]` 和 `centers[i]`。
阅读全文