在opencv使用c++筛选出边长较长的轮廓
时间: 2023-05-31 19:06:52 浏览: 54
可以使用以下步骤筛选出边长较长的轮廓:
1. 使用cv::findContours函数找到所有轮廓。
2. 遍历所有轮廓,使用cv::arcLength函数计算每个轮廓的周长。
3. 对于每个轮廓,使用cv::approxPolyDP函数将其近似为一个多边形。
4. 使用cv::boundingRect函数计算多边形的边界框。
5. 根据多边形的边长与边界框的宽度和高度比较,筛选出边长较长的轮廓。
以下是一个示例代码:
```
#include <opencv2/opencv.hpp>
using namespace cv;
int main()
{
// 读取图像并转为灰度图像
Mat image = imread("test.jpg");
Mat gray;
cvtColor(image, gray, COLOR_BGR2GRAY);
// 二值化
Mat binary;
threshold(gray, binary, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
// 查找轮廓
std::vector<std::vector<Point>> contours;
findContours(binary, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
// 筛选边长较长的轮廓
std::vector<std::vector<Point>> long_contours;
for (const auto& contour : contours)
{
// 计算轮廓周长
double perimeter = arcLength(contour, true);
// 近似为多边形
std::vector<Point> polygon;
approxPolyDP(contour, polygon, 0.02 * perimeter, true);
// 计算多边形的边界框
Rect rect = boundingRect(polygon);
// 判断边长是否较长
double length = std::max(rect.width, rect.height);
double ratio = length / std::min(rect.width, rect.height);
if (length > 50 && ratio > 1.5)
long_contours.push_back(contour);
}
// 绘制筛选出的轮廓
Mat result(image.size(), CV_8UC3);
drawContours(result, long_contours, -1, Scalar(0, 0, 255), 2);
imshow("result", result);
waitKey();
return 0;
}
```