Example #1
0
def main(argv):

    try:
        logging.info("Start batch RTSTRUCT conversion")

        # Parse command-line arguments
        parser = argparse.ArgumentParser(
            description="Batch Structure Set Conversion")
        parser.add_argument(
            "-i",
            "--input-folder",
            dest="input_folder",
            metavar="PATH",
            default="-",
            required=True,
            help=
            "Folder of input DICOM study (or database path to use existing)")
        parser.add_argument(
            "-r",
            "--ref-dicom-folder",
            dest="ref_dicom_folder",
            metavar="PATH",
            default="",
            required=False,
            help=
            "Folder containing reference anatomy DICOM image series, if stored outside the input study"
        )
        parser.add_argument(
            "-u",
            "--use-ref-image",
            dest="use_ref_image",
            default=False,
            required=False,
            action='store_true',
            help=
            "Use anatomy image as reference when converting structure set to labelmap"
        )
        parser.add_argument("-x",
                            "--exist-db",
                            dest="exist_db",
                            default=False,
                            required=False,
                            action='store_true',
                            help="Process an existing database")
        parser.add_argument("-m",
                            "--export-images",
                            dest="export_images",
                            default=False,
                            required=False,
                            action='store_true',
                            help="Export image data with labelmaps")
        parser.add_argument("-o",
                            "--output-folder",
                            dest="output_folder",
                            metavar="PATH",
                            default=".",
                            help="Folder for output labelmaps")
        parser.add_argument("-s",
                            "--export-surfaces",
                            dest="export_surfaces",
                            default=False,
                            required=False,
                            action='store_true',
                            help="Export surface mesh representation")
        parser.add_argument(
            "-c",
            "--show-python-console",
            dest="show_python_console",
            default=False,
            required=False,
            action='store_true',
            help=
            "If this flag is specified then messages are displayed in an interactive Python console and the application does not quit when the script is finished."
        )

        args = parser.parse_args(argv)

        if args.show_python_console:
            slicer.util.pythonShell().show()
            slicer.exit_when_finished = False

        # Check if SlicerRT is installed
        try:
            slicer.modules.dicomrtimportexport
        except AttributeError:
            logging.error("Please install SlicerRT extension")
            return 1

        # Check required arguments
        if args.input_folder == "-":
            logging.warning('Please specify input DICOM study folder!')
        if args.output_folder == ".":
            logging.info(
                'Current directory is selected as output folder (default). To change it, please specify --output-folder'
            )

        # Convert to python path style
        input_folder = args.input_folder.replace('\\', '/')
        ref_dicom_folder = args.ref_dicom_folder.replace('\\', '/')
        output_folder = args.output_folder.replace('\\', '/')

        use_ref_image = args.use_ref_image
        exist_db = args.exist_db
        export_images = args.export_images
        export_surfaces = args.export_surfaces

        # Perform batch conversion
        logic = BatchStructureSetConversionLogic()

        def save_rtslices(output_dir, use_ref_image, ref_image_node_id=None):
            # package the saving code into a subfunction
            logging.info("Convert loaded structure set to labelmap volumes")
            labelmaps = logic.ConvertStructureSetToLabelmap(
                use_ref_image, ref_image_node_id)

            logging.info("Save labelmaps to directory " + output_dir)
            logic.SaveLabelmaps(labelmaps, output_dir)
            if export_surfaces:
                logic.SaveModels(output_dir)
            if export_images:
                logic.SaveImages(output_dir)
            logging.info("DONE")

        if exist_db:
            logging.info('BatchStructureSet running in existing database mode')
            DICOMUtils.openDatabase(input_folder)
            all_patients = slicer.dicomDatabase.patients()
            logging.info('Processing %d patients...' % len(all_patients))

            for patient in all_patients:
                try:
                    slicer.mrmlScene.Clear(0)  # clear the scene
                    DICOMUtils.loadPatientByUID(patient)
                    output_dir = os.path.join(output_folder, patient)
                    if not os.access(output_dir, os.F_OK):
                        os.mkdir(output_dir)
                    save_rtslices(output_dir, use_ref_image)
                except OSError as e:
                    # Failed to load data from this patient, continue with the next one
                    print(e)

        else:
            logging.info('BatchStructureSet running in file mode')
            ref_volume_file_path = None
            if os.path.isdir(ref_dicom_folder):
                # If reference DICOM folder is given and valid, then import reference patient and save its ID
                logging.info("Import reference anatomy DICOM data from " +
                             ref_dicom_folder)
                DICOMUtils.openTemporaryDatabase()
                DICOMUtils.importDicom(ref_dicom_folder)
                # Save first volume to be used as reference
                logic.LoadFirstPatientIntoSlicer()
                scalarVolumeNodes = list(
                    slicer.util.getNodes('vtkMRMLScalarVolume*').values())
                if len(scalarVolumeNodes) > 0:
                    refVolNode = scalarVolumeNodes[0]
                    refVolStorageNode = refVolNode.CreateDefaultStorageNode()
                    ref_volume_file_path = os.path.join(
                        output_folder, 'refVolume.nrrd')
                    refVolStorageNode.SetFileName(ref_volume_file_path)
                    refVolStorageNode.WriteData(refVolNode)

            logging.info("Import DICOM data from " + input_folder)
            DICOMUtils.openTemporaryDatabase()
            DICOMUtils.importDicom(input_folder)

            all_patients = slicer.dicomDatabase.patients()
            logging.info('Processing %d patients...' % len(all_patients))
            for patient in all_patients:
                try:
                    slicer.mrmlScene.Clear(0)  # clear the scene
                    DICOMUtils.loadPatientByUID(patient)
                    output_dir = os.path.join(output_folder, patient)
                    if not os.access(output_dir, os.F_OK):
                        os.mkdir(output_dir)
                    ref_volume_node_id = None
                    if ref_volume_file_path:
                        try:
                            refVolNode = slicer.util.loadVolume(
                                ref_volume_file_path)
                            ref_volume_node_id = refVolNode.GetID()
                        except:
                            pass
                    save_rtslices(output_dir, use_ref_image,
                                  ref_volume_node_id)
                except OSError as e:
                    # Failed to load data from this patient, continue with the next one
                    print(e)

    except Exception as e:
        import traceback
        traceback.print_exc()
        print(e)
        return 1

    return 0
Example #2
0
def main(argv):
    try:
        # Parse command-line arguments
        parser = argparse.ArgumentParser(
            description="Batch Structure Set Conversion")
        parser.add_argument(
            "-i",
            "--input-folder",
            dest="input_folder",
            metavar="PATH",
            default="-",
            required=True,
            help=
            "Folder of input DICOM study (or database path to use existing)")
        parser.add_argument(
            "-r",
            "--ref-dicom-folder",
            dest="ref_dicom_folder",
            metavar="PATH",
            default="",
            required=False,
            help=
            "Folder containing reference anatomy DICOM image series, if stored outside the input study"
        )
        parser.add_argument(
            "-u",
            "--use-ref-image",
            dest="use_ref_image",
            default=False,
            required=False,
            action='store_true',
            help=
            "Use anatomy image as reference when converting structure set to labelmap"
        )
        parser.add_argument("-x",
                            "--exist-db",
                            dest="exist_db",
                            default=False,
                            required=False,
                            action='store_true',
                            help="Process an existing database")
        parser.add_argument("-m",
                            "--export-images",
                            dest="export_images",
                            default=False,
                            required=False,
                            action='store_true',
                            help="Export image data with labelmaps")
        parser.add_argument("-o",
                            "--output-folder",
                            dest="output_folder",
                            metavar="PATH",
                            default=".",
                            help="Folder for output labelmaps")

        args = parser.parse_args(argv)

        # Check required arguments
        if args.input_folder == "-":
            logging.warning('Please specify input DICOM study folder!')
        if args.output_folder == ".":
            logging.info(
                'Current directory is selected as output folder (default). To change it, please specify --output-folder'
            )

        # Convert to python path style
        input_folder = args.input_folder.replace('\\', '/')
        ref_dicom_folder = args.ref_dicom_folder.replace('\\', '/')
        output_folder = args.output_folder.replace('\\', '/')

        use_ref_image = args.use_ref_image
        exist_db = args.exist_db
        export_images = args.export_images

        # Perform batch conversion
        logic = BatchStructureSetConversionLogic()

        def save_rtslices(output_dir, use_ref_image, ref_image_node_id=None):
            # package the saving code into a subfunction
            logging.info("Convert loaded structure set to labelmap volumes")
            labelmaps = logic.ConvertStructureSetToLabelmap(
                use_ref_image, ref_image_node_id)

            logging.info("Save labelmaps to directory " + output_dir)
            logic.SaveLabelmaps(labelmaps, output_dir)
            if export_images:
                logic.SaveImages(output_dir)
            logging.info("DONE")

        if exist_db:
            logging.info('BatchStructureSet running in existing database mode')
            DICOMUtils.openDatabase(input_folder)
            all_patients = slicer.dicomDatabase.patients()
            logging.info('Must Process Patients %s' % len(all_patients))

            for patient in all_patients:
                slicer.mrmlScene.Clear(0)  # clear the scene
                DICOMUtils.loadPatientByUID(patient)
                output_dir = os.path.join(output_folder, patient)
                if not os.access(output_dir, os.F_OK):
                    os.mkdir(output_dir)
                save_rtslices(output_dir, use_ref_image)

        else:
            ref_image_node_id = None
            if os.path.isdir(ref_dicom_folder):
                # If reference DICOM folder is given and valid, then load that volume
                logging.info("Import reference anatomy DICOM data from " +
                             ref_dicom_folder)
                DICOMUtils.openTemporaryDatabase()
                DICOMUtils.importDicom(ref_dicom_folder)
                logic.LoadFirstPatientIntoSlicer()
                # Remember first volume
                scalarVolumeNodes = list(
                    slicer.util.getNodes('vtkMRMLScalarVolume*').values())
                if len(scalarVolumeNodes) > 0:
                    ref_image_node_id = scalarVolumeNodes[0].GetID()

            logging.info("Import DICOM data from " + input_folder)
            DICOMUtils.openTemporaryDatabase()
            DICOMUtils.importDicom(input_folder)

            logging.info("Load first patient into Slicer")
            logic.LoadFirstPatientIntoSlicer()
            save_rtslices(output_folder, use_ref_image, ref_image_node_id)

    except Exception as e:
        print(e)
    sys.exit(0)
Example #3
0
def main(argv):
  try:
    # Parse command-line arguments
    parser = argparse.ArgumentParser(description="Batch Structure Set Conversion")
    parser.add_argument("-i", "--input-folder", dest="input_folder", metavar="PATH",
                        default="-", required=True, help="Folder of input DICOM study (or database path to use existing)")
    parser.add_argument("-x", "--exist-db", dest="exist_db",
                        default=False, required=False, action='store_true',
                        help="Process an existing database")
    parser.add_argument("-m", "--export-images", dest="export_images",
                        default=False, required=False, action='store_true',
                        help="Export image data with labelmaps")
    parser.add_argument("-o", "--output-folder", dest="output_folder", metavar="PATH",
                        default=".", help="Folder for output labelmaps")

    args = parser.parse_args(argv)

    # Check required arguments
    if args.input_folder == "-":
      logging.warning('Please specify input DICOM study folder!')
    if args.output_folder == ".":
      logging.info('Current directory is selected as output folder (default). To change it, please specify --output-folder')

    # Convert to python path style
    input_folder = args.input_folder.replace('\\', '/')
    output_folder = args.output_folder.replace('\\', '/')
    exist_db = args.exist_db
    export_images = args.export_images

    # Perform batch conversion
    logic = BatchStructureSetConversionLogic()
    def save_rtslices(output_dir):
      # package the saving code into a subfunction
      logging.info("Convert loaded structure set to labelmap volumes")
      labelmaps = logic.ConvertStructureSetToLabelmap()

      logging.info("Save labelmaps to directory " + output_dir)
      logic.SaveLabelmaps(labelmaps, output_dir)
      if export_images:
        logic.SaveImages(output_dir)
      logging.info("DONE")

    if exist_db:
      logging.info('BatchStructureSet running in existing database mode')
      DICOMUtils.openDatabase(input_folder)
      all_patients = slicer.dicomDatabase.patients()
      logging.info('Must Process Patients %s' % len(all_patients))
      for patient in all_patients:
        slicer.mrmlScene.Clear(0) # clear the scene
        DICOMUtils.loadPatientByUID(patient)
        output_dir = os.path.join(output_folder,patient)
        if not os.access(output_dir, os.F_OK):
          os.mkdir(output_dir)
        save_rtslices(output_dir)
    else:
      logging.info("Import DICOM data from " + input_folder)
      DICOMUtils.openTemporaryDatabase()
      DICOMUtils.importDicom(input_folder)

      logging.info("Load first patient into Slicer")
      logic.LoadFirstPatientIntoSlicer()
      save_rtslices(output_folder)

  except Exception as e:
      print(e)
  sys.exit(0)
def main(argv):
  try:
    # Parse command-line arguments
    parser = argparse.ArgumentParser(description="Batch Structure Set Conversion")
    parser.add_argument("-i", "--input-folder", dest="input_folder", metavar="PATH",
                        default="-", required=True, help="Folder of input DICOM study (or database path to use existing)")
    parser.add_argument("-x", "--exist-db", dest="exist_db",
                        default=False, required=False, action='store_true',
                        help="Process an existing database")
    parser.add_argument("-m", "--export-images", dest="export_images",
                        default=False, required=False, action='store_true',
                        help="Export image data with labelmaps")
    parser.add_argument("-o", "--output-folder", dest="output_folder", metavar="PATH",
                        default=".", help="Folder for output labelmaps")

    args = parser.parse_args(argv)

    # Check required arguments
    if args.input_folder == "-":
      logging.warning('Please specify input DICOM study folder!')
    if args.output_folder == ".":
      logging.info('Current directory is selected as output folder (default). To change it, please specify --output-folder')

    # Convert to python path style
    input_folder = args.input_folder.replace('\\', '/')
    output_folder = args.output_folder.replace('\\', '/')
    exist_db = args.exist_db
    export_images = args.export_images

    # Perform batch conversion
    logic = BatchStructureSetConversionLogic()
    def save_rtslices(output_dir):
      # package the saving code into a subfunction
      logging.info("Convert loaded structure set to labelmap volumes")
      labelmaps = logic.ConvertStructureSetToLabelmap()

      logging.info("Save labelmaps to directory " + output_dir)
      logic.SaveLabelmaps(labelmaps, output_dir)
      if export_images:
        logic.SaveImages(output_dir)
      logging.info("DONE")

    if exist_db:
      logging.info('BatchStructureSet running in existing database mode')
      DICOMUtils.openDatabase(input_folder)
      all_patients = slicer.dicomDatabase.patients()
      logging.info('Must Process Patients %s' % len(all_patients))
      for patient in all_patients:
        slicer.mrmlScene.Clear(0) # clear the scene
        DICOMUtils.loadPatientByUID(patient)
        output_dir = os.path.join(output_folder,patient)
        if not os.access(output_dir, os.F_OK):
          os.mkdir(output_dir)
        save_rtslices(output_dir)
    else:
      logging.info("Import DICOM data from " + input_folder)
      DICOMUtils.openTemporaryDatabase()
      DICOMUtils.importDicom(input_folder)

      logging.info("Load first patient into Slicer")
      logic.LoadFirstPatientIntoSlicer()
      save_rtslices(output_folder)

  except Exception, e:
      print(e)