javascriptimage-processingmedicalmedical-imagingcornerstonejs

Select segmentation by mouse and change the color in Cornerstone.js


I’m using cornerstoneTools with the Cornerstone.js DICOM view. I draw multiple segments by the Cornerstone.js segment tool and load the segments from RLE.

How can I select an existing segment by clicking it by mouse on the DICOM viewer?


Solution

  • It’s not possible to set the segmentation colour directly in Cornerstone.js. However, you can set the color in Cornerstone.js by switching your desired color from colorLutTables.

    To do this, you have to do three steps:

    1. Set colorLutTables with your list of colors, for example.

      const COLORLIST = [[255,0,0,255], [255,255,0,255],[0,0,255,255],[255,255,255,255]] // four colors red, yellow, blue and white
      
      // Set colorLut list when you initialise cornerstone tools
      
      const { configuration, state } = cornerstoneTools.getModule('segmentation');
      state.colorLutTables[0] = COLORLIST
      
    2. Selecting the segment. This one. Also, there isn't any straight way to select a segment in Cornerstone.js. To do this, you have to use the Cornerstone.js tools event listener. You can use the cornerstonetoolsmouseclick event by attach this event to your Cornerstone.js-enabled element.

      element.addEventListener("cornerstonetoolsmouseclick", (e) => {
        const {getters: {segmentOfActiveLabelmapAtEvent}, setters: {deleteSegment}} = cornerstoneTools.getModule('segmentation');
      });
        const isSegment = segmentOfActiveLabelmapAtEvent(e); // If your mouse clicked any segments this will return an object otherwise undefined
         if(isSegment !== undefined) {
           // Here you can switch the colorLut index with your selected segment index, for example you can replace white color's index in colorLUT table
         }
      
    3. Switching indexes in colorLUT, from any color to white

      /*
      * from:     Desired colors index
      * to:       selectedSegment index
      * colorLUT: colorLUTTable array
      * element:  Active element
      */
      const switchColorLUT = (from, to, colorLUT, element) => {
          const updatedLUT = [...colorLUT];
          [updatedLUT[from], updatedLUT[to]] = [updatedLUT[to], updatedLUT[from]];
          const {state, getters, setters} = cornerstoneTools.getModule('segmentation');
          state.colorLutTables[0] = updatedLUT
          setters.activeSegmentIndex(element, to)
          setters.activeLabelmapIndex(element, 0);
          cornerstone.updateImage(element)
      }
      

      You can use this function to update the colorLUT table:

      // Inside `cornerstonetoolsmouseclick` event
      switchColorLUT(COLORLIST.length -1, isSegment.segmentIndex, COLORLIST, element);
      

      This will update the selected segment to a white color.