opencv分水岭算法 c++
时间: 2023-11-15 18:06:23 浏览: 138
第八章分水岭算法_opencv_AB实验_分水岭算法小应用_
以下是使用C++实现的OpenCV分水岭算法的示例代码:
```c++
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
// 读取图像
Mat src = imread("coins.jpg");
if (src.empty())
{
cout << "could not load image..." << endl;
return -1;
}
// 转换为灰度图像并进行二值化处理
Mat gray, binary;
cvtColor(src, gray, COLOR_BGR2GRAY);
threshold(gray, binary, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
// 形态学操作,去除噪声
Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3));
morphologyEx(binary, binary, MORPH_OPEN, kernel);
// 距离变换
Mat dist;
distanceTransform(binary, dist, DIST_L2, 3, CV_32F);
// 寻找种子点
Mat dist_8u;
dist.convertTo(dist_8u, CV_8U);
vector<vector<Point>> contours;
findContours(dist_8u, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
Mat markers = Mat::zeros(dist.size(), CV_32S);
for (size_t i = 0; i < contours.size(); i++)
{
drawContours(markers, contours, static_cast<int>(i), Scalar::all(static_cast<int>(i) + 1), -1);
}
circle(markers, Point(5, 5), 3, Scalar(255), -1);
// 分水岭变换
watershed(src, markers);
// 显示结果
imshow("src", src);
imshow("watershed", markers * 10000); waitKey(0);
return 0;
}
```
阅读全文