findcontours和drawcontours制作连通域
#include
#include
using namespace std;
using namespace cv;
int main()
{
Mat src = imread("src_img.jpg", 1);
imshow("src", src);
Mat grayImage;
cvtColor(src, grayImage, COLOR_BGR2GRAY);
Mat threshold_img;
threshold(grayImage, threshold_img, 1, 255, THRESH_OTSU + THRESH_BINARY_INV);
Mat element = getStructuringElement(MORPH_RECT, Size(3, 3));
morphologyEx(threshold_img, threshold_img, MORPH_OPEN, element, Point(-1, -1));
morphologyEx(threshold_img, threshold_img, MORPH_CLOSE, element, Point(-1, -1));
imshow("threshold_img",threshold_img);
Mat dist;
distanceTransform(threshold_img, dist, DIST_L2, 5);
normalize(dist, dist, 0, 255, cv::NORM_MINMAX);
double my_minv = 0.0, my_maxv = 0.0;
minMaxIdx(dist, &my_minv, &my_maxv);
Mat sure_fg;
threshold(dist, sure_fg, 0.7 * my_maxv, 255, THRESH_BINARY);
sure_fg.convertTo(sure_fg, CV_8U);
Mat element1 = getStructuringElement(MORPH_ELLIPSE, Size(3, 3));
dilate(sure_fg, sure_fg, element, Point(-1, -1), 3);
sure_fg.convertTo(sure_fg, CV_8U);
imshow("sure_fg", sure_fg);
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(sure_fg, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point());
Mat imageContours = Mat::zeros(sure_fg.size(), CV_8UC1);
Mat marks(sure_fg.size(), CV_32S);
marks = Scalar::all(0);
int index = 0;
int compCount = 0;
for (; index >= 0; index = hierarchy[index][0], compCount++)
{
drawContours(marks, contours, index, Scalar::all(compCount + 1), 1, 8, hierarchy);
drawContours(imageContours, contours, index, Scalar(255), 1, 8, hierarchy);
}
watershed(src, marks);
double maxVal = 0;
double minVal = 0;
minMaxLoc(marks, &minVal, &maxVal);
Mat dst = Mat::zeros(src.size(), CV_8U);
marks.convertTo(dst, CV_8U, 255.0 / (maxVal - minVal), -255.0 * minVal / (maxVal - minVal));
imshow("marks", dst);
waitKey(0);
return 0;
}