コード例 #1
0
ファイル: dicom_exporter.py プロジェクト: zoulianmp/mftm
    def set_magical_phantom_uids(self,dataset):
        import time
      
        dataset.InstanceCreatorUID = pydicom_root_UID + "1" 
        
        
        dataset.StudyInstanceUID =  generate_uid()
        time.sleep(0.156)

        dataset.SeriesInstanceUID = generate_uid()
        time.sleep(0.156)
        
        dataset.FrameofReferenceUID =  generate_uid()
コード例 #2
0
ファイル: dicom_exporter.py プロジェクト: zoulianmp/mftm
 def gen_general_study_module(self,dataset):
     """Generate the CT Image Storage General Study Module Attributes
     """
     # dataset.StudyInstanceUID = self.uid_root +'.' + '5'
     
     #from the Xio exported file
     
    
     # dataset.StudyInstanceUID =   generate_uid(self.borrow_uidroot)
     dataset.StudyInstanceUID =   generate_uid()
     
     from datetime import datetime
 
     tim = datetime.now()
     
     date = tim.strftime("%Y%m%d")
     time = tim.strftime("%H%M%S.%f")
  
     
     
     dataset.StudyDate = date
     #dataset.StudyTime = self.time + '.00'
     dataset.StudyTime = time 
     dataset.AccessionNumber = '3'
     
     
     
     
     full_study_id = '301' + date + '001'
     dataset.StudyID =  full_study_id
     
     dataset.ReferringPhysiciansName = 'MagicalPhantomSoftware'
     dataset.StudyDescription = "StudyGeneratedbyMagicalPhantom"
コード例 #3
0
def anonymize_all(folder):

    lista= os.listdir(folder) #Folders within gral. folder.
    anonfolder = folder+'anmzd'
    os.mkdir(anonfolder)
        #To get index of non dicom files
        
        #Adding needed tags and hiding institution name.    
    for z in lista:  #List of subfolders
        temp_var=folder+'/'+z
        for w in os.listdir(temp_var):
            an_var= temp_var+'/'+w
            data=dicom.read_file(an_var)
            os.remove(an_var)
            data.file_meta.MediaStorageSOPClassUID = '...'
            data.file_meta.MediaStorageSOPInstanceUID = generate_uid()
            data.InstitutionName='No location'
            data.save_as(an_var)
                    
        #Anonymize files and create NEW folder within the same direction
            
    for x in lista:
        tempdir=anonfolder+'/'+'anonymized-'+x
        os.makedirs(tempdir)
        tempfold=folder+'/'+x
        for y in os.listdir(tempfold):
            anonymize(tempfold+'/'+y, tempdir+'/'+'anon'+y)
                    
    print("All dicom files in this folder have been anonymized")
コード例 #4
0
ファイル: dicom_exporter.py プロジェクト: zoulianmp/mftm
 def gen_frame_of_reference_uid_module(self,dataset):
     """Generate the CT Image Storage frame_of_reference_uid Module Attributes
     """
     # dataset.FrameofReferenceUID = self.uid_root +'.' + '5'+'.' + '15'
     
     #from the Xio exported file
     dataset.FrameofReferenceUID =  generate_uid()
     #dataset.FrameofReferenceUID =  generate_uid(self.borrow_uidroot)
     
     dataset.PositionReferenceIndicator = ' '
コード例 #5
0
ファイル: test_UID.py プロジェクト: CrusherXRay/PyPiCOM
    def testGenerateUID(self):
        '''
        Test UID generator
        '''
        #Test standard UID generation with pydicom prefix
        uid = generate_uid()
        self.assertEqual(uid[:26], pydicom_root_UID)

        #Test standard UID generation with no prefix
        uid = generate_uid(None)
        self.assertEqual(uid[:5], '2.25.')

        #Test invalid UID truncation (trailing dot)
        invalid_prefix = \
            '1.2.33333333333333333333333333333333333333333333333333333333333.333.'
        self.assertRaises(InvalidUID,
             lambda: generate_uid(prefix=invalid_prefix, truncate=True))

        #Test standard UID with truncate=True
        prefix = '1.2.3.444444'
        uid = generate_uid(prefix=prefix, truncate=True)
        self.assertEqual(uid[:12], prefix)
コード例 #6
0
    def testGenerateUID(self):
        '''
        Test UID generator
        '''
        #Test standard UID generation with pydicom prefix
        uid = generate_uid()
        self.assertEqual(uid[:26], pydicom_root_UID)

        #Test standard UID generation with no prefix
        uid = generate_uid(None)
        self.assertEqual(uid[:5], '2.25.')

        #Test invalid UID truncation (trailing dot)
        invalid_prefix = \
            '1.2.33333333333333333333333333333333333333333333333333333333333.333.'
        self.assertRaises(
            InvalidUID,
            lambda: generate_uid(prefix=invalid_prefix, truncate=True))

        #Test standard UID with truncate=True
        prefix = '1.2.3.444444'
        uid = generate_uid(prefix=prefix, truncate=True)
        self.assertEqual(uid[:12], prefix)
コード例 #7
0
ファイル: dicom_exporter.py プロジェクト: zoulianmp/mftm
 def gen_general_series_module(self,dataset):
     """Generate the CT Image Storage General Series Module Attributes
     """
     dataset.Modality = 'CT'
     #dataset.SeriesInstanceUID =  self.uid_root +'.' + '5'+'.' + '1.8'
     
     #from the Xio exported file
     # dataset.SeriesInstanceUID = generate_uid(self.borrow_uidroot)
     dataset.SeriesInstanceUID = generate_uid()
    
     
     dataset.PatientPosition = 'HFS'
     dataset.SeriesDescription = 'VitualScanSeries'       
     dataset.SeriesNumber = ""
     dataset.OperatorsName = "MPhantom"
コード例 #8
0
def CSI_2_DCM(MRI_PATH, CSI_PATH, output):
    #args.MRI_PATH
    #args.CSI_PATH
    file = open(CSI_PATH, 'r')
    a = file.read()

    # Read image position patient

    IPP_loc = a.find('ImagePositionPatient')
    IPP = re.findall(r"[-+]?\d*\.\d+|\d+",
                     a[IPP_loc + 30:IPP_loc + 300])  # 30 was nessesary
    IPP = map(float, IPP)
    IPP = IPP[0:3]
    print('readed image position patient', IPP)
    #time.sleep(9999999)

    # Read image orientation patient
    IOP_string = 'ImageOrientationPatient'
    IOP_loc = a.find(IOP_string)
    IOP = re.findall(r"[-+]?\d*\.\d+|\d+", a[IOP_loc:IOP_loc + 300])
    IOP = map(float, IOP)
    IOP = IOP[0:3]
    print('readed image orientation patient', IOP)

    # Pixel spacing

    PS_loc = a.find('PixelSpacing')
    PS = re.findall(r"[-+]?\d*\.\d+|\d+", a[PS_loc:PS_loc + 300])
    PS = map(float, PS)
    PS = PS[0:3]
    print('readed Pixel spacing', PS)

    # read matrix size

    matrix_size_1_loc = a.find('sSpecPara.lFinalMatrixSizePhase')
    matrix_dim = re.findall(r"[-+]?\d*\.\d+|\d+",
                            a[matrix_size_1_loc:matrix_size_1_loc + 300])
    matrix_dim = map(float, matrix_dim)
    matrix_dim = matrix_dim[0:2]
    print('The matrix dimensions of the CSI image is:', matrix_dim)
    if matrix_dim[0] != matrix_dim[1]:
        print('warning matrix dimensions of CSI image does not agree')

    MheaderORG = dicom.read_file(MRI_PATH)
    CSIheaderORG = dicom.read_file(CSI_PATH)

    Mheader = copy.copy(MheaderORG)

    CSIheader = copy.copy(MheaderORG)
    # Find phase encoding direction

    phase_direction = MheaderORG.InplanePhaseEncodingDirection
    print('phase_direction', phase_direction)

    ############################
    if phase_direction == 'COL':
        FOV_loc2 = a.find('sSpecPara.sVoI.dPhaseFOV')  # 2
        FOV_loc1 = a.find('sSpecPara.sVoI.dReadoutFOV')  # 1
        print("Phase encoding direction is in column direction")
        print('FOV_loc2', FOV_loc2)
        print('FOV_loc1', FOV_loc1)
    else:
        ##################### changed to ::::
        FOV_loc1 = a.find('sSpecPara.sVoI.dPhaseFOV')  #1
        FOV_loc2 = a.find('sSpecPara.sVoI.dReadoutFOV')  # 1
        #################
        print('FOV_loc2', FOV_loc2)
        print('FOV_loc1', FOV_loc1)
        print("Phase encoding direction is in row direction")

    #############################

    # Localize FOV
    FOV_loc3 = a.find('sSpecPara.sVoI.dThickness')

    FOV1 = re.findall(r"[-+]?\d*\.\d+|\d+", a[FOV_loc1:FOV_loc1 + 300])
    FOV1 = map(float, FOV1)
    FOV1 = FOV1[0]
    FOV2 = re.findall(r"[-+]?\d*\.\d+|\d+", a[FOV_loc2:FOV_loc2 + 300])
    FOV2 = map(float, FOV2)
    FOV2 = FOV2[0]
    FOV3 = re.findall(r"[-+]?\d*\.\d+|\d+", a[FOV_loc3:FOV_loc3 + 300])
    FOV3 = map(float, FOV3)
    FOV3 = FOV3[0]

    ############################ # check if patient is feet first prone
    if MheaderORG.PatientPosition == 'FFP':
        FOV = [FOV2, FOV1, FOV3]
    else:
        ##################### most likely case
        FOV = [FOV1, FOV2, FOV3]

    #############################

    #FOV=[FOV1,FOV2,FOV3]

    print('The field of view in CSI is:', FOV)

    # Add files from Mheader

    fields = len(Mheader)
    for iterator in range(fields):
        keynum = Mheader.keys()[iterator]
        mystring = Mheader[keynum]
        try:
            CSIheaderORG[keynum]
        except KeyError:
            CSIheaderORG.add_new(mystring.tag, mystring.VR, mystring.value)

    # add specific pixel spacing and slice thickness
    PixelSpacing = map(truediv, FOV[0:2], matrix_dim)
    PixelSpacing = map(float, PixelSpacing)
    CSIheaderORG.PixelSpacing = PixelSpacing
    CSIheaderORG.SliceThickness = int(FOV3)
    CSIheaderORG.SeriesDescription = 'CSI_dicom'

    ##### CALCULATE patient coordinates
    R = np.zeros((4, 4))
    R[0:3, 0] = MheaderORG.ImageOrientationPatient[0:3]
    R[0:3, 1] = MheaderORG.ImageOrientationPatient[3:6]
    R[0:3, 2] = np.cross(MheaderORG.ImageOrientationPatient[0:3],
                         MheaderORG.ImageOrientationPatient[3:6])
    R[3, 3] = 1
    R2 = numpy.copy(R)

    #print('R',R,MheaderORG.ImageOrientationPatient)
    nCols = MheaderORG.Columns
    nRows = MheaderORG.Rows
    m = nRows * nCols
    i = np.matlib.repmat(np.array(range(0, nCols)), nRows, 1)
    a = np.expand_dims(np.transpose(np.array(range(0, nRows))), 1)
    #print('a',a,a.shape)
    j = np.matlib.repmat(a, 1, nCols)

    cent = np.array((i[nRows // 2, nCols // 2], j[nRows // 2,
                                                  nCols // 2], 0, 1))
    M = R
    M[0:3, 0] = R[0:3, 0] * MheaderORG.PixelSpacing[1]
    M[0:3, 1] = R[0:3, 1] * MheaderORG.PixelSpacing[0]
    M[0:3, 3] = np.transpose(MheaderORG.ImagePositionPatient)

    i_new = np.reshape(np.transpose(i), (1, m))
    #print('i_new',i_new.shape,i_new[0][509:514])
    #time.sleep(999999)
    j_new = np.reshape(np.transpose(j), (1, m))
    #print('j_new',j_new.shape,j_new[0][0:10])
    zeross = np.zeros((1, m))
    oness = np.ones((1, m))
    imageCoordinates = np.concatenate((i_new, j_new, zeross, oness), axis=0)
    patientCoordinates = np.matmul(M, imageCoordinates)

    # Estimate center of mass
    cent1 = np.matmul(M, cent)

    # Estimate IPP using the center

    i = np.matlib.repmat(np.array(range(0, int(matrix_dim[1]))),
                         int(matrix_dim[0]), 1)
    a = np.expand_dims(np.transpose(np.array(range(0, int(matrix_dim[0])))), 1)
    j = np.matlib.repmat(a, int(1), int(matrix_dim[1]))
    i2 = np.array(
        (i[int(matrix_dim[0]) // 2,
           int(matrix_dim[1]) // 2], j[int(matrix_dim[0]) / 2,
                                       int(matrix_dim[1]) // 2], 0, 1))

    x1 = cent1[0] - i2[0] * R2[0, 0] * FOV[0] / int(
        matrix_dim[0]) - R2[0, 1] * FOV[1] / int(matrix_dim[1]) * i2[1]
    x2 = cent1[1] - i2[0] * R2[1, 0] * FOV[0] / int(
        matrix_dim[0]) - R2[1, 1] * FOV[1] / int(matrix_dim[1]) * i2[1]
    x3 = cent1[2] - i2[0] * R2[2, 0] * FOV[0] / int(
        matrix_dim[0]) - R2[2, 1] * FOV[1] / int(matrix_dim[0]) * i2[1]

    IPP_cal = np.array((x1, x2, x3))
    result = np.allclose(IPP, IPP_cal)
    print('IPP', IPP_cal, IPP, cent1)
    #time.sleep(99999)
    if result is None:
        print(
            "########################################################################################"
        )
        print(
            "WARNING - No correspondence between calculated ImagePositioPatient and readed ImagePositionPaiten"
        )
        print(
            "########################################################################################"
        )

    elif result:
        print(
            "Correspondence calculated between ImagePositioPatient and readed ImagePositionPaitens"
        )
        #time.sleep(9999)
    else:
        print(
            "########################################################################################"
        )
        print(
            "WARNING - No correspondence between calculated ImagePositioPatient and readed ImagePositionPaiten"
        )
        print(
            "########################################################################################"
        )

    print('IPP', IPP, IPP_cal)
    IPP_cal = IPP_cal.tolist()
    CSIheaderORG.ImagePositionPatient = IPP

    #time.sleep(9999999)
    CSIheaderORG.Rows = int(matrix_dim[0])
    CSIheaderORG.Columns = int(matrix_dim[1])

    new_img = np.zeros(
        (int(matrix_dim[0]), int(matrix_dim[1]))).astype('uint16')
    print('create CSI dicom image with zeros')

    CSIheaderORG[0x0028, 0x0107].value = 4095
    CSIheaderORG[0x0028, 0x0106].value = 4095
    CSIheaderORG[0x0028, 0x0107].VR = 'US'
    CSIheaderORG[0x0028, 0x0106].VR = 'US'
    CSIheaderORG[0x7fe0, 0x0010].VR = 'OW'

    #print('Mheader',Mheader)
    #time.sleep(99999999)

    #  Generate UID

    n2 = 9

    UIDnr2 = CSIheaderORG[0x0020, 0x00e].value  #[0:30

    groups = UIDnr2.split('.')
    UID_gen_prefix = '.'.join(groups[:n2]) + '.'  #, '.'.join(groups[n:])

    uid_gen_series = generate_uid(prefix=UID_gen_prefix, truncate=True)
    print('Generated UID series:', uid_gen_series)
    CSIheaderORG[0x0020, 0x00e].value = uid_gen_series
    CSIheaderORG[0x008, 0x060].value = 'MR'
    CSIheaderORG[0x008, 0x103e].value = 'CSI metabolite image'

    print('CSI header ORG', CSIheaderORG.ImagePositionPatient)
    print('IPP', IPP)

    def write_dicom(ds, pixel_array, filename):
        """
        INPUTS:
        pixel_array: 2D numpy ndarray.  If pixel_array is larger than 2D, errors.
        filename: string name for the output file.
        Image array are stored as uint16
        """

        ## These are the necessary imaging components of the FileDataset object.
        ds.SamplesPerPixel = 1
        ds.PhotometricInterpretation = "MONOCHROME2"
        ds.PixelRepresentation = 0
        ds.HighBit = 15  #63
        ds.BitsStored = 16  #64
        ds.BitsAllocated = 16  #64
        #ds.SmallestImagePixelValue = '\\x00\\x00'
        #ds.LargestImagePixelValue = '\\xff\\xff'
        ds.Columns = pixel_array.shape[0]
        ds.Rows = pixel_array.shape[1]
        if pixel_array.dtype != np.uint16:
            pixel_array = pixel_array.astype(np.uint16)

    #    if pixel_array.dtype != np.float64:
    #        pixel_array = pixel_array.astype(np.float64)
        ds.PixelData = pixel_array.tostring()

        ds.save_as(filename)
        return
    write_dicom(CSIheaderORG, new_img, output)
    #CSIheader.save_as(args.outputFolder+args.output)

    print("CSI header saved as", output)
コード例 #9
0
ファイル: dicom_exporter.py プロジェクト: zoulianmp/mftm
 def  _sop_instance_uid_root_default(self):
     return   generate_uid()      
コード例 #10
0
def generate_dic(PETraw_path, csi_dicom_path, pet_dicom):

    #parser = ArgumentParser(description="ikjMatrix multiplication")
    #parser.add_argument("-ResampledPETrawpath", dest="PETraw_path", required=True,
    #    help="Resampled raw PET image", metavar="FILE")
    #parser.add_argument("-CSIdicom_path", dest="dicom_path", required=True,
    #    help="Pseudo dicom csi image", metavar="FILE")
    #parser.add_argument("-PETdicom", dest="PETdcm", required=True,
    #    help="pseudo valid dicom PET image", metavar="FILE")

    #args = parser.parse_args()

    output = pet_dicom

    new_img = np.fromfile(PETraw_path, dtype='float64', sep="")
    new_img = new_img.reshape(
        [int(np.sqrt(len(new_img))),
         int(np.sqrt(len(new_img)))])

    ds = dicom.read_file(csi_dicom_path)
    ds.pixel_array = new_img
    ds.PixelData = new_img.tostring()
    UIDnr = ds[0x0020, 0x00d].value  #[0:30]
    #
    temp = ds[0x028, 0x030].value
    temp2 = [temp[1], temp[0]]
    ds[0x028, 0x030].value = temp2

    n = 8
    groups = UIDnr.split('.')
    UID_gen_prefix = '.'.join(groups[:n]) + '.'  #, '.'.join(groups[n:])

    uid_gen_Study = generate_uid(prefix=UID_gen_prefix, truncate=True)

    print('Generated UID studt:', uid_gen_Study)

    n2 = 9

    UIDnr2 = ds[0x0020, 0x00e].value  #[0:30

    groups = UIDnr2.split('.')
    UID_gen_prefix = '.'.join(groups[:n2]) + '.'  #, '.'.join(groups[n:])

    uid_gen_series = generate_uid(prefix=UID_gen_prefix, truncate=True)
    print('Generated UID series:', uid_gen_series)
    ds[0x0020, 0x00e].value = uid_gen_series
    ds[0x008, 0x060].value = 'PT'
    ds[0x008, 0x103e].value = 'PET resampled in CSI space'

    def write_dicom(ds, pixel_array, filename):
        """
        INPUTS:
        pixel_array: 2D numpy ndarray.  If pixel_array is larger than 2D, errors.
        filename: string name for the output file.
        Image array are stored as uint16
        """

        ## These are the necessary imaging components of the FileDataset object.
        ds.SamplesPerPixel = 1
        ds.PhotometricInterpretation = "MONOCHROME2"
        ds.PixelRepresentation = 0
        ds.HighBit = 15  #63
        ds.BitsStored = 16  #64
        ds.BitsAllocated = 16  #64
        #ds.SmallestImagePixelValue = '\\x00\\x00'
        #ds.LargestImagePixelValue = '\\xff\\xff'
        ds.Columns = pixel_array.shape[0]
        ds.Rows = pixel_array.shape[1]
        if pixel_array.dtype != np.uint16:
            pixel_array = pixel_array.astype(np.uint16)

    #    if pixel_array.dtype != np.float64:
    #        pixel_array = pixel_array.astype(np.float64)
        ds.PixelData = pixel_array.tostring()

        ds.save_as(filename)
        return

    write_dicom(ds, new_img, output)