All files / tools/src/stateManagement/segmentation/utilities removeContourIslands.ts

0% Statements 0/19
0% Branches 0/9
0% Functions 0/3
0% Lines 0/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59                                                                                                                     
import type { ContourSegmentationAnnotation } from '../../../types';
import { getAnnotation } from '../../annotation/annotationState';
import { getSegmentation } from '../getSegmentation';
import { extractSegmentPolylines } from './extractSegmentPolylines';
import findIslands from '../../../utilities/contours/findIslands';
import { removeCompleteContourAnnotation } from './removeCompleteContourAnnotation';
 
/**
 * Removes contour islands from a segmentation segment by detecting and deleting small isolated contours.
 * Islands are contours that are smaller than the specified threshold and are not connected to larger contours.
 * This helps clean up segmentations by removing noise and small artifacts.
 *
 * @param segmentationId - The unique identifier of the segmentation
 * @param segmentIndex - The index of the segment within the segmentation
 * @param options - Configuration options for island detection
 * @param options.threshold - The minimum size threshold for contours (default: 3)
 */
export default function removeContourIslands(
  segmentationId: string,
  segmentIndex: number,
  options: { threshold: number } = { threshold: 3 }
) {
  const segmentation = getSegmentation(segmentationId);
  if (!segmentation) {
    console.warn(`Invalid segmentation given ${segmentationId}`);
    return;
  }
  if (!segmentation.representationData.Contour) {
    console.warn(
      `No contour representation found for segmentation ${segmentationId}`
    );
    return;
  }
 
  const polylinesCanvasMap = extractSegmentPolylines(
    segmentationId,
    segmentIndex
  );
  if (!polylinesCanvasMap) {
    console.warn(
      `Error extracting contour data from segment ${segmentIndex} in segmentation ${segmentationId}`
    );
    return;
  }
 
  const keys = Array.from(polylinesCanvasMap?.keys());
  const polylines = keys.map((key) => polylinesCanvasMap.get(key));
 
  const islands = findIslands(polylines, options.threshold);
  if (islands?.length > 0) {
    islands.forEach((index) => {
      const annotation = getAnnotation(
        keys[index]
      ) as ContourSegmentationAnnotation;
      removeCompleteContourAnnotation(annotation);
    });
  }
}