All files / polymorphic-segmentation/src/workers polySegConverters.js

0% Statements 0/217
0% Branches 0/41
0% Functions 0/23
0% Lines 0/217

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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
import { expose } from 'comlink';
import { utilities } from '@cornerstonejs/core';
import { utilities as ToolsUtilities } from '@cornerstonejs/tools';
import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData';
import vtkDataArray from '@kitware/vtk.js/Common/Core/DataArray';
import vtkPlane from '@kitware/vtk.js/Common/DataModel/Plane';
import vtkPolyData from '@kitware/vtk.js/Common/DataModel/PolyData';
import vtkContourLoopExtraction from '@kitware/vtk.js/Filters/General/ContourLoopExtraction';
import vtkCutter from '@kitware/vtk.js/Filters/Core/Cutter';
 
const {
  math: {
    polyline: { containsPoint, getAABB, projectTo2D },
  },
  geometricSurfaceUtils: { checkStandardBasis, rotatePoints },
  boundingBox: { getBoundingBoxAroundShapeWorld },
  planar: { isPlaneIntersectingAABB },
} = ToolsUtilities;
 
async function peerImport(moduleId) {
  try {
    if (moduleId === '@icr/polyseg-wasm') {
      return import('@icr/polyseg-wasm');
    }
  } catch (error) {
    console.warn('Error importing module:', error);
    return null;
  }
}
 
/**
 * Object containing methods for converting between different representations of
 * segmentations (e.g., contour, labelmap, surface, etc.) These logics
 * are used in a webworker to avoid blocking the main thread. You can
 * search for workerManager.executeTask('polySeg', ...) to see
 * how these methods are used.
 *
 * See also the webworker docs at packages/docs/docs/concepts/cornerstone-core/web-worker.md
 * to learn more about how to use web-workers in the context of Cornerstone.
 */
const polySegConverters = {
  /**
   * The polySeg instance that is used to convert between different representations
   */
  polySeg: null,
  /**
   * Utilities to keep track of the initialization state of the polySeg instance
   * and avoid initializing it multiple times
   */
  polySegInitializing: false,
  polySegInitializingPromise: null,
  /**
   * This method initializes the polySeg instance and sets it to this.polySeg
   */
  async initializePolySeg(progressCallback) {
    let ICRPolySeg;
    try {
      ICRPolySeg = (await peerImport('@icr/polyseg-wasm')).default;
    } catch (error) {
      console.error(error);
      console.debug(
        "Warning: '@icr/polyseg-wasm' module not found. Please install it separately."
      );
      return;
    }
 
    if (this.polySegInitializing) {
      await this.polySegInitializingPromise;
      return;
    }
 
    if (this.polySeg?.instance) {
      return;
    }
 
    this.polySegInitializing = true;
    this.polySegInitializingPromise = new Promise((resolve) => {
      this.polySeg = new ICRPolySeg();
      this.polySeg
        .initialize({
          updateProgress: progressCallback,
        })
        .then(() => {
          this.polySegInitializing = false;
          resolve();
        });
    });
 
    await this.polySegInitializingPromise;
  },
  /**
   * Converts a contour to a surface using the PolySeg library.
   * @param {Object} args - The arguments for the conversion.
   * @param {Array} args.polylines - The polylines representing the contour.
   * @param {Array} args.numPointsArray - The number of points in each polyline.
   * @param {...Function} callbacks - Optional callback functions.
   * @returns {Promise} - A promise that resolves to the converted surface.
   */
  async convertContourToSurface(args, ...callbacks) {
    const { polylines, numPointsArray } = args;
    const [progressCallback] = callbacks;
    await this.initializePolySeg(progressCallback);
    const results = await this.polySeg.instance.convertContourRoiToSurface(
      polylines,
      numPointsArray
    );
 
    return results;
  },
  /**
   * Converts a labelmap to a surface using the specified arguments.
   * @param {Object} args - The arguments for the conversion.
   * @param {Array} args.scalarData - The scalar data of the labelmap.
   * @param {Array} args.dimensions - The dimensions of the labelmap.
   * @param {Array} args.spacing - The spacing of the labelmap.
   * @param {Array} args.direction - The direction of the labelmap.
   * @param {Array} args.origin - The origin of the labelmap.
   * @param {number} args.segmentIndex - The segment index of the labelmap.
   * @param {Function} progressCallback - The callback function for progress updates.
   * @returns {Promise} - A promise that resolves with the converted surface results.
   */
  async convertLabelmapToSurface(args, ...callbacks) {
    const [progressCallback] = callbacks;
    await this.initializePolySeg(progressCallback);
 
    const results = this.polySeg.instance.convertLabelmapToSurface(
      args.scalarData,
      args.dimensions,
      args.spacing,
      args.direction,
      args.origin,
      [args.segmentIndex]
    );
    const rotationInfo = checkStandardBasis(args.direction);
    if (!rotationInfo.isStandard) {
      const rotatedPoints = rotatePoints(
        rotationInfo.rotationMatrix,
        args.origin,
        results.points
      );
      results.points = [...rotatedPoints];
    }
    return results;
  },
  /**
   * Converts a contour to a volume labelmap.
   * @param {Object} args - The arguments for the conversion.
   * @param {Array} args.segmentIndices - The indices of the segments.
   * @param {Array} args.scalarData - The scalar data.
   * @param {Map} args.annotationUIDsInSegmentMap - The map of annotation UIDs in segment.
   * @param {Array} args.dimensions - The dimensions of the image data.
   * @param {Array} args.origin - The origin of the image data.
   * @param {Array} args.direction - The direction of the image data.
   * @param {Array} args.spacing - The spacing of the image data.
   * @param {...Function} callbacks - Optional callbacks.
   * @param {Function} callbacks[0] - The progress callback.
   * @returns {Array} - The scalar data of the segmentation voxel manager.
   */
  async convertContourToVolumeLabelmap(args, ...callbacks) {
    const [progressCallback] = callbacks;
    await this.initializePolySeg(progressCallback);
 
    const {
      segmentIndices,
      scalarData,
      annotationUIDsInSegmentMap,
      dimensions,
      origin,
      direction,
      spacing,
    } = args;
 
    const segmentationVoxelManager =
      utilities.VoxelManager.createScalarVolumeVoxelManager({
        dimensions,
        scalarData,
      });
 
    const imageData = vtkImageData.newInstance();
    imageData.setDimensions(dimensions);
    imageData.setOrigin(origin);
    imageData.setDirection(direction);
    imageData.setSpacing(spacing);
 
    const scalarArray = vtkDataArray.newInstance({
      name: 'Pixels',
      numberOfComponents: 1,
      values: scalarData,
    });
 
    imageData.getPointData().setScalars(scalarArray);
 
    imageData.modified();
 
    for (const index of segmentIndices) {
      const annotations = annotationUIDsInSegmentMap.get(index);
 
      for (const annotation of annotations) {
        if (!annotation.polyline) {
          continue;
        }
 
        const { polyline, holesPolyline } = annotation;
        const bounds = getBoundingBoxAroundShapeWorld(polyline);
 
        const [iMin, jMin, kMin] = utilities.transformWorldToIndex(imageData, [
          bounds[0][0],
          bounds[1][0],
          bounds[2][0],
        ]);
 
        const [iMax, jMax, kMax] = utilities.transformWorldToIndex(imageData, [
          bounds[0][1],
          bounds[1][1],
          bounds[2][1],
        ]);
 
        const { projectedPolyline, sharedDimensionIndex } =
          projectTo2D(polyline);
 
        const holes = holesPolyline?.map((hole) => {
          const { projectedPolyline: projectedHole } = projectTo2D(hole);
          return projectedHole;
        });
 
        const firstDim = (sharedDimensionIndex + 1) % 3;
        const secondDim = (sharedDimensionIndex + 2) % 3;
 
        const voxels = utilities.VoxelManager.createScalarVolumeVoxelManager({
          dimensions,
          scalarData,
        });
 
        voxels.forEach(
          ({ pointIJK }) => {
            segmentationVoxelManager.setAtIJKPoint(pointIJK, index);
          },
          {
            imageData,
            isInObject: (pointLPS) => {
              const point2D = [pointLPS[firstDim], pointLPS[secondDim]];
 
              // Check if the point is inside any of the polylines for this segment
              const isInside = containsPoint(projectedPolyline, point2D, {
                holes,
              });
 
              return isInside;
            },
            boundsIJK: [
              [iMin, iMax],
              [jMin, jMax],
              [kMin, kMax],
            ],
          }
        );
      }
    }
 
    return segmentationVoxelManager.scalarData;
  },
  /**
   * Converts a contour to a stack labelmap.
   * @param {Object} args - The arguments for the conversion.
   * @param {Array} callbacks - Optional callbacks for progress updates.
   * @returns {Promise<Object>} - The converted segmentations information.
   */
  async convertContourToStackLabelmap(args, ...callbacks) {
    const [progressCallback] = callbacks;
    await this.initializePolySeg(progressCallback);
 
    const { segmentationsInfo, annotationUIDsInSegmentMap, segmentIndices } =
      args;
 
    const segmentationVoxelManagers = new Map();
 
    segmentationsInfo.forEach((segmentationInfo, referencedImageId) => {
      const { dimensions, scalarData, direction, spacing, origin } =
        segmentationInfo;
      const manager = utilities.VoxelManager.createScalarVolumeVoxelManager({
        dimensions,
        scalarData,
      });
 
      const imageData = vtkImageData.newInstance();
      imageData.setDimensions(dimensions);
      imageData.setOrigin(origin);
      imageData.setDirection(direction);
      imageData.setSpacing(spacing);
 
      const scalarArray = vtkDataArray.newInstance({
        name: 'Pixels',
        numberOfComponents: 1,
        values: scalarData,
      });
 
      imageData.getPointData().setScalars(scalarArray);
 
      imageData.modified();
 
      segmentationVoxelManagers.set(referencedImageId, { manager, imageData });
    });
 
    for (const index of segmentIndices) {
      const annotations = annotationUIDsInSegmentMap.get(index);
 
      for (const annotation of annotations) {
        if (!annotation.polyline) {
          continue;
        }
 
        const { polyline, holesPolyline, referencedImageId } = annotation;
        const bounds = getBoundingBoxAroundShapeWorld(polyline);
 
        const { manager: segmentationVoxelManager, imageData } =
          segmentationVoxelManagers.get(referencedImageId);
 
        const [iMin, jMin, kMin] = utilities.transformWorldToIndex(imageData, [
          bounds[0][0],
          bounds[1][0],
          bounds[2][0],
        ]);
 
        const [iMax, jMax, kMax] = utilities.transformWorldToIndex(imageData, [
          bounds[0][1],
          bounds[1][1],
          bounds[2][1],
        ]);
 
        const { projectedPolyline, sharedDimensionIndex } =
          projectTo2D(polyline);
 
        const holes = holesPolyline?.map((hole) => {
          const { projectedPolyline: projectedHole } = projectTo2D(hole);
          return projectedHole;
        });
 
        const firstDim = (sharedDimensionIndex + 1) % 3;
        const secondDim = (sharedDimensionIndex + 2) % 3;
        const voxels = utilities.VoxelManager.createImageVoxelManager({
          width: imageData.getDimensions()[0],
          height: imageData.getDimensions()[1],
          scalarData: imageData.getPointData().getScalars().getData(),
        });
 
        voxels.forEach(
          ({ pointIJK }) => {
            segmentationVoxelManager.setAtIJKPoint(pointIJK, index);
          },
          {
            imageData,
            isInObject: (pointLPS) => {
              const point2D = [pointLPS[firstDim], pointLPS[secondDim]];
 
              // Check if the point is inside any of the polylines for this segment
              const isInside = containsPoint(projectedPolyline, point2D, {
                holes,
              });
 
              return isInside;
            },
            boundsIJK: [
              [iMin, iMax],
              [jMin, jMax],
              [kMin, kMax],
            ],
          }
        );
      }
    }
 
    segmentationsInfo.forEach((segmentationInfo, referencedImageId) => {
      const { manager: segmentationVoxelManager } =
        segmentationVoxelManagers.get(referencedImageId);
 
      segmentationInfo.scalarData = segmentationVoxelManager.scalarData;
    });
    return segmentationsInfo;
  },
  /**
   * Converts a surface to a volume labelmap.
   *
   * @param {Object} args - The arguments for the conversion.
   * @param {Array} args.points - The points defining the surface.
   * @param {Array} args.polys - The polygons defining the surface.
   * @param {Array} args.dimensions - The dimensions of the volume.
   * @param {Array} args.spacing - The spacing between voxels in the volume.
   * @param {Array} args.direction - The direction of the volume.
   * @param {Array} args.origin - The origin of the volume.
   * @param {Function} progressCallback - The callback function for reporting progress.
   * @returns {Promise} - A promise that resolves with the converted labelmap.
   */
  async convertSurfaceToVolumeLabelmap(args, ...callbacks) {
    const [progressCallback] = callbacks;
    await this.initializePolySeg(progressCallback);
 
    const results = this.polySeg.instance.convertSurfaceToLabelmap(
      args.points,
      args.polys,
      args.dimensions,
      args.spacing,
      args.direction,
      args.origin
    );
 
    return results;
  },
  /**
   * Converts surfaces to a volume labelmap.
   * @param {Object} args - The arguments for the conversion.
   * @param {Map} args.segmentsInfo - A map containing information about the segments.
   * @param {Function} progressCallback - A callback function for reporting progress.
   * @returns {Uint8Array} - The resulting volume labelmap.
   */
  async convertSurfacesToVolumeLabelmap(args, ...callbacks) {
    const [progressCallback] = callbacks;
    await this.initializePolySeg(progressCallback);
 
    const { segmentsInfo } = args;
 
    const promises = Array.from(segmentsInfo.keys()).map((segmentIndex) => {
      const { points, polys } = segmentsInfo.get(segmentIndex);
      const result = this.polySeg.instance.convertSurfaceToLabelmap(
        points,
        polys,
        args.dimensions,
        args.spacing,
        args.direction,
        args.origin
      );
 
      return {
        ...result,
        segmentIndex,
      };
    });
 
    const results = await Promise.all(promises);
 
    const targetImageData = vtkImageData.newInstance();
    targetImageData.setDimensions(args.dimensions);
    targetImageData.setOrigin(args.origin);
    targetImageData.setSpacing(args.spacing);
    targetImageData.setDirection(args.direction);
 
    const totalSize =
      args.dimensions[0] * args.dimensions[1] * args.dimensions[2];
 
    const scalarArray = vtkDataArray.newInstance({
      name: 'Pixels',
      numberOfComponents: 1,
      values: new Uint8Array(totalSize),
    });
 
    targetImageData.getPointData().setScalars(scalarArray);
    targetImageData.modified();
 
    // we need to then consolidate the results into a single volume
    // by looping into each voxel with voxelmanager for each
    // and check if the voxel is inside any of the reconstructed
    // labelmaps
    const { dimensions } = args;
    const scalarData = targetImageData.getPointData().getScalars().getData();
    const segmentationVoxelManager =
      utilities.VoxelManager.createScalarVolumeVoxelManager({
        dimensions,
        scalarData,
      });
 
    const outputVolumesInfo = results.map((result) => {
      const { data, dimensions, direction, origin, spacing } = result;
      const volume = vtkImageData.newInstance();
      volume.setDimensions(dimensions);
      volume.setOrigin(origin);
      volume.setSpacing(spacing);
      volume.setDirection(direction);
 
      const scalarArray = vtkDataArray.newInstance({
        name: 'Pixels',
        numberOfComponents: 1,
        values: data,
      });
 
      volume.getPointData().setScalars(scalarArray);
 
      volume.modified();
 
      const voxelManager =
        utilities.VoxelManager.createScalarVolumeVoxelManager({
          dimensions,
          scalarData: data,
        });
 
      const extent = volume.getExtent(); // e.g., [0, 176, 0, 268, 0, 337] for dimensions of [177, 269, 338]
 
      return {
        volume,
        voxelManager,
        extent,
        scalarData: data,
        segmentIndex: result.segmentIndex,
      };
    });
 
    const voxels = utilities.VoxelManager.createScalarVolumeVoxelManager({
      dimensions: targetImageData.getDimensions(),
      scalarData: targetImageData.getPointData().getScalars().getData(),
    });
 
    voxels.forEach(
      ({ pointIJK, pointLPS }) => {
        // Check if the point is inside any of the reconstructed labelmaps
        // Todo: we can optimize this by returning early if the bounding box
        // of the point is outside the bounding box of the labelmap
 
        try {
          for (const volumeInfo of outputVolumesInfo) {
            const { volume, extent, voxelManager, segmentIndex } = volumeInfo;
 
            const index = volume.worldToIndex(pointLPS);
 
            // check if the ijk point is inside the volume
            if (
              index[0] < extent[0] ||
              index[0] > extent[1] ||
              index[1] < extent[2] ||
              index[1] > extent[3] ||
              index[2] < extent[4] ||
              index[2] > extent[5]
            ) {
              continue;
            }
 
            const roundedIndex = index.map(Math.round);
            const value = voxelManager.getAtIJK(...roundedIndex);
            if (value > 0) {
              segmentationVoxelManager.setAtIJKPoint(pointIJK, segmentIndex);
              break;
            }
          }
        } catch (error) {
          // right now there is weird error if the point is outside the volume
        }
      },
      { imageData: targetImageData }
    );
 
    return segmentationVoxelManager.scalarData;
  },
  getSurfacesAABBs({ surfacesInfo }) {
    const aabbs = new Map();
    for (const { points, id } of surfacesInfo) {
      const aabb = getAABB(points, { numDimensions: 3 });
      aabbs.set(id, aabb);
    }
    return aabbs;
  },
  /**
   * Cuts the surfaces into planes.
   *
   * @param {Object} options - The options object.
   * @param {Array} options.planesInfo - The information about the planes.
   * @param {Array} options.surfacesInfo - The information about the surfaces.
   * @param {Function} progressCallback - The callback function for progress updates.
   * @param {Function} updateCacheCallback - The callback function for updating the cache.
   */
  cutSurfacesIntoPlanes(
    { planesInfo, surfacesInfo, surfacesAABB = new Map() },
    progressCallback,
    updateCacheCallback
  ) {
    const numberOfPlanes = planesInfo.length;
    const cutter = vtkCutter.newInstance();
 
    const plane1 = vtkPlane.newInstance();
 
    cutter.setCutFunction(plane1);
 
    const surfacePolyData = vtkPolyData.newInstance();
 
    try {
      for (const [index, planeInfo] of planesInfo.entries()) {
        const { sliceIndex, planes } = planeInfo;
 
        const polyDataResults = new Map();
        for (const polyDataInfo of surfacesInfo) {
          const { points, polys, id, segmentIndex } = polyDataInfo;
 
          const aabb3 =
            surfacesAABB.get(id) || getAABB(points, { numDimensions: 3 });
 
          if (!surfacesAABB.has(id)) {
            surfacesAABB.set(id, aabb3);
          }
 
          const { minX, minY, minZ, maxX, maxY, maxZ } = aabb3;
 
          const { origin, normal } = planes[0];
 
          // Check if the plane intersects the AABB
          if (
            !isPlaneIntersectingAABB(
              origin,
              normal,
              minX,
              minY,
              minZ,
              maxX,
              maxY,
              maxZ
            )
          ) {
            continue;
          }
 
          // Set up the initial polydata
          surfacePolyData.getPoints().setData(points, 3);
          surfacePolyData.getPolys().setData(polys);
          surfacePolyData.modified();
 
          cutter.setInputData(surfacePolyData);
          plane1.setOrigin(origin);
          plane1.setNormal(normal);
 
          try {
            cutter.update();
          } catch (e) {
            console.warn('Error during clipping', e);
            continue;
          }
 
          const polyData = cutter.getOutputData();
 
          // Additional validation of cutter output
          if (
            !polyData ||
            !polyData.getPoints() ||
            polyData.getPoints().getNumberOfPoints() === 0
          ) {
            continue;
          }
 
          const cutterOutput = polyData;
          cutterOutput.buildLinks();
          const loopExtraction = vtkContourLoopExtraction.newInstance();
          loopExtraction.setInputData(cutterOutput);
 
          try {
            loopExtraction.update();
            const loopOutput = loopExtraction.getOutputData();
 
            if (
              loopOutput &&
              loopOutput.getPoints() &&
              loopOutput.getLines() &&
              loopOutput.getPoints().getNumberOfPoints() > 0 &&
              loopOutput.getLines().getNumberOfCells() > 0
            ) {
              polyDataResults.set(segmentIndex, {
                points: loopOutput.getPoints().getData(),
                lines: loopOutput.getLines().getData(),
                numberOfCells: loopOutput.getLines().getNumberOfCells(),
                segmentIndex,
              });
            }
          } catch (loopError) {
            console.warn('Error during loop extraction:', loopError);
            continue;
          }
        }
 
        progressCallback({ progress: (index + 1) / numberOfPlanes });
 
        updateCacheCallback({ sliceIndex, polyDataResults });
      }
    } catch (e) {
      console.warn('Error during processing', e);
    } finally {
      // Cleanup on completion
      surfacesInfo = null;
      plane1.delete();
    }
  },
};
 
expose(polySegConverters);