Код: Выделить всё
cv::Mat test_convexityDefects(
const cv::Mat& binary_,
std::vector& concave_points_) {
concave_points_.clear();
std::vector contours;
cv::findContours(binary_, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
cv::Mat inputImage, colored;
cv::cvtColor(binary_, inputImage, cv::COLOR_GRAY2BGR);
colored = inputImage.clone();
for (auto& cnt : contours) {
std::vector hullIndices;
cv::convexHull(cnt, hullIndices, false, false);
std::vector defects;
if (cnt.size() >= 3 && hullIndices.size() >= 3) {
cv::convexityDefects(cnt, hullIndices, defects);
std::vector farPoints;
for (const auto& d : defects) {
int farIdx = d[2];
float depth = d[3] / 256.0f;
if (depth > 1) {
concave_points_.push_back(cnt[farIdx]);
}
}
}
std::vector convexPeaks;
for (int idx : hullIndices) {
convexPeaks.push_back(cnt[idx]);
}
int numPeaks = int(convexPeaks.size());
for (int i = 0; i < numPeaks; i++) {
int iNext = (i + 1) % numPeaks;
cv::line(colored, convexPeaks[i], convexPeaks[iNext], cv::Scalar(0, 255, 0), 1);
cv::circle(colored, convexPeaks[i], 1, cv::Scalar(0, 255, 255), 2);
}
}
int binary_h = binary_.rows;
int binary_w = binary_.cols;
cv::Mat result = cv::Mat::zeros(cv::Size(binary_w, 2 * binary_h), CV_8UC3);
for (const auto& p : concave_points_) {
cv::circle(colored, p, 2, cv::Scalar(0, 0, 255), 2);
}
inputImage.copyTo(result(cv::Rect(0, 0, binary_w, binary_h)));
colored.copyTo(result(cv::Rect(0, binary_h, binary_w, binary_h)));
return result;
}
int main() {
const std::string path = "./image.png";
cv::Mat grayImage = cv::imread(path, cv::IMREAD_GRAYSCALE);
cv::Mat binary;
cv::threshold(grayImage, binary, 125, 255, cv::THRESH_BINARY);
std::vector concave_points;
cv::Mat result = test_convexityDefects(binary, concave_points);
cv::imwrite("image_out.png", result);
return 0;
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... ty-defects