Ejemplo n.º 1
0
    def make_png(self):
        """Create mask for each structure for all patients."""
        print(f"Structure(s) to export: {self.structures}")
        print(f"Patient(s) identification : {self.patients}")

        for index, path_patient in enumerate(self.patient_paths):
            patient_id = self.patients[index]
            print(f"Exporting {index + 1} ({patient_id}) on {len(self.patients)}")
            nii_output = os.path.join(path_patient, "output")

            _, not_missing = self.find_structures(index)
            dcmrtstruct2nii(self.rs_paths[index], path_patient, nii_output, not_missing, False, mask_foreground_value=1)

            nii_maks = [nii_mask for nii_mask in os.listdir(nii_output) if nii_mask.startswith('mask')]
            
            for nii in nii_maks:
                nii_object = nib.load(os.path.join(nii_output, nii))
                name = os.path.splitext(nii)[0].split("_")[1].replace("-", " ")
                self.nii_to_png(name, nii_object, patient_id)

            ct_nii_object = nib.load(os.path.join(nii_output, "image.nii"))
            self.nii_to_png("ct", ct_nii_object, patient_id)


        print(f"Export done")
Ejemplo n.º 2
0
def rtstruct2nii(rtstruct_file, original_dcm, output_path):
    try:
        dcmrtstruct2nii(rtstruct_file, original_dcm, output_path)
    except Exception as e:
        print(e)
        exc_type, exc_value, exc_traceback = sys.exc_info()
        traceback.print_tb(exc_traceback)
        sys.exit(1)
    try:
        os.chdir(output_path)
        for file in glob.glob("mask*.gz"):
            print(file)
            mask_nii_gz = file
            mask_nii = os.path.splitext(mask_nii_gz)[0]
            print(mask_nii)
            with gzip.open(os.path.join(output_path, mask_nii_gz),
                           'r') as f_in, open(
                               os.path.join(output_path, mask_nii),
                               'wb') as f_out:
                shutil.copyfileobj(f_in, f_out)
    except Exception as error:
        print(error)
        exc_type, exc_value, exc_traceback = sys.exc_info()
        traceback.print_tb(exc_traceback)
        sys.exit(1)
Ejemplo n.º 3
0
def test_bmia_stwstrategyhn1(tmpdir):
    dataset = Path(tmpdir / 'stwstrategyhn1')
    dcmrtstruct2niidir = Path(tmpdir / 'dcmrtstruct2nii')

    dcmrtstruct2niidir.mkdir(exist_ok=True)

    counter = 0
    subjects = list_subjects_stwstrategyhn1()
    numsubjects = len(subjects)

    for subject in subjects:
        counter += 1
        print(f'Comparing {subject.label} {counter}/{numsubjects}')

        subject_dir = Path(dataset / subject.label)
        download_subject(subject, subject_dir)

        rtstructs = list(
            subject_dir.glob('*/scans/*/resources/secondary/files/*'))
        if len(rtstructs) > 1 or len(rtstructs) <= 0:
            assert False, f'> 1 RTSTRUCT or <= 0 RTSTRUCT found for subject {subject.label}, something changed in the dataset?'
        rtstruct = rtstructs[0]

        dicoms = list(subject_dir.glob('*/scans/*/resources/DICOM/files'))
        if len(dicoms) > 1 or len(dicoms) <= 0:
            assert False, f'> 1 DICOM or <= 0 DICOM found for subject {subject.label}, something changed in the dataset?'

        dicom = dicoms[0]

        subjoutdir = Path(dcmrtstruct2niidir / subject.label)
        subjoutdir.mkdir(exist_ok=True)

        dcmrtstruct2nii(rtstruct, dicom, subjoutdir)

        niicounter = 0
        for nii in subjoutdir.glob('*.nii.gz'):
            niicounter += 1
            niftis = list(subject_dir.glob(f'**/{nii.name}'))

            if len(niftis) > 1 or len(niftis) <= 0:
                assert False, f'> 1 niftis or <= 0 niftis {nii.name} found for subject {subject.label}, something changed in the dataset?'

            nii_stwstrategyhn1 = niftis[0]

            diff = diffnii(nii, nii_stwstrategyhn1)

            if not (diff['similarity'] > .95 and diff['similarity'] < 1.05):
                assert False, f'niftis not equal {diff["similarity"]}, {nii}:{nii_stwstrategyhn1} data: {diff}'

        print(f"Compared {niicounter} NiFTI's for subject {subject.label}")

        # cleanup, GitHub runners only have ~14 GB of space
        shutil.rmtree(subjoutdir)
        shutil.rmtree(subject_dir)

    assert True
    def dcmrtstruct2niiLoop(currStruct): 
        try: 
            # Extract the structure and convert to Nifti
            # We do not want convert_original_dicom=True for all structures as this will add a lot of time. 
            # Do this only for BODY as this structure is always present. It has nothing to do with the structure itself for enabling convert_original_dicom=True. 
            if currStruct == 'BODY' or currStruct == 'External':
                dcmrtstruct2nii(patRTStructFile, patCTFolder, tempOutFolder, structures=currStruct, gzip=True, mask_background_value=0, mask_foreground_value=1, convert_original_dicom=True)
            else: 
                dcmrtstruct2nii(patRTStructFile, patCTFolder, tempOutFolder, structures=currStruct, gzip=True, mask_background_value=0, mask_foreground_value=1, convert_original_dicom=False)

        except: 
            print('An exception occurred in dcmrtstruct2nii data extraction for struct ' + str(currStruct))
            print(patRTStructFile)
            print(list_rt_structs(patRTStructFile))
            # Write to error log file,
            myInference.write2log(outFileNameErrors, 'An exception occurred in dcmrtstruct2nii data extraction for struct ' + str(currStruct))
Ejemplo n.º 5
0
    def patLargeDataLoop(patNr, patient):
        # Create new random seed
        # Important for parallell threading
        R=np.random.RandomState()
        # Create random large integer
        # Use it to name the folders
        randPatValue = R.randint(100000000000, 999999999999)
        # Patient folder where data files are originally contained
        patFolderPath = allPatFolder + '/' + patient
        # Move RS struct file that is not a CT Dicom file to another folder
        # otherwise dcmstruct2nii will not accept it
        RTStructFolderName = moveRTStructFile(patFolderPath)
        # Move CT files to a subdirectory under the patient
        CTFolderName = moveCTFiles(patFolderPath)
        # Patient folder where CT files now are contained
        patCTFolderPath = allPatFolder + '/' + patient +'/' + CTFolderName
        # Get RT struct file name
        RTStructFile = getRTStructFile(patFolderPath + '/' + RTStructFolderName)
        # Define whole path for RT struct file
        patRTStructFile = patFolderPath + '/' + RTStructFolderName + '/' + RTStructFile
        # Define patient output folder
        patOutFolderPath = outFolder + '/' + str(randPatValue)
        # Get list of all structures present
        structListExported = list_rt_structs(patRTStructFile)

        # Convert the RT structs to Nifty format 
        # This is performed by targeting each individual structure at a time in a loop. 
        # This is slower but safer. 
        # In this way we can isolate exceptions to individual structures and not break 
        # the process of dcmrtstruc2nii which happens otherwise. This avoids modification of the 
        # dcmrtstruc2nii source code and allows us in retrospect to see if missing data was important or not.
        # Failed objects are due to the fact that the structures are not completed or simply empty in Eclipse. 
        for structNr, currStruct in enumerate(structListExported):
            try:
                # Extract the structure and convert to Nifty
                # We do not want convert_original_dicom=True for all structures as this will add a lot of time. 
                # Do this only for BODY as this structure is always present. It has nothing to do with the structure itself for enabling convert_original_dicom=True. 
                if currStruct == 'BODY':
                    print(patient   + '  ' + str(randPatValue))
                    dcmrtstruct2nii(patRTStructFile, patCTFolderPath, patOutFolderPath, structures=currStruct, gzip=True, mask_background_value=0, mask_foreground_value=1, convert_original_dicom=True)
                else:
                    dcmrtstruct2nii(patRTStructFile, patCTFolderPath, patOutFolderPath, structures=currStruct, gzip=True, mask_background_value=0, mask_foreground_value=1, convert_original_dicom=False)
                
            except:
                print("Exception when extracting " + currStruct + ' for ' + patient  + ' ' + str(randPatValue))
Ejemplo n.º 6
0
    def make(self):
        """Create structures and convert the CT in nii format for each subject."""
        print(f"Structure(s) to export: {self.structures}")
        print(f"Patient(s) identification : {self.patients}")

        for index, path_patient in enumerate(self.patient_paths):
            patient_id = self.patients[index]
            print(
                f"Exporting {index + 1} ({patient_id}) on {len(self.patients)}"
            )

            nii_output = os.path.join(self.export_path, patient_id)
            missing, not_missing = self.find_structures(index)
            if len(missing) == 0 or self.force:

                dcmrtstruct2nii(self.rs_paths[index],
                                path_patient,
                                nii_output,
                                not_missing,
                                False,
                                mask_foreground_value=1)

                nii_maks = [
                    nii_mask for nii_mask in os.listdir(nii_output)
                    if nii_mask.startswith('mask')
                ]
                for nii in nii_maks:
                    name = os.path.splitext(nii)[0].split("_")[1].replace(
                        "-", " ")
                    os.rename(os.path.join(nii_output, nii),
                              os.path.join(nii_output, name + '.nii'))

                os.rename(os.path.join(nii_output, "image.nii"),
                          os.path.join(nii_output, "ct.nii"))
            else:
                print(f"Skip {patient_id} because of missing structure(s)")

        print("Export done")
def convertitoreRTstDCtoNII(PathDicom_RT,PathDicom_CT,output_path):
    return dcmrtstruct2nii(PathDicom_RT, PathDicom_CT, output_path,structures=None,gzip=False,mask_background_value=0, mask_foreground_value=1,convert_original_dicom=True)
Ejemplo n.º 8
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 14 09:13:56 2019

@author: leonardo
"""

from dcmrtstruct2nii import dcmrtstruct2nii

RT='/home/leonardo/Scrivania/paziente_prova/CSI+Boost/RTst_2011-09-29_075800_TomoTherapy.Patient.Disease_TomoTherapy.Structure.Set_n1__00000/1.2.826.0.1.3680043.2.200.868401404.495.96056.551.dcm'
PathDicom_DOSE='/home/leonardo/Scrivania/paziente_prova/CSI+Boost/RTDOSE_2011-09-29_075800_TomoTherapy.Patient.Disease_TomoTherapy.Planned.Dose_n1__00000'
output_path='/home/leonardo/Scrivania/paziente_prova/RT_2_nii_(DOSE)/'

dcmrtstruct2nii(RT,PathDicom_DOSE,output_path,structures=None,gzip=False,mask_background_value=0,mask_foreground_value=1,convert_original_dicom=True)