Skip to content

Commit 93b514d

Browse files
committed
Add cpp implementation
1 parent 2b9b0a4 commit 93b514d

File tree

2 files changed

+18
-5
lines changed

2 files changed

+18
-5
lines changed

src/cpp/models/include/models/results.h

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -315,10 +315,11 @@ struct Contour {
315315
std::string label;
316316
float probability;
317317
std::vector<cv::Point> shape;
318+
std::vector<std::vector<cv::Point>> child_shapes;
318319

319320
friend std::ostream& operator<<(std::ostream& os, const Contour& contour) {
320321
return os << contour.label << ": " << std::fixed << std::setprecision(3) << contour.probability << ", "
321-
<< contour.shape.size();
322+
<< contour.shape.size() << ", " << contour.child_shapes.size();
322323
}
323324
};
324325

@@ -332,7 +333,7 @@ static inline std::vector<Contour> getContours(const std::vector<SegmentedObject
332333
if (contours.size() != 1) {
333334
throw std::runtime_error("findContours() must have returned only one contour");
334335
}
335-
combined_contours.push_back({obj.label, obj.confidence, contours[0]});
336+
combined_contours.push_back({obj.label, obj.confidence, contours[0], {}});
336337
}
337338
return combined_contours;
338339
}

src/cpp/models/src/segmentation_model.cpp

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -298,17 +298,29 @@ std::vector<Contour> SegmentationModel::getContours(const ImageResultWithSoftPre
298298
cv::Scalar(index, index, index),
299299
label_index_map);
300300
std::vector<std::vector<cv::Point>> contours;
301-
cv::findContours(label_index_map, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
301+
std::vector<cv::Vec4i> hierarchy;
302+
cv::findContours(label_index_map, contours, hierarchy, cv::RETR_CCOMP, cv::CHAIN_APPROX_NONE);
302303

303304
std::string label = getLabelName(index - 1);
304305

305-
for (unsigned int i = 0; i < contours.size(); i++) {
306+
for (size_t i = 0; i < contours.size(); ++i) {
307+
if (hierarchy[i][3] >= 0) {
308+
continue;
309+
}
310+
311+
std::vector<std::vector<cv::Point>> children;
312+
int next_child_idx = hierarchy[i][2];
313+
while (next_child_idx >= 0) {
314+
children.push_back(contours[next_child_idx]);
315+
next_child_idx = hierarchy[next_child_idx][0];
316+
}
317+
306318
cv::Mat mask = cv::Mat::zeros(imageResult.resultImage.rows,
307319
imageResult.resultImage.cols,
308320
imageResult.resultImage.type());
309321
cv::drawContours(mask, contours, i, 255, -1);
310322
float probability = (float)cv::mean(current_label_soft_prediction, mask)[0];
311-
combined_contours.push_back({label, probability, contours[i]});
323+
combined_contours.push_back({label, probability, contours[i], children});
312324
}
313325
}
314326

0 commit comments

Comments
 (0)