MCPcopy Create free account
hub / github.com/UX-Decoder/Semantic-SAM / remove_small_regions

Function remove_small_regions

utils/sam_utils/amg.py:267–291  ·  view source on GitHub ↗

Removes small disconnected regions and holes in a mask. Returns the mask and an indicator of if the mask has been modified.

(
    mask: np.ndarray, area_thresh: float, mode: str
)

Source from the content-addressed store, hash-verified

265
266
267def remove_small_regions(
268 mask: np.ndarray, area_thresh: float, mode: str
269) -> Tuple[np.ndarray, bool]:
270 """
271 Removes small disconnected regions and holes in a mask. Returns the
272 mask and an indicator of if the mask has been modified.
273 """
274 import cv2 # type: ignore
275
276 assert mode in ["holes", "islands"]
277 correct_holes = mode == "holes"
278 working_mask = (correct_holes ^ mask).astype(np.uint8)
279 n_labels, regions, stats, _ = cv2.connectedComponentsWithStats(working_mask, 8)
280 sizes = stats[:, -1][1:] # Row 0 is background label
281 small_regions = [i + 1 for i, s in enumerate(sizes) if s < area_thresh]
282 if len(small_regions) == 0:
283 return mask, False
284 fill_labels = [0] + small_regions
285 if not correct_holes:
286 fill_labels = [i for i in range(n_labels) if i not in fill_labels]
287 # If every region is below threshold, keep largest
288 if len(fill_labels) == 0:
289 fill_labels = [int(np.argmax(sizes)) + 1]
290 mask = np.isin(regions, fill_labels)
291 return mask, True
292
293
294def coco_encode_rle(uncompressed_rle: Dict[str, Any]) -> Dict[str, Any]:

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected