opencv寻找多边形拐点 c++代码
时间: 2023-11-06 14:57:30 浏览: 131
以下是使用OpenCV查找多边形拐点的C ++代码示例:
```cpp
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat image = imread("poly.png", IMREAD_GRAYSCALE);
if (image.empty())
{
cout << "Could not read the image" << endl;
return -1;
}
threshold(image, image, 128, 255, THRESH_BINARY);
vector<vector<Point>> contours;
findContours(image, contours, RETR_LIST, CHAIN_APPROX_SIMPLE);
for (size_t i = 0; i < contours.size(); i++)
{
vector<Point> polygon = contours[i];
vector<Point> corners;
for (size_t j = 0; j < polygon.size(); j++)
{
Point prev = polygon[(j + polygon.size() - 1) % polygon.size()];
Point cur = polygon[j];
Point next = polygon[(j + 1) % polygon.size()];
double angle = acos((prev - cur).dot(next - cur) / (norm(prev - cur) * norm(next - cur)));
if (angle < CV_PI * 0.9)
{
corners.push_back(cur);
}
}
cout << "Polygon " << i << " has " << corners.size() << " corners" << endl;
for (size_t j = 0; j < corners.size(); j++)
{
circle(image, corners[j], 5, Scalar(255), 2);
}
}
imshow("Contours", image);
waitKey(0);
return 0;
}
```
在这个示例中,我们首先从文件中读取灰度图像。然后使用二值化阈值将图像转换为黑白。接下来,我们使用`findContours`函数查找多边形的轮廓。对于每个多边形,我们使用角度检测方法查找拐点。如果两条相邻的边的夹角小于90度,则它们之间的顶点被视为拐点。最后,我们在图像中绘制每个多边形的拐点,并在控制台上打印拐点数。
阅读全文