阈值分割之后,怎么把根据其特征把特定的区域给取出来,OPENCV
时间: 2024-01-26 13:02:41 浏览: 69
在阈值分割后,可以使用 OpenCV 中的轮廓检测函数 `findContours()` 来找到图像中的轮廓。该函数可以找到图像中所有的轮廓,并存储为一个向量容器 `vector<vector<Point>> contours`,其中每个轮廓是一个包含一系列点的向量。
接下来,可以通过遍历轮廓向量,计算每个轮廓的特征,如面积、周长、中心点等,来判断是否为所需的特定区域。如果是,可以将其提取出来,并用 `drawContours()` 函数将其在图像上标记出来。
以下是一个简单的示例代码:
```cpp
Mat image = imread("image.jpg");
if (image.empty()) {
cout << "Failed to read image!" << endl;
return -1;
}
Mat gray;
cvtColor(image, gray, COLOR_BGR2GRAY);
Mat binary;
threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(binary, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0));
for (int i = 0; i < contours.size(); i++) {
double area = contourArea(contours[i]);
if (area > 1000 && area < 5000) { // 判断面积是否在特定范围内
drawContours(image, contours, i, Scalar(0, 255, 0), 2);
// 在图像上标记该轮廓
}
}
imshow("Result", image);
waitKey(0);
```
在上述代码中,使用 `threshold()` 函数对灰度图像进行二值化,然后使用 `findContours()` 函数提取轮廓,再通过遍历轮廓向量,使用 `contourArea()` 函数计算每个轮廓的面积,并判断是否在特定范围内。如果是,则通过 `drawContours()` 函数在图像上标记该轮廓。
阅读全文
相关推荐


















