std::vector<std::vector<cv::Point>> fillContour(const std::vector<std::vector<cv::Point>> & _contours) { // sort as x descent y descent. std::vector<std::vector<cv::Point>> contours(_contours); for(size_t i = 0; i<contours.size(); ++i) { std::vector<cv::Point> sub(contours[i]); std::sort(sub.begin(), sub.end(), [&](cv::Point & A, cv::Point & B) { if (A.x == B.x) return A.y < B.y; else return A.x < B.x; }); contours[i] = sub; } // restore as pairs with same ys. std::vector<std::vector<std::pair<cv::Point, cv::Point>>> contours_pair; for (size_t i = 0; i < contours.size(); ++i) { std::vector<std::pair<cv::Point, cv::Point>> pairs; for (size_t j = 0; j < contours[i].size(); ++j) { // j==0 if (pairs.size() == 0) { pairs.push_back({ contours[i][j],contours[i][j] }); continue; } // j>0 if (contours[i][j].x != pairs[pairs.size() - 1].first.x) { pairs.push_back({ contours[i][j],contours[i][j] }); continue; } if (contours[i][j].x == pairs[pairs.size() - 1].first.x) { if (contours[i][j].y > pairs[pairs.size() - 1].second.y) pairs[pairs.size() - 1].second = contours[i][j]; continue; } } contours_pair.push_back(pairs); } // fill contour coordinates. std::vector<std::vector< cv::Point>> fill_con; for (auto pair_set : contours_pair) { std::vector<cv::Point> pointSet; for (auto aPair : pair_set) { if (aPair.first == aPair.second) { pointSet.push_back(aPair.first); } else { for (int i = aPair.first.y; i <= aPair.second.y; ++i) { pointSet.push_back(cv::Point(aPair.first.x, i)); } } } fill_con.push_back(pointSet); } return fill_con; }