Skip to content

Commit 3018059

Browse files
committed
Add support of holes to contours generation
1 parent a9fb359 commit 3018059

File tree

2 files changed

+26
-7
lines changed

2 files changed

+26
-7
lines changed

src/python/model_api/models/result/segmentation.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -149,13 +149,20 @@ def rotated_rects(self, value):
149149

150150

151151
class Contour:
152-
def __init__(self, label: str, probability: float, shape: list[tuple[int, int]]):
152+
def __init__(self, label: str, probability: float, shape: np.ndarray, child_shapes: list[np.ndarray] | None = None):
153153
self.shape = shape
154154
self.label = label
155155
self.probability = probability
156+
self.child_shapes = child_shapes
156157

157158
def __str__(self):
158-
return f"{self.label}: {self.probability:.3f}, {len(self.shape)}"
159+
repr = f"{self.label}: {self.probability:.3f}, {len(self.shape)}"
160+
if self.child_shapes is not None:
161+
repr += f", {len(self.child_shapes)}"
162+
return repr
163+
164+
def __repr__(self):
165+
return self.__str__()
159166

160167

161168
class ImageResultWithSoftPrediction(Result):

src/python/model_api/models/segmentation.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ def postprocess(self, outputs: dict, meta: dict) -> ImageResultWithSoftPredictio
186186
def get_contours(
187187
self,
188188
prediction: ImageResultWithSoftPrediction,
189-
) -> list:
189+
) -> list[Contour]:
190190
n_layers = prediction.soft_prediction.shape[2]
191191

192192
if n_layers == 1:
@@ -207,13 +207,25 @@ def get_contours(
207207
obj_group = prediction.resultImage == layer_index
208208
label_index_map = obj_group.astype(np.uint8) * 255
209209

210-
contours, _hierarchy = cv2.findContours(
210+
contours, hierarchy = cv2.findContours(
211211
label_index_map,
212-
cv2.RETR_EXTERNAL,
212+
cv2.RETR_CCOMP,
213213
cv2.CHAIN_APPROX_NONE,
214214
)
215+
hierarchy = hierarchy.squeeze()
215216

216-
for contour in contours:
217+
for i, contour in enumerate(contours):
218+
children = None
219+
220+
if hierarchy[i][3] >= 0:
221+
continue
222+
223+
children = []
224+
if hierarchy[i][2] >= 0:
225+
child_next_idx = hierarchy[i][2]
226+
while child_next_idx >= 0:
227+
children.append(contours[child_next_idx])
228+
child_next_idx = hierarchy[child_next_idx][0]
217229
mask = np.zeros(prediction.resultImage.shape, dtype=np.uint8)
218230
cv2.drawContours(
219231
mask,
@@ -223,7 +235,7 @@ def get_contours(
223235
thickness=-1,
224236
)
225237
probability = cv2.mean(current_label_soft_prediction, mask)[0]
226-
combined_contours.append(Contour(label, probability, contour))
238+
combined_contours.append(Contour(label, probability, contour, children))
227239

228240
return combined_contours
229241

0 commit comments

Comments
 (0)