示例#1
0
    def __init__(self, path, *, dtype=None, dpi=None, sid=None):
        """
        Parameters
        ----------
        path : str, file-object
            The path to the file or the data stream.
        dtype : dtype, None, optional
        The data type to cast the image data as. If None, will use whatever raw image format is.
            dpi : int, float
        The dots-per-inch of the image, defined at isocenter.

            .. note:: If a DPI tag is found in the image, that value will override the parameter, otherwise this one
                will be used.
        sid : int, float
            The Source-to-Image distance in mm.
        """
        super().__init__(path)
        self._sid = sid
        self._dpi = dpi
        # read the file once to get just the DICOM metadata
        self.metadata = dicom.read_file(path, force=True)
        self._original_dtype = self.metadata.pixel_array.dtype
        # read a second time to get pixel data
        if isinstance(path, BytesIO):
            path.seek(0)
        ds = dicom.read_file(path, force=True)
        if dtype is not None:
            self.array = ds.pixel_array.astype(dtype)
        else:
            self.array = ds.pixel_array
        # convert values to proper HU: real_values = slope * raw + intercept
        if self.metadata.SOPClassUID.name == 'CT Image Storage':
            self.array = int(self.metadata.RescaleSlope)*self.array + int(self.metadata.RescaleIntercept)
示例#2
0
def main():
    dcm = dicom.read_file(sys.argv[1])
    img=dcm.pixel_array
    sg = SkeletonGraph(img)
    arg2 = dicom.read_file(sys.argv[2])
    img2 = arg2.pixel_array
    sg.setOriginalImage(img2)
#sg.setOriginalImage(fname=sys.argv[2])
    sg.getGraphsFromSkeleton(verbose=False)
    sg.setLargestGraphToCurrentGraph()
    list(sg.graphs.keys())
    sg.findEndpointsBifurcations()
    root = sg.selectSeedFromDFE()
#sg.viewGraph()
#raw_input('continue')
    sg.setRoot(root,key="test")
    sg.traceEndpoints(key='test')
    ogkey = sg.getLargestOrderedGraphKey()
    sg.deleteDegree2Nodes(ogkey)
    sg.prunePaths(ogkey)
    sg.deleteDegree2Nodes(ogkey)
    sg.fitEdges(key=ogkey)
    og = sg.orderedGraphs[ogkey]
    sg.viewGraph(og)
    sg.saveGraphs(sys.argv[3])
示例#3
0
def getDicomInfo(directory):
    '''
    Input : directory location
    Output : dicom information
    '''

    #Looping through the input directory
    switch='non-break'
    firstDicomFile=''

    for root, dirs, files in os.walk(directory):

        #Looping through the bunch of files
        for singleFile in files:

            #if there is dicom files
            if re.search('.*ima|.*dcm|\d{8}',singleFile,flags=re.IGNORECASE):
                try:
                    firstDicomFile = dicom.read_file(os.path.join(root,singleFile))
                except:
                    firstDicomFile = dicom.read_file(os.path.join(root,singleFile),force=True)

                #make a switch to turn off the later loops
                switch='break'

                #turn the file loop off
                break
            else:
                switch='non-break'

        #if switch is on, turn the dir loop off
        if switch=='break':
            break
    return firstDicomFile
def get_blur(df_s, path):
    df_s = remove_weird_slice(df_s)
    Dset = []
    for idx in range(len(df_s)):  
        #Get brightest and darkest frames for study number idx
        #idx = 0
        ext = df_s.index[idx]
        #print ext
        BT = np.argmax(df_s['brightness'][idx])
        DK = np.argmin(df_s['brightness'][idx])
        filename1 = os.listdir(path + '/' + ext)[BT]
        filename2 = os.listdir(path + '/' + ext)[DK]

        dcm1 = path + '/' + ext+ '/' + filename1
        dcm2 = path + '/' + ext+ '/' + filename2

        ds1 = dicom.read_file(dcm1)
        ds2 = dicom.read_file(dcm2)

        data1 = ds1.pixel_array
        data2 = ds2.pixel_array
        # plt.imshow(data1, cmap=plt.cm.bone)
        # plt.show()
        # plt.imshow(data2, cmap=plt.cm.bone)
        # plt.show()
        datab1 = cv2.blur(data1,(7,7))
        datab2 = cv2.blur(data2,(7,7))
        #D is delta between brightest and darkest image for a slice
        D = abs(datab2.astype(int) - datab1.astype(int))
        Dset.append(D)
        #plt.imshow(D, cmap=plt.cm.bone)
        #plt.show()

    #Average deltas for all slices gives region of movement
    return np.mean(np.array(Dset), axis = 0)
 def times(self):
     """
     Determines the time of each series. 'time' is a string.
     """
     types=self.type
     process=self.processed
 
     os.chdir(data_loc)    
     
     if process:
         time='Processed'
     else:
         if types=='T1 Dynamic':
             original=dicom.read_file(self.filename)
             time1=original.ContentTime
             time2=original.ContentTime
             #still has to go through entire hard drive
             files=os.listdir(data_loc)
             for i in files:
                 data=dicom.read_file(i)
                 if data.SeriesInstanceUID==original.SeriesInstanceUID:
                     if data.ContentTime<time1:
                         time1=data.ContentTime
                     elif data.ContentTime>time2:
                         time2=data.ContentTime
                     else:
                         pass
                 else:
                     pass
             time=str(time1)+'-'+str(time2)
         else:
             time=None
     self.time=time
     return       
示例#6
0
文件: load.py 项目: kleinfeld/medpy
def __load_pydicom(image):
    """
    Image loader using the third-party module pydicom.
    @param image the image to load
    @return A tuple of 1. a scipy array with the image data, 2. a ImageHeader object with additional information
    """
    import dicom
    
    logger = Logger.getInstance()
    logger.debug('Loading image {} with PyDicom...'.format(image))
    
    try:
        img = dicom.read_file(image)
    except dicom.filereader.InvalidDicomError as e:
        logger.debug('Module pydicom signaled error: {}. Attempting to force loading nevertheless'.format(e))
        img = dicom.read_file(image, force=True)
    arr = img.pixel_array
    
    # Dicom images are difficult and require special treatment:
    # (1) Usually, when saved as DICOM image, row and solumn direction as exchanged as
    #     compared to other image modailites.
    # (2) Furthermore PyDicom loads DICOM images with the 3rd dimension (Frames/Slices)
    #     in the first numpy ndarray position.
    # Thus, to ensure consistency between the loaded data independent of the 3rd party
    # tool or image format used, we have to
    # (a) transpose the data array, which counters both, point (1) and point (2) in one go
    # (b) flip the first and second (column and row) element of the pixel spacing
    # Note: Strangely the offset i.e. PatientPosition does not have do be flipped... why?  
    pixel_spacing = scipy.asarray(header.get_pixel_spacing(img))
    tmp = float(pixel_spacing[1])
    pixel_spacing[1] = pixel_spacing[0]
    pixel_spacing[0] = tmp
    header.set_pixel_spacing(img, pixel_spacing)
    
    return scipy.transpose(arr), img
示例#7
0
    def __init__(self, **kwargs):
        med2image.__init__(self, **kwargs)

        self.l_dcmFileNames = sorted(glob.glob('%s/*.dcm' % self._str_inputDir))
        self.slices         = len(self.l_dcmFileNames)

        if self._b_convertMiddleSlice:
            self._sliceToConvert = int(self.slices/2)
            self._dcm            = dicom.read_file(self.l_dcmFileNames[self._sliceToConvert])
            self._str_inputFile  = self.l_dcmFileNames[self._sliceToConvert]
            str_outputFile       = self.l_dcmFileNames[self._sliceToConvert]
            if not self._str_outputFileStem.startswith('%'):
                self._str_outputFileStem, ext = os.path.splitext(self.l_dcmFileNames[self._sliceToConvert])
        if not self._b_convertMiddleSlice and self._sliceToConvert != -1:
            self._dcm = dicom.read_file(self.l_dcmFileNames[self._sliceToConvert])
        else:
            self._dcm = dicom.read_file(self._str_inputFile)
        if self._sliceToConvert == -1:
            self._b_3D = True
            self._dcm = dicom.read_file(self._str_inputFile)
            image = self._dcm.pixel_array
            shape2D = image.shape
            #print(shape2D)
            self._Vnp_3DVol = np.empty( (shape2D[0], shape2D[1], self.slices) )
            i = 0
            for img in self.l_dcmFileNames:
                self._dcm = dicom.read_file(img)
                image = self._dcm.pixel_array
                #print('%s: %s\n' % (img, image.shape))
                try:
                    self._Vnp_3DVol[:,:,i] = image
                except Exception, e:
                    error.fatal(self, 'dcmInsertionFail', '\nFor input DICOM file %s\n%s\n' % (img, str(e)))
                i += 1
示例#8
0
def getDicomInfoAuto(firstDicomAddress):
    
    try:
        df = dicom.read_file(firstDicomAddress)
        dob =  df.PatientBirthDate
        sex = df.PatientSex
        pID = df.PatientID
        date = df.StudyDate
        age,dob,date=calculate_age(dob,date) 
        name = df.PatientName
        
        print name
        print dob
        print sex
        print pID
        print date
        print age 
        
        return {'name':name,
                'dob':dob,
                'sex':sex,
                'patientId':pID,
                'scanDate':date,
                'age':age,
                'dicomRead':df}
    
    except:
        dicom.read_file(firstDicomAddress,force=True)
        print 'cannot properly read dicom file'
示例#9
0
	def get_images(self):
		#Read images in from the same folder
		imfilenames=glob.glob(os.path.join(self.contourdirectory,'*MR*'))
		IPP=[dicom.read_file(x).ImagePositionPatient for x in imfilenames]
		IPPz=[f[2] for f in IPP]
		together=zip(IPPz,imfilenames,IPP)
		together=sorted(together)
		sortedimfilenames=[y[1] for y in together]
		sortedUIDfromimfilenames=[x.split('MR.')[1] for x in sortedimfilenames]

		sortedIPP=[z[2] for z in together]
		sortedIPPz=[p[0] for p in together]

		#Read in the files in the proper order
		#Read in first one to get information needed
		info=dicom.read_file(sortedimfilenames[0])
		cols=info.Columns
		rows=info.Rows
		PS=info.PixelSpacing
		im=info.pixel_array

		images=np.zeros(np.array([im.shape[0],im.shape[1],len(sortedimfilenames)]))
		
		for i in range(0,len(sortedimfilenames)):
			temp=dicom.read_file(sortedimfilenames[i])
			images[:,:,i]=temp.pixel_array
		
		self.images=images
		self.sortedIPP=sortedIPP
		self.sortedUIDfromimfilenames=sortedUIDfromimfilenames
		self.rows=rows
		self.cols=cols
		self.PS=PS
示例#10
0
    def _read_all_dicom_images(self):
        f1 = self._filename(self.slices[0], self.time[0])
        d1 = dicom.read_file(f1)
        (x, y) = d1.PixelSpacing
        (x, y) = (float(x), float(y))
        if len(self.slices)>1:
          f2 = self._filename(self.slices[1], self.time[0])

          d2 = dicom.read_file(f2)
        # try a couple of things to measure distance between slices
        try:
            if len(self.slices)>1:
              dist = np.abs(d2.SliceLocation - d1.SliceLocation)
            else:
              dist = d1.SliceThickness
        
        except AttributeError:
            try:
                dist = d1.SliceThickness
            except AttributeError:
                dist = 8  # better than nothing...

        self.images = np.array([[self._read_dicom_image(self._filename(d, i))
                                 for i in self.time]
                                for d in self.slices])
        self.dist = dist
        self.area_multiplier = x * y
示例#11
0
	def read_structural(self,seriestag): #method to read image stack - read in by file name due to poor dicom conversion
		# Find folder that matches seriestag
		stackfolder=glob.glob(os.path.join(self.datadirect,seriestag))
		if not stackfolder:
			print('Folder not found')
			return
		print('Found ', stackfolder[0])

		# find .dcm files
		filenames=glob.glob(os.path.join(stackfolder[0],'*.dcm'))
		print('Check file ordering: ')
		for item in filenames:
			print(os.path.split(item)[1])
		
		numfiles=len(filenames)
		print("Reading "+str(numfiles)+" files")
		
		# read the first file to find out size, and add pixel size info to T2winfo structure
		info=dicom.read_file(filenames[0])
		self.structuralinfo=np.zeros(1,dtype=[('pixelsize','f8')])
		self.structuralinfo['pixelsize']=float(info.PixelSpacing[0])
		im=info.pixel_array

		ims=np.zeros(np.array([im.shape[0],im.shape[1],numfiles]))
		for i in range(0,numfiles):
			temp=dicom.read_file(filenames[i])
			ims[:,:,i]=np.flipud(temp.pixel_array)
		self.structural=ims
示例#12
0
    def __init__(self, paths,typeFloat):
        ''' Initialization
        '''
        self._dicomReaders = []
        self._typeFloat = typeFloat
        for path in paths:
            if os.path.isdir(path):
                for infile in glob.glob( os.path.join(path, '*.dcm') ):
                    dicomFile = dicom.read_file(infile)
                    dcmFileType = str(dicomFile.SOPClassUID)
                    if dcmFileType == 'CT Image Storage':
                        reader = DicomCTReader(path,typeFloat)
                        break
                    else:
                        raise ValueError("Directory: Case not defined yet in dicom reader")
            else:
                dicomFile = dicom.read_file(path)
                dcmFileType = str(dicomFile.SOPClassUID)
                if dcmFileType == 'RT Dose Storage':
                    reader = DicomRDReader(path,typeFloat)
                elif dcmFileType == 'RT Ion Plan Storage':
                    reader = DicomRPReader(path,typeFloat)
                elif dcmFileType == 'RT Structure Set Storage':
                    reader = DicomRSReader(path,typeFloat)
                else:
                    reader = DicomGeneralReader(path,typeFloat)
                    

            self._dicomReaders.append(reader)
        self._fullPlan = self.checkFullRTPlan()
        print "Full RT Plan (CT, RP, RD, RS): %s"%str(self._fullPlan)
        self._sameFrameOfRefUID = self.checkFrameOfReferenceUID()
        print "Same Frame Of Reference UID: %s"%str(self._sameFrameOfRefUID)
        self._sameStudyInstanceUID = self.checkSameStudyInstanceUID()
        print "Same Study Instance UID: %s"%str(self._sameStudyInstanceUID)
示例#13
0
    def _read_all_dicom_images(self):

        #Computing distance between...
        f1 = self._filename(self.slices[0], self.time[0])
        d1 = dicom.read_file(f1)
        (x, y) = d1.PixelSpacing
        (x, y) = (float(x), float(y))
        f2 = self._filename(self.slices[1], self.time[0])
        d2 = dicom.read_file(f2)

        # try a couple of things to measure distance between slices
        try:
            dist = np.abs(d2.SliceLocation - d1.SliceLocation)
        except AttributeError:
            try:
                dist = d1.SliceThickness
            except AttributeError:
                dist = 8  # better than nothing...

        self.images = np.array([[self._read_dicom_image(self._filename(d, i))
                                 for i in self.time]
                                for d in self.slices])
        # sets dist equal to the two first slices distance (subtracting first
        # from second) or equal to first slice's thickness. I THINK the second
        # logic is better
        #
        # maybe set dist = d1.SliceThickness
        self.dist = dist
        self.area_multiplier = x * y
示例#14
0
    def find_files(self, base_dir):
        '''
        When we run the deident software we won't know the name of the 
        directory the image gets put into; however it will (should!) be 
        the only subdirectory present in the specified output directory, 
        and we just need to get its name
        '''
        # Find the directories that the de-ident software created
        dirnames = os.listdir(base_dir)

        # Now find the dicom files inside each directory
        dicom_files = []
        for directory in dirnames:
            files = os.listdir(os.path.join(base_dir, directory))

            # now see which are dicom images
            for f in files:
                try:
                    file_path = os.path.join(base_dir, directory, f)
                    dicom.read_file(os.path.join(file_path))
                    dicom_files.append(file_path)
                except Exception as msg:
                    sys.stdout.write("Warning: Found invalid DICOM file: %s\n"
                        % os.path.join(base_dir, directory, f))

            if len(dicom_files) == 0:
                sys.stdout.write("ERROR: No Dicom images found at: %s\n"
                    % os.path.join(base_dir, directory))
                return 0

        return dicom_files
示例#15
0
def ReadDicom(dicom_dir='dicom', points_threshold=1100):
    # Get the dicom file list.
    files = sorted(glob.glob(os.path.join(dicom_dir, 'CT*')))

    # Get CT meta data.
    data = dicom.read_file(files[0])
    dims = (int(data.Rows), int(data.Columns), len(files))
    # spacing is in mm.
    spaces = (float(data.PixelSpacing[0]), float(data.PixelSpacing[1]), float(data.SliceThickness))

    # Allocate spaces, loop through all the DICOM files
    v = np.zeros(dims, dtype=data.pixel_array.dtype)
    for f in files:
        data = dicom.read_file(f)
        v[:, :, files.index(f)] = data.pixel_array  

    # Get 3 dimension data. Use t as the filter.
    t = v >= points_threshold
    a = t.nonzero()
    v = v[t]
    v = v.reshape(len(a[0]))
    data = np.array([a[0] * spaces[0], a[1] * spaces[1], a[2] * spaces[2], v])

    # Return a ? * 4 matrix
    data = data.transpose()
    return data
示例#16
0
文件: util.py 项目: sssruhan1/spine
def read_dicom(path):
    import re
    files = []
    arr = None
    for dirName, subdirList, fileList in os.walk(path):
        for filename in fileList:
            m = re.search(r'IM\d+', filename)
            if m <> None:
                if filename[m.end(): ] == '':
                    files.append(os.path.join(dirName, filename))
    
    if len(files) != 0:
        reference = dicom.read_file(files[0])
        height = int(reference.Rows)
        width = int(reference.Columns)
        slice_num = int(len(files))
        spacing = (float(reference.PixelSpacing[0]),float(reference.PixelSpacing[1]), float(reference.SliceThickness))
#        x = np.arange(0.0, (height*spacing[0], spacing[0]))
#        y = np.arange(0.0, (width * spacing[1], spacing[1]))
#        z = np.arange(0.0, (slice_num * spacing[2]), spacing[2])
    
        arr = np.zeros((slice_num, height, width), dtype=np.int16)
        for filename in files:
            ds = dicom.read_file(filename)
            arr[files.index(filename), :, : ] = ds.pixel_array
    
    else:
        import sys
        sys.stderr.write("didn't find any images")
    return arr
示例#17
0
def is_dicom_dir(datapath):
    """
    Check if in dir is one or more dicom file. We use two methods.
    First is based on dcm extension detection.
    """
    # Second tries open files
    # with dicom module.

    retval = False
    for f in os.listdir(datapath):
        if f.endswith((".dcm", ".DCM")):
            retval = True
            return True
# @todo not working and I dont know why
        try:
            dicom.read_file(f)

            retval = True
        except:
            import traceback
            traceback.print_exc
            pass

        if retval:
            return True
            print f
    return False
示例#18
0
def genepara(namedirtopcf):
    dirFileP = os.path.join(namedirtopcf, source)
    listsln=[]
        #list dcm files
    fileList =[name for name in  os.listdir(dirFileP) if ".dcm" in name.lower()]
    slnt=0
    for filename in fileList:
        FilesDCM =(os.path.join(dirFileP,filename))
        RefDs = dicom.read_file(FilesDCM,force=True)
        scanNumber=int(RefDs.InstanceNumber)
        if scanNumber>slnt:
            slnt=scanNumber
        listsln.append(scanNumber)

    FilesDCM =(os.path.join(dirFileP,fileList[0]))
    FilesDCM1 =(os.path.join(dirFileP,fileList[1]))
    RefDs = dicom.read_file(FilesDCM,force=True)
    RefDs1 = dicom.read_file(FilesDCM1,force=True)
    patientPosition=RefDs.PatientPosition
#    SliceThickness=RefDs.SliceThickness
    try:
            slicepitch = np.abs(RefDs.ImagePositionPatient[2] - RefDs1.ImagePositionPatient[2])
    except:
            slicepitch = np.abs(RefDs.SliceLocation - RefDs1.SliceLocation)

    
    SliceThickness=RefDs.SliceThickness
    try:
            SliceSpacingB=RefDs.SpacingBetweenSlices
    except AttributeError:
             print "Oops! No Slice spacing..."
             SliceSpacingB=0
    print 'number of slices', slnt
    print 'slice Thickness :',SliceThickness
    print 'Slice spacing',SliceSpacingB
    print 'slice pitch in z :',slicepitch
    print 'patient position :',patientPosition
    errorfile = open(eferror, 'a')
    errorfile.write('---------------\n')

    errorfile.write('number of slices :'+str(slnt)+'\n')
    errorfile.write('slice Thickness :'+str(SliceThickness)+'\n')
    errorfile.write('slice spacing :'+str(SliceSpacingB)+'\n')
    errorfile.write('slice pitch in z :'+str(slicepitch)+'\n')
    errorfile.write('patient position  :'+str(patientPosition)+'\n')

    slnt=slnt+1
    fxs=float(RefDs.PixelSpacing[0])/avgPixelSpacing
    dsr= RefDs.pixel_array
    dsr= dsr-dsr.min()
    dsr=dsr.astype('uint16')
    errorfile.write('patient shape  :'+str(dsr.shape[0])+'\n')
    errorfile.write('--------------------------------\n')
    errorfile.close()  
#    dsrresize = scipy.ndimage.interpolation.zoom(dsr, fxs, mode='nearest')
#    dsrresize=cv2.resize(dsr,None,fx=fxs,fy=fxs,interpolation=cv2.INTER_CUBIC)
    dimtabx=dimtabxref
    dimtaby=dimtabxref
    return dimtabx,dimtaby,slnt,fxs,listsln
 def isValidDcmFile(self, fileName):
     valid = False;
     try:
         dicom.read_file(fileName)
         valid = True;
     except:
         valid = False;
     return valid;
def main():
    print("Creating data iterator...")
    with open("config.yml", 'r') as ymlfile:
        cfg = yaml.load(ymlfile)
    train_dir = cfg['dataset_paths']['train_data']
    train_labels = cfg['dataset_paths']['train_labels']

    mri_iter = MRIDataIterator(train_dir, train_labels)
    outputdir = './testpreproc/'
    for patient_index, patient_slices in mri_iter.frames.iteritems():
        slices_locations_to_names = {}
        i = 0
        for sax_set in patient_slices:
            slices_locations_to_names[int(dicom.read_file(sax_set[0]).SliceLocation)] = i
            i += 1
        median_array = slices_locations_to_names.keys()
        median_array.sort()
        values_closest_to_middle = []
        if len(median_array) > 1:
            middle_value = (median_array[-1] + median_array[0])/2
            for val in median_array:
                if math.sqrt((val - middle_value)**2) < 25:
                    values_closest_to_middle.append(val)
        else:
             middle_value = median_array[0]
             values_closest_to_middle.append(median_array[0])

        z = 0
        values = []
        for proposed_median_value in values_closest_to_middle:
            median_index = slices_locations_to_names[proposed_median_value]
            sax_set = patient_slices[median_index]
            time_series = []
            for path in sax_set:
                f = dicom.read_file(path)
                gender = f.PatientsSex
                age = convert_age(f.PatientsAge)
                img = mri_iter.preproc(f.pixel_array.astype(np.float32) / np.max(f.pixel_array), 64, f.PixelSpacing, True, False)
                time_series.append(img)
            values.append(time_series)
            z +=1
        data_array = np.array(values)
        rois,circles = calc_rois(data_array)
        i = 0
        import pdb; pdb.set_trace()
        new_set = []
        for sax_set in data_array:
            center_point, radius = circles[i]
            new_time_series = []
            for img in sax_set:
                # make it square
                crop_img = img[center_point[0]-40:center_point[0]+40, center_point[1]-60:center_point[1]+20]
                new_time_series.append(crop_img)
            new_set.append(new_time_series)
                
        new_data_array = np.array(new_set)
        im = Image.fromarray(new_data_array[0][0]).convert('RGB')
        im.save('examples/' + randword() +'.png')
示例#21
0
def convert_nifti_2_dicoms(nifti_path, dicom_targets, dicom_source,
                           output_folder, label=None):
    """Convert 4D niftis generated by reg_f3d into DICOM files.

    :param nifti_path: path to the nifti file
    :param dicom_target: list of dicom files from the target
     for the registration for header info
    :param dicom_source: one dicom file from the source
     for the registration for header info
    :param output_folder: folder where the DICOM files will be saved
    :param label: name for the output dicom files
    :return: None
    """
    if not os.path.isfile(nifti_path):
        raise Exception("NIFTI File %s not found." % nifti_path)
    # Load image from NIFTI
    f_img = nib.load(nifti_path)
    f_img_data = f_img.get_data()

    # Load dicom headers
    if not os.path.isfile(dicom_source):
        raise Exception("DICOM File %s not found ." % dicom_source)
    adc_dcm_obj = dicom.read_file(dicom_source)

    # Make output_folder:
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # Series Number and SOP UID
    ti = time.time()
    series_number = 86532 + int(str(ti)[2:4]) + int(str(ti)[4:6])
    sop_id = adc_dcm_obj.SOPInstanceUID.split('.')
    sop_id = '.'.join(sop_id[:-1])+'.'

    # Sort the DICOM T2 to create the ADC registered DICOMs
    dcm_obj_sorted = dict()
    for dcm_file in dicom_targets:
        # Load dicom headers
        if not os.path.isfile(dcm_file):
            raise Exception("DICOM File %s not found." % dcm_file)
        t2_dcm_obj = dicom.read_file(dcm_file)
        dcm_obj_sorted[t2_dcm_obj.InstanceNumber] = t2_dcm_obj

    for vol_i in range(f_img_data.shape[2]):
        if f_img_data.shape[2] > 100:
            filename = os.path.join(output_folder, '%s_%03d.dcm' % (label,
                                                                    vol_i+1))
        elif f_img_data.shape[2] > 10:
            filename = os.path.join(output_folder, '%s_%02d.dcm' % (label,
                                                                    vol_i+1))

        else:
            filename = os.path.join(output_folder, '%s_%d.dcm' % (label,
                                                                  vol_i+1))

        write_dicom(np.rot90(f_img_data[:, :, vol_i]), filename,
                    dcm_obj_sorted[vol_i+1], adc_dcm_obj, vol_i,
                    series_number, sop_id)
示例#22
0
def genebmp(dirName,fn,subs):
    """generate patches from dicom files"""
#    print ('load dicom files in :',dirName, 'scan name:',fn)
    #directory for patches
    
    predictout_f_dir = os.path.join( dirName,picklefile)
    remove_folder(predictout_f_dir)
    os.mkdir(predictout_f_dir)
#    print 'predictoutdir', predictout_f_dir
    subfile=os.path.join(predictout_f_dir,subsamplef)
    subfilec = open(subfile, 'w')
    subfilec.write('subsample '+str(subs)+'\n' )
    subfilec.close()
    bmp_dir = os.path.join(dirName, scanbmp)

    FilesDCM =(os.path.join(dirName,fn))  
#           
    ds = dicom.read_file(FilesDCM)
    endnumslice=fn.find('.dcm')
    imgcore=fn[0:endnumslice]+'.'+typei
   
    posend=endnumslice
    while fn.find('-',posend)==-1:
        posend-=1
    debnumslice=posend+1
    slicenumber=int(fn[debnumslice:endnumslice])

    bmpfile=os.path.join(bmp_dir,imgcore)
    scipy.misc.imsave(bmpfile, ds.pixel_array)

    lung_dir = os.path.join(dirName, lungmask)
    
    lung_bmp_dir = os.path.join(lung_dir,lungmaskbmp)
    lunglist = os.listdir(lung_dir)
    #             print(lung_bmp_dir)
#    lungFound=False
    for lungfile in lunglist:
    #                print(lungfile)
                    if ".dcm" in lungfile.lower():
                        endnumslice=lungfile.find('.dcm')
                        imgcorescan=lungfile[0:endnumslice]+'.'+typei  
                        posend=endnumslice
                        while lungfile.find('_',posend)==-1:
                            posend-=1
                        debnumslice=posend+1
                        slicescan=int(lungfile[debnumslice:endnumslice])
#                        print slicescan
                        if slicescan== slicenumber:

        # check whether the file's DICOM
                            lungDCM =os.path.join(lung_dir,lungfile)  
                            dslung = dicom.read_file(lungDCM)
                           
                            lungcore=imgcorescan+'.'+typei
                            lungcoref=os.path.join(lung_bmp_dir,lungcore)
                            scipy.misc.imsave(lungcoref, dslung.pixel_array)
                            break
示例#23
0
 def load_dicoms(self):
     if os.path.isfile(self.filepath) and tarfile.is_tarfile(self.filepath):     # compressed tarball
         with tarfile.open(self.filepath) as archive:
             self.dcm_list = [dicom.read_file(cStringIO.StringIO(archive.extractfile(ti).read())) for ti in archive if ti.isreg()]
     elif os.path.isfile(self.filepath):                                         # single file
         self.dcm_list = [dicom.read_file(self.filepath)]
     else:                                                                       # directory of dicoms
         self.dcm_list = [dicom.read_file(os.path.join(self.filepath, f)) for f in os.listdir(self.filepath)]
     self.dcm_list.sort(key=lambda dcm: dcm.InstanceNumber)
示例#24
0
	def read_MOLLI(self,seriestag,PreOrPost): #Method to read in single slice MOLLI images, by filename due to poor dicom conversion
		#Look for MOLLIpre and MOLLIpost.npy in the Analysis folder first
		if PreOrPost=='Pre' and os.path.isfile(os.path.join(os.path.split(self.datadirect)[0],'Analysis','MOLLIpre.npy')):
			print('reading from saved array')
			self.MOLLIpre=np.load(os.path.join(os.path.split(self.datadirect)[0],'Analysis','MOLLIpre.npy'))
			#self.dyninfo=np.load(os.path.join(os.path.split(self.datadirect)[0],'Analysis','dyninfo.npy'))
			return

		if PreOrPost=='Post' and os.path.isfile(os.path.join(os.path.split(self.datadirect)[0],'Analysis','MOLLIpost.npy')):
			print('reading from saved array')
			self.MOLLIpost=np.load(os.path.join(os.path.split(self.datadirect)[0],'Analysis','MOLLIpost.npy'))
			#self.dyninfo=np.load(os.path.join(os.path.split(self.datadirect)[0],'Analysis','dyninfo.npy'))
			


		# Use known series tag by calling disp_seriesfolders first
		# Find folder that matches seriestag
		MOLLIFolder=glob.glob(os.path.join(self.datadirect,seriestag))
		if not MOLLIFolder:
			print('Folder not found')
			return
		print('Found ',MOLLIFolder[0])

		# Find all the filenames
		MOLLIfiles=glob.glob(os.path.join(self.datadirect,MOLLIFolder[0],'*.dcm'))
		numfiles=len(MOLLIfiles)
		print("Reading "+str(numfiles)+" MOLLI files")

		# Read the last file to work out size, check for manufacturer and fill out info variables
		info=dicom.read_file(MOLLIfiles[-1])
		im=info.pixel_array
		# Find pixel sizes and other required dynamic info
		# self.dyninfo=np.zeros(1,dtype=[('pixelsize','f8'),('TR','f8'),('FlipAngle','f8'),('tres','f8'),('numtimepoints','i4'),('numslices','i4')])
		# self.dyninfo['pixelsize']=float(info.PixelSpacing[0])
		# self.dyninfo['TR']=float(info.RepetitionTime)
		# self.dyninfo['FlipAngle']=float(info.FlipAngle)

		# Make an array to hold the dynamic data
		MOLLIims=np.zeros((im.shape[0],im.shape[1],numfiles),dtype='uint16')
		
		# Read files into the array
		for i in range(0,len(MOLLIfiles)):
			temp=dicom.read_file(MOLLIfiles[i]) # Read file
			MOLLIims[:,:,i]=np.flipud(temp.pixel_array) # Read into the right part of the array

		# save this file as an npy array for next time

		if PreOrPost=='Pre':
			np.save(os.path.join(os.path.split(self.datadirect)[0],'Analysis','MOLLIpre.npy'),MOLLIims)
			#np.save(os.path.join(os.path.split(self.datadirect)[0],'Analysis','dyninfo.npy'),self.dyninfo)
			self.MOLLIpre=MOLLIims

		if PreOrPost=='Post':
			np.save(os.path.join(os.path.split(self.datadirect)[0],'Analysis','MOLLIpost.npy'),MOLLIims)
			#np.save(os.path.join(os.path.split(self.datadirect)[0],'Analysis','dyninfo.npy'),self.dyninfo)
			self.MOLLIpost=MOLLIims
示例#25
0
def checkDicomFile(filename):
    """
        Проверяет, является ли выбранный файл корректным файлом DICOM
    """
    error = False
    try:
        dicom.read_file(filename)
    except:
        error = True
    return error
示例#26
0
 def testRead(self):
     """Unicode: Can read a file with unicode characters in name................"""
     uni_name = u'test°'
     try:
         dicom.read_file(uni_name)
     except UnicodeEncodeError:
         self.fail("UnicodeEncodeError generated for unicode name")
     # ignore file doesn't exist error
     except IOError:
         pass
示例#27
0
 def listdirRecursive(self, rootDir):
   files = []
   for root, subFolders, dirFiles in os.walk(rootDir):
     for f in dirFiles:
       try:
         fileName = os.path.join(root,f)
         dicom.read_file(fileName)
         files.append(fileName)
       except:
         pass
   return files
示例#28
0
文件: dcm.py 项目: 0xBADCA7/spyder
 def load_dicom(filename):
     try:
         name = osp.splitext(osp.basename(filename))[0]
         try:
             data = dicomio.read_file(filename, force=True)
         except TypeError:
             data = dicomio.read_file(filename)                
         arr = data.pixel_array
         return {name: arr}, None
     except Exception as error:
         return None, str(error)
示例#29
0
    def setUp(self):
        dcm_path = path.join(test_dir,
                             'data',
                             'dcmstack',
                             '2D_16Echo_qT2',
                             'TE_20_SlcPos_-33.707626341697.dcm')
        self.dcm = dicom.read_file(dcm_path)

        self.stack = dcmstack.DicomStack()
        self.stack.add_dcm(self.dcm)
        self.dcm = dicom.read_file(dcm_path)
def get_LorR_from_bilateral(DicomDirectory, DynSeries_id, T2Series_id):
    '''
    This function takes a root directory with a bilateral scan and returns two subdirectories 
    nested inside abspath_PhaseID, one for LEFT breast and other for Right breast only
    '''
    # procees Dynamic
    abspath_PhaseID = DicomDirectory+os.sep+DynSeries_id
    # read and sort by location
    [len_listSeries_files, sorted_FileNms_slices_stack] = ReadDicomfiles(abspath_PhaseID) 
    # simple separation between L and R
    Left_slices = sorted_FileNms_slices_stack.iloc[:int(len_listSeries_files/2)]
    Rigth_slices = sorted_FileNms_slices_stack.iloc[int(len_listSeries_files/2+1):]
    
    os.chdir(abspath_PhaseID)
    # preccess Left
    os.mkdir(abspath_PhaseID+os.sep+'Left')
    for i in range(len(Left_slices)):
        dcmtomove = Left_slices.iloc[i,1]
        proc = subprocess.Popen(['cp', dcmtomove, 'Left'+os.sep], stdout=subprocess.PIPE)
        proc.wait()
        
    # process Right        
    os.mkdir(abspath_PhaseID+os.sep+'Right')
    for i in range(len(Rigth_slices)):
        dcmtomove = Rigth_slices.iloc[i,1]
        proc = subprocess.Popen(['cp', dcmtomove, 'Right'+os.sep], stdout=subprocess.PIPE)
        proc.wait()
        
    # extract left most slice position for each subvolume
    # for left
    [Leftlen_listSeries_files, Leftsorted_FileNms_slices_stack] = ReadDicomfiles(abspath_PhaseID+os.sep+'Left') 
    print Leftsorted_FileNms_slices_stack.values
    Leftmostleft_slice = Leftsorted_FileNms_slices_stack.iloc[0]['slices']  
    dicomInfo_Left = dicom.read_file(abspath_PhaseID+os.sep+'Left'+os.sep+str(Leftmostleft_slice))     
    # Image Position (0020,0032): specifies the x, y, and z coordinates of the upper left hand corner of the image. 
    # his tag specifies the coordinates of the the first voxel transmitted.
    Left_pos_pat = list(dicomInfo_Left[0x0020,0x0032].value)
    # Image Orientation (0020,0037): specifies the direction cosines 
    Left_ori_pat = list(dicomInfo_Left[0x0020,0x0037].value)
    print "Left DCE image_pos_pat: %s" % Left_pos_pat
    
    # for Right
    [Rightlen_listSeries_files, Rightsorted_FileNms_slices_stack] = ReadDicomfiles(abspath_PhaseID+os.sep+'Right') 
    print Rightsorted_FileNms_slices_stack.values
    Rightmostleft_slice = Rightsorted_FileNms_slices_stack.iloc[0]['slices']  
    dicomInfo_Right = dicom.read_file(abspath_PhaseID+os.sep+'Right'+os.sep+str(Rightmostleft_slice))     
    # Image Position (0020,0032): specifies the x, y, and z coordinates of the upper left hand corner of the image. 
    # his tag specifies the coordinates of the the first voxel transmitted.
    Right_pos_pat = list(dicomInfo_Right[0x0020,0x0032].value)
    # Image Orientation (0020,0037): specifies the direction cosines 
    Right_ori_pat = list(dicomInfo_Right[0x0020,0x0037].value)
    print "Right DCE image_pos_pat: %s" % Right_pos_pat
    
    return Left_pos_pat, Left_ori_pat, Right_pos_pat, Right_ori_pat
示例#31
0
    def get_3Ddata(self, start=0, stop=None, step=1):
        """
        Function make 3D data from dicom file slices
        """
        data3d = []
        dcmlist = self.dcmlist
        # print 'stsp ', start, stop, step

        if stop is None:
            stop = len(dcmlist)

        raw_max = None
        raw_min = None
        slope = None
        inter = None

        printRescaleWarning = False
        for i in xrange(start, stop, step):
            onefile = dcmlist[i]
            data = dicom.read_file(onefile)
            data2d = data.pixel_array
            # mport pdb; pdb.set_trace()

            if len(data3d) == 0:
                shp2 = data2d.shape
                data3d = np.zeros([len(dcmlist), shp2[0], shp2[1]],
                                  dtype=np.int16)
                mx = np.max(data2d)
                mn = np.min(data2d)
                if (raw_max is None) or (raw_max < mx):
                    raw_max = mx
                if (raw_min is None) or (raw_min < mx):
                    raw_min = mn

            try:
                slope = data.RescaleSlope
                inter = data.RescaleIntercept
                if slope == 1 and inter == 0:
                    printRescaleWarning = True
                    slope = 0.5
                    inter = 0  # -16535
                new_data2d = (np.float(slope) * data2d)\
                    + np.float(inter)

            except:
                logger.warning(
                    'problem with RescaleSlope and RescaleIntercept')
                print 'problem with RescaleSlope and RescaleIntercept'
                traceback.print_exc()
                print '----------'

                new_data2d = (np.float(1) * data2d)\
                    + np.float(0)

            # first readed slide is at the end

            data3d[-i - 1, :, :] = new_data2d

            logger.debug("Data size: " + str(data3d.nbytes) + ', shape: ' +
                         str(shp2) + 'x' + str(len(dcmlist)) + ' file ' +
                         onefile)
        if printRescaleWarning:
            print "Automatic Rescale with slope 0.5"
            logger.warning("Automatic Rescale with slope 0.5")

        return data3d
    def examinePhilips4DUS(self, filePath):
        # currently only this one (bogus, non-standard) Philips 4D US format is supported
        supportedSOPClassUID = '1.2.840.113543.6.6.1.3.10002'

        # Quick check of SOP class UID without parsing the file...
        try:
            sopClassUID = slicer.dicomDatabase.fileValue(
                filePath, self.tags['sopClassUID'])
            if sopClassUID != supportedSOPClassUID:
                # Unsupported class
                return []
        except Exception as e:
            # Quick check could not be completed (probably Slicer DICOM database is not initialized).
            # No problem, we'll try to parse the file and check the SOP class UID then.
            pass

        try:
            ds = dicom.read_file(filePath, stop_before_pixels=True)
        except Exception as e:
            logging.debug("Failed to parse DICOM file: {0}".format(e.message))
            return []

        if ds.SOPClassUID != supportedSOPClassUID:
            # Unsupported class
            return []

        confidence = 0.9

        if ds.PhotometricInterpretation != 'MONOCHROME2':
            logging.warning('Warning: unsupported PhotometricInterpretation')
            confidence = .4

        if ds.BitsAllocated != 8 or ds.BitsStored != 8 or ds.HighBit != 7:
            logging.warning('Warning: Bad scalar type (not unsigned byte)')
            confidence = .4

        if ds.PhysicalUnitsXDirection != 3 or ds.PhysicalUnitsYDirection != 3:
            logging.warning('Warning: Units not in centimeters')
            confidence = .4

        if ds.SamplesPerPixel != 1:
            logging.warning('Warning: multiple samples per pixel')
            confidence = .4

        name = ''
        if hasattr(ds, 'SeriesNumber') and ds.SeriesNumber:
            name = '{0}:'.format(ds.SeriesNumber)
        if hasattr(ds, 'Modality') and ds.Modality:
            name = '{0} {1}'.format(name, ds.Modality)
        if hasattr(ds, 'SeriesDescription') and ds.SeriesDescription:
            name = '{0} {1}'.format(name, ds.SeriesDescription)
        if hasattr(ds, 'InstanceNumber') and ds.InstanceNumber:
            name = '{0} [{1}]'.format(name, ds.InstanceNumber)

        loadable = DICOMLoadable()
        loadable.files = [filePath]
        loadable.name = name.strip(
        )  # remove leading and trailing spaces, if any
        loadable.tooltip = "Philips 4D Ultrasound"
        loadable.selected = True
        loadable.confidence = confidence

        return [loadable]
示例#33
0
    colors = tuple(np.array([con['color'] for con in contours]) / 255.0)
    return label, colors


data_path = "C:/INFINITT/BNCT_TEMP"
patients = [
    os.path.join(data_path, name) for name in os.listdir(data_path)
    if os.path.isdir(os.path.join(data_path, name))
]

pat = patients[0]
for subdir, dirs, files in os.walk(pat):
    dcms = glob.glob(os.path.join(subdir, "*.dcm"))
    if len(dcms) == 1:
        structure = dicom.read_file(os.path.join(subdir, files[0]))
        contours = read_structure(structure)
    elif len(dcms) > 1:
        slices = [dicom.read_file(dcm) for dcm in dcms]
        slices.sort(key=lambda x: float(x.ImagePositionPatient[2]))
        image = np.stack([s.pixel_array for s in slices], axis=-1)
        label, colors = get_mask(contours, slices)

plt.figure(figsize=(15, 15))
for i in range(9):
    plt.subplot(3, 3, i + 1)
    plt.imshow(image[..., i + 50], cmap="gray")
    plt.contour(label[..., i + 50],
                levels=[0.5, 1.5, 2.5, 3.5, 4.5],
                colors=colors)
    plt.axis('off')
示例#34
0
def preprocess_image(filename, laterality):
    dcm = dicom.read_file(filename)
    m = center_crop_resize_filter(dcm.pixel_array, laterality)
    return np.array([[m, m, m]])
    def examineGeKretzUS(self, filePath):
        # E Kretz uses 'Ultrasound Image Storage' SOP class UID
        supportedSOPClassUID = '1.2.840.10008.5.1.4.1.1.6.1'

        # Quick check of SOP class UID without parsing the file...
        try:
            sopClassUID = slicer.dicomDatabase.fileValue(
                filePath, self.tags['sopClassUID'])
            if sopClassUID != supportedSOPClassUID:
                # Unsupported class
                return []
        except Exception as e:
            # Quick check could not be completed (probably Slicer DICOM database is not initialized).
            # No problem, we'll try to parse the file and check the SOP class UID then.
            pass

        try:
            ds = dicom.read_file(
                filePath,
                defer_size=50)  # use defer_size to not load large fields
        except Exception as e:
            logging.debug("Failed to parse DICOM file: {0}".format(e.message))
            return []

        if ds.SOPClassUID != supportedSOPClassUID:
            # Unsupported class
            return []

        # Check if these expected DICOM tags are available:
        # (7fe1,0011) LO [KRETZ_US]                               #   8, 1 PrivateCreator
        # (7fe1,1101) OB 4b\52\45\54\5a\46\49\4c\45\20\31\2e\30\20\20\20\00\00\01\00\02\00... # 3471038, 1 Unknown Tag & Data
        kretzUsTag = dicom.tag.Tag('0x7fe1', '0x11')
        kretzUsDataTag = dicom.tag.Tag('0x7fe1', '0x1101')

        if kretzUsTag not in ds.keys():
            return []
        if kretzUsDataTag not in ds.keys():
            return []

        confidence = 0.9

        # These manufacturers values have been found in successfully loadable files:
        # - Kretztechnik
        # - GE Healthcare
        # - GE Healthcare Austria GmbH & Co OG
        if (ds.Manufacturer != 'Kretztechnik') and (
                ds.Manufacturer.find('GE Healthcare') < 0):
            logging.warning('Warning: unknown manufacturer: ' +
                            ds.Manufacturer)
            confidence = .4

        name = ''
        if hasattr(ds, 'SeriesNumber') and ds.SeriesNumber:
            name = '{0}:'.format(ds.SeriesNumber)
        if hasattr(ds, 'Modality') and ds.Modality:
            name = '{0} {1}'.format(name, ds.Modality)
        if hasattr(ds, 'SeriesDescription') and ds.SeriesDescription:
            name = '{0} {1}'.format(name, ds.SeriesDescription)
        if hasattr(ds, 'InstanceNumber') and ds.InstanceNumber:
            name = '{0} [{1}]'.format(name, ds.InstanceNumber)
        name = name.strip()  # remove leading and trailing spaces, if any

        loadable = DICOMLoadable()
        loadable.files = [filePath]
        loadable.name = name
        loadable.tooltip = "GE Kretz 3D Ultrasound"
        loadable.warning = "Importing of this file format is experimental: images may be distorted, size measurements may be inaccurate."
        loadable.selected = True
        loadable.confidence = confidence

        loadableHighRes1 = DICOMLoadable()
        loadableHighRes1.files = loadable.files
        loadableHighRes1.name = loadable.name + " (LR)"
        loadableHighRes1.tooltip = loadable.tooltip + " (low-resolution)"
        loadableHighRes1.warning = loadable.warning
        loadableHighRes1.selected = False
        loadableHighRes1.confidence = confidence

        loadableHighRes2 = DICOMLoadable()
        loadableHighRes2.files = loadable.files
        loadableHighRes2.name = loadable.name + " (HR)"
        loadableHighRes2.tooltip = loadable.tooltip + " (high-resolution)"
        loadableHighRes2.warning = loadable.warning
        loadableHighRes2.selected = False
        loadableHighRes2.confidence = confidence

        return [loadable, loadableHighRes1, loadableHighRes2]
示例#36
0
import dicom

filepath = '/media/aether/My Passport/Medical Images Data/LCTSC - Lung CT Segmentation Challenge 2017/train/LCTSC-Train-S1-001/S1-001_countors/'

ds = dicom.read_file(filepath + "000000.dcm", force=True)
# print ds.dir("contour")
ctrs = ds.ROIContourSequence
# print len(ctrs) #5
# print len(ctrs[0]) #3

print ctrs[0].ContourSequence[0].ContourData

# ss = dicom.read_file('rtss.dcm')
# ss.ROIContours[0].Contours[0].ContourData 
def vNavRead():
    f, axarr = plt.subplots(1, 2)
    #subjects = ["BANDA050","BANDA051","BANDA052","BANDA053","BANDA054","BANDA055","BANDA056","BANDA057","BANDA058","BANDA059","BANDA060"]
    #subjects = ["BANDA004","BANDA005","BANDA006","BANDA007","BANDA008","BANDA009","BANDA010","BANDA011","BANDA012","BANDA013", "BANDA014", "BANDA015"]
    #subjects = ["BANDA092","BANDA093","BANDA094","BANDA095","BANDA096","BANDA097","BANDA098","BANDA099", "BANDA100","BANDA101","BANDA102","BANDA103","BANDA104","BANDA105","BANDA106","BANDA107","BANDA108","BANDA109", "BANDA110","BANDA111","BANDA112","BANDA113","BANDA114","BANDA115","BANDA116","BANDA117","BANDA118","BANDA119"]
    #,"BANDA088","BANDA089","BANDA090","BANDA091",]
    #subjects = ["BANDA138","BANDA139","BANDA140"]
    subjects = ["BANDA091"]  #,"BANDA139","BANDA140"]
    #["BANDA126","BANDA127","BANDA128","BANDA129","BANDA130","BANDA132","BANDA133","BANDA135","BANDA136","BANDA137","BANDA138","BANDA139","BANDA140"]

    #["BANDA083","BANDA084","BANDA085","BANDA086","BANDA087"]
    for s in subjects:

        dicoms = glob.glob('/space/erebus/1/users/data/dicoms/' + s + '/MR*')
        vnavsT1 = []
        vnavsT2 = []
        vnavsT1Score = []
        vnavsT2Score = []
        vnavsT1Comms = []
        vnavsT2Comms = []

        vNav = 0
        vNav2 = 0
        for d in dicoms:
            dcm = dicom.read_file(d)
            if dcm.ProtocolName == 'HCP_MGH_T1w_MPR_vNav' and dcm.SequenceName == 'ABCD3d1_32ns':
                quat = dcm.ImageComments.split()
                if vNav == 0 and len(vnavsT1Score) > 1:
                    vnavsT1Score = []
                vnavsT1Comms.append(
                    str(dcm.AcquisitionNumber) + " " + dcm.ImageComments)
                if int(dcm.AcquisitionNumber) > 1:

                    vnavsT1.append(
                        np.array([
                            float(quat[1]),
                            float(quat[2]),
                            float(quat[3]),
                            float(quat[4]),
                            float(quat[6]),
                            float(quat[7]),
                            float(quat[8])
                        ]))
                    if len(vnavsT1) > 1:
                        vnavsT1Score.append(getvNavScore(vnavsT1))
                        print(vnavsT1Comms[len(vnavsT1Comms) - 2],
                              "vnav score:",
                              vnavsT1Score[len(vnavsT1Score) - 1])
                    vNav += 1

                else:
                    vnavsT1.append(
                        np.array([0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]))
                    vnavsT1Score.append(getvNavScore(vnavsT1))
                    print(vnavsT1Comms[len(vnavsT1Comms) - 2], "vnav score:",
                          vnavsT1Score[len(vnavsT1Score) - 1])
                    vNav = 0

            elif dcm.ProtocolName == 'HCP_MGH_T2w_SPC_vNav' and dcm.SequenceName == 'ABCD3d1_32ns':
                quat = dcm.ImageComments.split()
                if vNav2 == 0 and len(vnavsT2Score) > 1:
                    vnavsT2Score = []
                if int(dcm.AcquisitionNumber) > 1:
                    vnavsT2.append(
                        np.array([
                            float(quat[1]),
                            float(quat[2]),
                            float(quat[3]),
                            float(quat[4]),
                            float(quat[6]),
                            float(quat[7]),
                            float(quat[8])
                        ]))
                    if len(vnavsT2) > 1:
                        vnavsT2Score.append(getvNavScore(vnavsT2))
                    vNav2 += 1
                else:
                    vnavsT2.append(
                        np.array([0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]))
                    vnavsT2Score.append(getvNavScore(vnavsT2))
                    vNav2 = 0

        f = open(
            "/space/erebus/1/users/data/preprocess/" + s +
            "/motion/vnavsT1Score.csv", 'w')
        f.write(str(vnavsT1Score).replace("[", "").replace("]", ""))
        f.close()
        f = open(
            "/space/erebus/1/users/data/preprocess/" + s +
            "/motion/vnavsT2Score.csv", 'w')
        f.write(str(vnavsT2Score).replace("[", "").replace("]", ""))
        f.close()

        print(vnavsT1Score)
        print(vnavsT2Score)
        print(s, "T1", sum(np.array(vnavsT1Score) > 0.5))
        print(s, "T2", sum(np.array(vnavsT2Score) > 0.5))

        axarr[0].plot(range(len(vnavsT1Score)), vnavsT1Score, label=s)
        axarr[0].set_xlabel('TR (T1)')
        axarr[0].set_ylabel('vnav score')

        axarr[1].plot(range(len(vnavsT2Score)), vnavsT2Score, label=s)
        axarr[1].set_xlabel('TR (T2)')
        axarr[1].set_ylabel('vnav score')
    axarr[0].legend(ncol=3)
    axarr[1].legend(ncol=3)
示例#38
0
文件: pycom.py 项目: lynch829/pycom
                    required=True)
parser.add_argument('-B', '--beamdir', help='Directory for BEAM model')
parser.add_argument('-D', '--dosxyzdir', help='Directory for dosxyznrc')
args = parser.parse_args()

if args.beamdir:
    beamdir = args.beamdir
else:
    beamdir = os.getenv('EGS_HOME') + '/BEAM_ARC'
if args.dosxyzdir:
    dosxyzdir = args.dosxyzdir
else:
    dosxyzdir = os.getenv('EGS_HOME') + '/dosxyznrc'

dcmplanfile = args.dcmplan
dcmplan = dicom.read_file(dcmplanfile)

patientname = dcmplan.PatientsName
patientid = dcmplan.PatientID
planname = dcmplan.RTPlanLabel

# open the serial of files for output
outpath = os.path.dirname(os.path.abspath(dcmplanfile)) + '/'
outpathbeam = outpath + 'beamnrc/'
outpathdose = outpath + 'dosxyznrc/'
if not os.path.exists(outpathbeam):
    os.makedirs(outpathbeam)
if not os.path.exists(outpathdose):
    os.makedirs(outpathdose)

filemainpart = patientid + '_' + planname
示例#39
0
        # Check for new file every 1ms
        while not os.path.exists(nextFullFilename):
            time.sleep(0.001)

        # Maybe useful to have a timestamp
        print(time.time())

        # Give a little time for the file to be fully transferred
        time.sleep(0.01)
        if verbose:
            print('File size is {0} bytes'.format(
                os.path.getsize(nextFullFilename)))

        # read in, convert to nifti, analyze, send file back

        dicomObject = dicom.read_file(nextFullFilename)
        niftiObject = dicomreaders.mosaic_to_nii(dicomObject)
        dat = niftiObject.get_data()
        print(dat.shape)

        currentImage = currentImage + 1

        if verbose:
            print('Send')
        linuxSocket.send(feedbackData)

except (KeyboardInterrupt):
    print('Close')
    linuxSocket.close()
    def examineGeUSMovie(self, filePath):
        supportedSOPClassUIDs = [
            '1.2.840.10008.5.1.4.1.1.6.1'  # UltrasoundImageStorage
        ]

        # Quick check of SOP class UID without parsing the file...
        try:
            sopClassUID = slicer.dicomDatabase.fileValue(
                filePath, self.tags['sopClassUID'])
            if not sopClassUID in supportedSOPClassUIDs:
                # Unsupported class
                return []
        except Exception as e:
            # Quick check could not be completed (probably Slicer DICOM database is not initialized).
            # No problem, we'll try to parse the file and check the SOP class UID then.
            pass

        try:
            ds = dicom.read_file(
                filePath,
                defer_size=30)  # use defer_size to not load large fields
        except Exception as e:
            logging.debug("Failed to parse DICOM file: {0}".format(e.message))
            return []

        if not ds.SOPClassUID in supportedSOPClassUIDs:
            # Unsupported class
            return []

        geUsMovieGroupRootTag = dicom.tag.Tag('0x7fe1', '0x0010')
        geUsMovieGroupRootItem = ds.get(geUsMovieGroupRootTag)

        if not geUsMovieGroupRootItem:
            return []
        if geUsMovieGroupRootItem.name != 'Private Creator':
            return []
        if geUsMovieGroupRootItem.value != 'GEMS_Ultrasound_MovieGroup_001':
            return []

        confidence = 0.8

        name = ''
        if hasattr(ds, 'SeriesNumber') and ds.SeriesNumber:
            name = '{0}:'.format(ds.SeriesNumber)
        if hasattr(ds, 'Modality') and ds.Modality:
            name = '{0} {1}'.format(name, ds.Modality)
        if hasattr(ds, 'SeriesDescription') and ds.SeriesDescription:
            name = '{0} {1}'.format(name, ds.SeriesDescription)
        if hasattr(ds, 'InstanceNumber') and ds.InstanceNumber:
            name = '{0} [{1}]'.format(name, ds.InstanceNumber)

        loadable = DICOMLoadable()
        loadable.files = [filePath]
        loadable.name = name.strip(
        )  # remove leading and trailing spaces, if any
        loadable.tooltip = "GE ultrasound image sequence"
        loadable.warning = "Importing of this file format is experimental: images may be distorted, size measurements may be inaccurate."
        loadable.selected = True
        loadable.confidence = confidence

        return [loadable]
示例#41
0
    def get_metaData(self, dcmlist=None, ifile=0):
        """
        Get metadata.
        Voxel size is obtained from PixelSpacing and difference of
        SliceLocation of two neighboorhoding slices (first have index ifile).
        Files in are used.
        """
        if dcmlist is None:
            dcmlist = self.dcmlist

        if len(dcmlist) <= 0:
            return {}

        data = dicom.read_file(dcmlist[ifile])
        try:
            data2 = dicom.read_file(dcmlist[ifile + 1])
            voxeldepth = float(np.abs(data.SliceLocation -
                                      data2.SliceLocation))
        except:
            logger.warning('Problem with voxel depth. Using SliceThickness,' +
                           ' SeriesNumber: ' + str(data.SeriesNumber))

            try:
                voxeldepth = float(data.SliceThickness)
            except:
                logger.warning('Probem with SliceThicknes, setting zero. ' +
                               traceback.format_exc())
                voxeldepth = 0

        try:
            pixelsize_mm = data.PixelSpacing
        except:
            logger.warning('Problem with PixelSpacing. Using [1,1]')
            pixelsize_mm = [1, 1]
        voxelsize_mm = [
            voxeldepth,
            float(pixelsize_mm[0]),
            float(pixelsize_mm[1]),
        ]
        metadata = {
            'voxelsize_mm': voxelsize_mm,
            'Modality': data.Modality,
            'SeriesNumber': self.series_number
        }

        try:
            metadata['SeriesDescription'] = data.SeriesDescription

        except:
            logger.warning(
                'Problem with tag SeriesDescription, SeriesNumber: ' +
                str(data.SeriesNumber))
        try:
            metadata['ImageComments'] = data.ImageComments
        except:
            logger.warning('Problem with tag ImageComments, SeriesNumber: ' +
                           str(data.SeriesNumber))
        try:
            metadata['Modality'] = data.Modality
        except:
            logger.warning('Problem with tag Modality, SeriesNumber: ' +
                           str(data.SeriesNumber))

        metadata['dcmfilelist'] = self.dcmlist

        # mport pdb; pdb.set_trace()
        return metadata
示例#42
0
                        str(int(s.cell(row, 1).value))].append(valuelist)
# update LIDC annotation with series number, rather than scan id
import dicom
LIDCpath = '/media/data1/wentao/LIDC-IDRI/DOI/'
antdictscan = {}
for k, v in antdict.iteritems():
    pid, scan = k.split('_')
    hasscan = False
    for sdu in os.listdir(os.path.join(LIDCpath, 'LIDC-IDRI-' + pid)):
        for srs in os.listdir(
                os.path.join(*[LIDCpath, 'LIDC-IDRI-' + pid, sdu])):
            if srs.endswith('.npy'):
                print('npy', pid, scan, srs)
                continue
            RefDs = dicom.read_file(
                os.path.join(
                    *[LIDCpath, 'LIDC-IDRI-' + pid, sdu, srs, '000006.dcm']))
            # print scan, str(RefDs[0x20, 0x11].value)
            if str(RefDs[0x20, 0x11].value) == scan or scan == '0':
                if hasscan: print('rep', pid, sdu, srs)
                hasscan = True
                antdictscan[pid + '_' + srs] = v
                break
    if not hasscan: print('not found', pid, scan, sdu, srs)
# find the match from LIDC-IDRI annotation
import math
lunaantdictnodid = {}
maxdist = 0
for srcid, lunaantlidc in lunantdictlidc.iteritems():
    lunaantdictnodid[srcid] = []
    pid, stdid = sidmap[srcid]
示例#43
0
def load_data_1(
        startpath='/home/tuixiangbeijingtest0/Desktop/workfolder/CR/',
        big_batch=10000,
        verbose=1,
        nb_classes=2,
        ycolindex=25,  ## the column that we want to investigate
        big_batch_index=0):

    starttime = time.time()
    rawtextcol = []
    foldercol = []
    foldercol1 = []
    for ypath in ypathlist:
        wb = xlrd.open_workbook(ypath)
        sh = wb.sheet_by_index(0)
        rawtextcol += sh.col_values(3)
        foldercol += sh.col_values(5)
        foldercol1 += sh.col_values(4)
        #result0=sh.col_values(3)
        #bodypartcol+=sh.col_values(3)
        #ycol+=sh.col_values(ycolindex)

    Xtest1 = []
    Xtest2 = []
    X_overall = []
    Y_overall = []
    chestposlist = []
    rawtextlist = []
    count = 0
    count1 = 0
    count11 = 0
    selectcount = 0
    selectratio = 1

    #xls0=xlwt.Workbook(encoding='utf-8')
    #xls1=xlwt.Workbook(encoding='utf-8')
    #xls2=xlwt.Workbook(encoding='utf-8')
    #sheet0=xls0.add_sheet('Sheet1')
    #sheet1=xls1.add_sheet('Sheet1')
    #sheet2=xls2.add_sheet('Sheet1')
    #xls=xlwt.Workbook(encoding='utf-8')
    #sheet1=xls.add_sheet('sheet1')
    #for folderi in range(1,1000):
    for folderi in range(1, sh.nrows):
        #if count==450 and count1==225 and count11==225:
        #break
        folder = foldercol[folderi]
        if len(folder) == 0:
            pass
        else:
            #newpath=glob.glob(startpath+folder+'/Final*')
            newpath = '/media/tuixiangbeijingtest0/f989fbc9-24a9-42ce-802e-902125737abd/srv/ruxian2' + foldercol1[
                folderi] + foldercol[folderi] + 'hh'
            #print(newpath)
            if os.path.exists(newpath):
                #bodypart=bodypartcol[folderi]
                #print(newpath)
                rawtext = rawtextcol[folderi]
                tmp = dicom.read_file(
                    newpath
                )  #dicom.read_file("//home/tuixiangbeijingtest0/Desktop/Image_Decom/image1")
                #bodypart=tmp.BodyPartExamined#bodypart=tmp['Body Part Examined'][0]
                #rawtext=rawtext.replace('.','')
                if hasattr(
                        tmp, 'BodyPartExamined'
                ) and tmp.BodyPartExamined == part and hasattr(
                        tmp, 'ViewPosition'
                ) and tmp.ViewPosition == position:  #bodypart: #体位 X光
                    #ifbool=True
                    #for cont in controltextlist:
                    #if not cont in rawtext:
                    #ifbool=False
                    #break
                    #ifbool=True
                    #if str1 in rawtext:
                    if any(cont in rawtext for cont in indtext0) and (not all(
                            cont in rawtext
                            for cont in indtext1)) and (not all(
                                cont in rawtext
                                for cont in indtext2)) and count < 100:
                        #if (ifbool==True and not any(cont in rawtext for cont in indtext) and not any(cont in rawtext for cont in indtext2)): #or (any(wl in rawtext for wl in wllist) and all(zdy in rawtext for zdy in zdylist)  and not any(cont in rawtext for cont in indtext) and not any(cont in rawtext for cont in indtext2)):
                        #if any(cont in rawtext for cont in controltextlist):
                        #tmp=sio.loadmat(newpath[0])
                        pos = tmp.ViewPosition  #pos=tmp['View Position']

                        if pos == 'PA':  #部位 X光
                            if selectcount % selectratio == 0:
                                #if count>=1000:
                                #continue
                                rawtextlist.append(rawtext)
                                #sheet0.write(count,0,rawtext)
                                #sheet0.write(count,1,'0')
                                #sheet2.write(count,0,rawtext)
                                #sheet2.write(count,1,'0')
                                chestposlist.append(pos)
                                imageData = cv2.resize(
                                    tmp.pixel_array, (224, 224)
                                )  #imageData=cv2.resize(x1.pixel_array,(224,224))
                                #imageData=misc.imresize(imageData,newsize)
                                #imageData=imageData[45:173,60:188]
                                #imageData=misc.imresize(imageData,newsize)
                                X_overall.append(imageData)
                                Y_overall.append(0)
                                Xtest1.append(imageData)
                                count += 1
                                #continue
                                '''
                                foldername='/home/tuixiangbeijingtest0/Desktop/workfolder/ttest/'+str(count)+'.png'                               
                                plt.clf()
                                plt.xlabel(0)
                                plt.imshow(imageData,cmap=plt.cm.Greys_r)
                                plt.savefig(foldername)
                                '''
                    elif any(cont in rawtext
                             for cont in indtext1) and (not all(
                                 cont in rawtext
                                 for cont in indtext0)) and count1 < 50:
                        #elif any(cont in rawtext for cont in indtext) and not(str2 in rawtext) and not(str3 in rawtext) and not(str4 in rawtext) and not(str5 in rawtext) and not(str6 in rawtext) and count1<550:
                        #tmp=sio.loadmat(newpath[0])
                        pos = tmp.ViewPosition  #
                        if pos == 'PA':
                            selectcount += 1
                            #if count1>=1000:
                            #continue
                            rawtextlist.append(rawtext)
                            #sheet1.write(count1,1,rawtext)
                            #sheet1.write(count1,2,'1')
                            #sheet1.write(count1,3,'heart')
                            #sheet2.write(count1+1000,0,rawtext)
                            #sheet2.write(count1+1000,1,'1')
                            chestposlist.append(pos)
                            imageData = cv2.resize(
                                tmp.pixel_array, (224, 224)
                            )  #imageData=cv2.resize(x1.pixel_array,(224,224))
                            #imageData=misc.imresize(imageData,newsize)
                            #imageData=imageData[45:173,60:188]
                            #imageData=misc.imresize(imageData,newsize)

                            X_overall.append(imageData)
                            Y_overall.append(1)
                            Xtest2.append(imageData)
                            count1 += 1
                            #continue
                            #print(count1)
                            #print(rawtext)
                            #sheet1.write(count1,1,rawtext)

                            #elif any(cont in rawtext for cont in indtext2):
                            #’‘’(any(wl in rawtext for wl in wllist) and not any(cont in rawtext for cont in controltextlist)) or‘’‘

                    #(any(wl in rawtext for wl in wllist) and
                    #elif ((any(wl in rawtext for wl in wllist) and any(cont in rawtext for cont in indtext2)) or any(cont in rawtext for cont in indtext2)) and not(str2 in rawtext) and count11<500:
                    #elif ((any(wl in rawtext for wl in wllist) and any(cont in rawtext for cont in indtext2)) or any(cont in rawtext for cont in indtext2)) and not(str2 in rawtext) and not(str3 in rawtext) and not(str4 in rawtext) and not(str5 in rawtext) and not(str6 in rawtext) and count11<450:
                    #elif any(cont in rawtext for cont in indtext2) and not(str2 in rawtext) and not(str3 in rawtext)  and count11<500:
                    elif any(cont in rawtext
                             for cont in indtext2) and (not all(
                                 cont in rawtext
                                 for cont in indtext0)) and count11 < 50:
                        pos = tmp.ViewPosition  #
                        if pos == 'PA':
                            selectcount += 1
                            rawtextlist.append(rawtext)
                            #sheet1.write(count11+500,1,rawtext)
                            #sheet1.write(count11+500,2,'1')
                            #sheet1.write(count11+500,3,'lung')
                            #sheet2.write(count11+1500,0,rawtext)
                            #sheet2.write(count11+1500,1,'1')
                            chestposlist.append(pos)
                            imageData = cv2.resize(
                                tmp.pixel_array, (224, 224)
                            )  #imageData=cv2.resize(x1.pixel_array,(224,224))
                            #imageData=misc.imresize(imageData,newsize)
                            #imageData=imageData[45:173,60:188]
                            #imageData=misc.imresize(imageData,newsize)

                            X_overall.append(imageData)
                            Y_overall.append(1)
                            Xtest2.append(imageData)
                            count11 += 1
                            #continue
                            #print(count1)
                            #print(rawtext)
                            #sheet1.write(count1,1,rawtext.strip())
                            #xls.save('name1_1.xls')
                            '''
                             foldername='/home/tuixiangbeijingtest0/Desktop/workfolder/ttest/'+str(count)+'.png'
                             plt.clf()
                             plt.xlabel(1)
                             plt.imshow(imageData,cmap=plt.cm.Greys_r)
                             plt.savefig(foldername)
                             '''

    #xls0.save('/home/tuixiangbeijingtest0/Desktop/ftp/heart&lung_0.xls')
    #xls1.save('/home/tuixiangbeijingtest0/Desktop/ftp/heart&lung_1.xls')
    #xls2.save('/home/tuixiangbeijingtest0/Desktop/ftp/heart&lung_1000.xls')
    X_overall = np.array(X_overall) / 5000.0

    Xshape = X_overall.shape
    print(Xshape)
    X_overall = X_overall.reshape(Xshape[0], Xshape[1] * Xshape[2])
    Y_overall = np.array(Y_overall)
    if verbose:
        print("total time " + str(time.time() - starttime))
        unique, counts = np.unique(Y_overall, return_counts=True)
        print(np.mean(np.array(Xtest1)), np.mean(np.array(Xtest2)))
        print(np.std(np.array(Xtest1)), np.std(np.array(Xtest2)))
        print(counts, float(counts[0]) / float((counts[1] + counts[0])))
        '''
      #author: yangfan 
      #功能 根据混淆矩阵的索取得对应报告
      #参数 indexlist 混淆矩阵对应的报告
      #返回值 xlsbg.save 含有报告的xls 
      #使用方法 先得到混淆矩阵 然后取消此处的注视 然后运行模型代码 当控制台输出报告生成完毕 可停止模型
      #注意事项 1.保存位置在/home/tuixiangbeijingtest0/Desktop/workfolder/xls/bgxls/下 
               #2.根据不同情况取不同的表名
               #3.哪个模型的混淆矩阵下标list对应哪个模型 不能混淆 否则会出现匹配报告错误的情况 此处要细心
    
    xlsbg=xlwt.Workbook(encoding='utf-8')
    sheetbg=xlsbg.add_sheet('Sheet1')
    X_validate_a=np.load('/home/tuixiangbeijingtest0/Desktop/workfolder/weights/vgg_transfer_lung/1462865076/X_validate.npy')
    xlcount=0
    indexlist=[66, 80, 124, 176, 190, 282, 301, 363, 382]

    

  
    
    print('正在生成报告...')
    for x_over in range(0,len(X_overall)):
        for index in indexlist:
            if(X_overall[x_over]==X_validate_a[index]).all():
                #print(rawtextlist[xcount])
                                
                #for word in indtext2:
                    #if word in rawtextlist[x_over]:
                        #print('new')
                        #print('----------------------------------------------------')
                        #print(rawtextlist[x_over])
                        #print('111:',word)
                        #print('----------------------------------------------------')
                        #print('end')
                        #break
                     
                sheetbg.write(xlcount,1,rawtextlist[x_over])
                xlcount+=1
                #print(rawtextlist[x_over])
    xlsbg.save('/home/tuixiangbeijingtest0/Desktop/workfolder/xls/bgxls/146286507456_15_01.xls')
    print('报告生成完毕') 
    '''
    return X_overall, Y_overall
示例#44
0
    def patchDicomDir(self, inputDirPath, outputDirPath):
        """
    Since CTK (rightly) requires certain basic information [1] before it can import
    data files that purport to be dicom, this code patches the files in a directory
    with some needed fields.

    Calling this function with a directory path will make a patched copy of each file.
    Importing the old files to CTK should still fail, but the new ones should work.

    The directory is assumed to have a set of instances that are all from the
    same study of the same patient.  Also that each instance (file) is an
    independent (multiframe) series.

    [1] https://github.com/commontk/CTK/blob/16aa09540dcb59c6eafde4d9a88dfee1f0948edc/Libs/DICOM/Core/ctkDICOMDatabase.cpp#L1283-L1287
    """

        import dicom

        self.addLog('DICOM patching started...')
        logging.debug('DICOM patch input directory: ' + inputDirPath)
        logging.debug('DICOM patch output directory: ' + outputDirPath)

        for rule in self.patchingRules:
            rule.logCallback = self.addLog
            rule.processStart(inputDirPath, outputDirPath)

        for root, subFolders, files in os.walk(inputDirPath):

            currentSubDir = os.path.relpath(root, inputDirPath)
            rootOutput = os.path.join(outputDirPath, currentSubDir)

            # Notify rules that processing of a new subdirectory started
            for rule in self.patchingRules:
                rule.processDirectory(currentSubDir)

            for file in files:
                filePath = os.path.join(root, file)
                self.addLog('Examining %s...' %
                            os.path.join(currentSubDir, file))

                skipFileRequestingRule = None
                for rule in self.patchingRules:
                    if rule.skipFile(currentSubDir):
                        skipFileRequestingRule = rule
                        break
                if skipFileRequestingRule:
                    self.addLog('  Rule ' + rule.__class__.__name__ +
                                ' requested to skip this file.')
                    continue

                try:
                    ds = dicom.read_file(filePath)
                except (IOError, dicom.filereader.InvalidDicomError):
                    self.addLog('  Not DICOM file. Skipped.')
                    continue

                self.addLog('  Patching...')

                for rule in self.patchingRules:
                    rule.processDataSet(ds)

                patchedFilePath = os.path.abspath(
                    os.path.join(rootOutput, file))
                for rule in self.patchingRules:
                    patchedFilePath = rule.generateOutputFilePath(
                        ds, patchedFilePath)

                ######################################################
                # Write

                dirName = os.path.dirname(patchedFilePath)
                if not os.path.exists(dirName):
                    os.makedirs(dirName)

                self.addLog('  Writing DICOM...')
                dicom.write_file(patchedFilePath, ds)
                self.addLog('  Created DICOM file: %s' % patchedFilePath)

        self.addLog(
            'DICOM patching completed. Patched files are written to:\n{0}'.
            format(outputDirPath))
示例#45
0
def build_xls(xlsx_file,
              dicom_paths,
              sem_xlsx_file,
              wrongs=[None, None],
              rights=[None, None]):
    sem_file = openpyxl.load_workbook(sem_xlsx_file)
    sem_sheet = sem_file.active

    if os.path.exists(xlsx_file):
        os.remove(xlsx_file)
    wb = openpyxl.Workbook()
    ws = wb.active

    for i in range(len(dicom_paths)):
        data = dicom.read_file(dicom_paths[i])
        r = i + 1
        c = 0

        #Patient ID
        c += 1
        patient = data[0x10, 0x10][:]

        if r == 1:
            ws.cell(row=r, column=c, value='Patient_ID')
        else:
            ws.cell(row=r, column=c, value=patient)

        #Patient always or mostly wrong or right?
        if len(wrongs) == len(rights):
            if len(wrongs) == 2:
                c += 1
                if r == 1:
                    if wrongs[1] in ['Always', 'always']:
                        ws.cell(row=r, column=c, value='Always...')
                    elif wrongs[1] in ['Mostly', 'mostly']:
                        ws.cell(row=r, column=c, value='Mostly...')
                    elif wrongs[1] not in [
                            'Always', 'always', 'Mostly', 'mostly'
                    ]:
                        raise IOError(
                            'wrongs[1] and rights[1] must both be "Always" or "Mostly"'
                        )
                else:
                    if patient in wrongs[0]:
                        ws.cell(row=r, column=c, value='wrong')
                    elif patient in rights[0]:
                        ws.cell(row=r, column=c, value='right')
            else:
                raise IOError(
                    'wrongs and rights take exactly 2 arguments, {} given'.
                    format(len(wrongs)))
        else:
            raise IOError(
                'wrongs and rights must be same length, and both "Always" or both "Mostly"'
            )

        #Patient sex
        c += 1
        if r == 1:
            ws.cell(row=r, column=c, value='Sex')
        else:
            ws.cell(row=r, column=c, value=data[0x10, 0x40].value)

        #Patient age
        c += 1
        if r == 1:
            ws.cell(row=r, column=c, value='Age')
        else:
            for i in range(1, sem_sheet.max_column):
                if sem_sheet.cell(row=1, column=i).value == 'Age':
                    column_index = i
                    break
            for i in range(1, sem_sheet.max_row):
                if sem_sheet.cell(row=i, column=1).value == patient:
                    ws.cell(row=r,
                            column=c,
                            value=sem_sheet.cell(row=i,
                                                 column=column_index).value)
                    break

        #Location
        c += 1
        if r == 1:
            ws.cell(row=r, column=c, value='Tumour location')
        else:
            for i in range(1, sem_sheet.max_column):
                if sem_sheet.cell(row=1, column=i).value == 'Localisation':
                    column_index = i
                    break
            for i in range(1, sem_sheet.max_row):
                if sem_sheet.cell(row=i, column=1).value == patient:
                    ws.cell(row=r,
                            column=c,
                            value=sem_sheet.cell(row=i,
                                                 column=column_index).value)
                    break

        #Depth
        c += 1
        if r == 1:
            ws.cell(row=r, column=c, value='Tumour depth')
        else:
            for i in range(1, sem_sheet.max_column):
                if sem_sheet.cell(row=1, column=i).value == 'Depth_Melissa':
                    column_index = i
                    break
            for i in range(1, sem_sheet.max_row):
                if sem_sheet.cell(row=i, column=1).value == patient:
                    ws.cell(row=r,
                            column=c,
                            value=sem_sheet.cell(row=i,
                                                 column=column_index).value)
                    break

        #Manufacturer
        c += 1
        if r == 1:
            ws.cell(row=r, column=c, value='Manufacturer')
        else:
            ws.cell(row=r, column=c, value=data[0x08, 0x70].value)

        #Scanner model
        c += 1
        if r == 1:
            ws.cell(row=r, column=c, value='Model')
        else:
            ws.cell(row=r, column=c, value=data[0x08, 0x1090].value)

        #Institution name
        c += 1
        if r == 1:
            ws.cell(row=r, column=c, value='Institution')
        else:
            try:
                ws.cell(row=r, column=c, value=data[0x08, 0x80].value)
            except KeyError:
                ws.cell(row=r, column=c, value='-')

        #Station name
        c += 1
        if r == 1:
            ws.cell(row=r, column=c, value='Station')
        else:
            try:
                ws.cell(row=r, column=c, value=data[0x08, 0x1010].value)
            except KeyError:
                ws.cell(row=r, column=c, value='-')

        #Slice thickness
        c += 1
        if r == 1:
            ws.cell(row=r, column=c, value='Slice thickness')
        else:
            ws.cell(row=r, column=c, value=data[0x18, 0x50].value)

        #Repetition time
        c += 1
        if r == 1:
            ws.cell(row=r, column=c, value='RT')
        else:
            ws.cell(row=r, column=c, value=data[0x18, 0x80].value)

        #Echo time
        c += 1
        if r == 1:
            ws.cell(row=r, column=c, value='ET')
        else:
            ws.cell(row=r, column=c, value=data[0x18, 0x81].value)

        #Magnetic field strength
        c += 1
        if r == 1:
            ws.cell(row=r, column=c, value='B0')
        else:
            ws.cell(row=r, column=c, value=data[0x18, 0x87].value)

        #Spacing between slices
        c += 1
        if r == 1:
            ws.cell(row=r, column=c, value='Slice spacing')
        else:
            ws.cell(row=r, column=c, value=data[0x18, 0x88].value)

        #Smalles image pixel value
        c += 1
        if r == 1:
            ws.cell(row=r, column=c, value='Smallest pixel value')
        #else:
        #ws.cell(row=r, column=c, value=data[0x28, 0x0106].value)

        #Largest image pixel value
        c += 1
        if r == 1:
            ws.cell(row=r, column=c, value='Largest pixel value')
        #else:
        #ws.cell(row=r, column=c, value=data[0x28, 0x0107].value)

        wb.save(xlsx_file)
    print('file written to {}'.format(xlsx_file))
    return
    def __init__(self, folder1, file1):
        self.folder1 = folder1
        self.file1 = file1
        Imxray1 = dicom.read_file(self.folder1 + self.file1 + ".dcm")

        Image.__init__(self, Imxray1.pixel_array)
示例#47
0
import os
import glob as gb
import numpy as np
import cv2
import matplotlib.pyplot as plt
import dicom
# 提取轮廓的窗宽 窗位
WL,WW=-360,446
dcm_dir='image.dcm'

dcm = dicom.read_file(dcm_dir)
img_origin = dcm.pixel_array * dcm.RescaleSlope + dcm.RescaleIntercept
img_abdoment = (img_origin - (WL - WW / 2)) / WW * 255  # (x-min)/(max-min)
img_abdoment[img_abdoment < 0] = 0
img_abdoment[img_abdoment > 255] = 255
plt.subplot(1,4,1)
plt.title('ww_wl')
plt.imshow(img_abdoment, cmap='Greys_r')


#===========================================
dicom_np = np.uint8(img_abdoment)
ret, img = cv2.threshold(dicom_np,90,255, cv2.THRESH_BINARY)  # 二值化
im2, contours, _ = cv2.findContours(img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)  # 查找轮廓
# cv2.drawContours(dicom_np, contours, -1, (0, 255, 255), 2)  # 填充轮廓颜色
plt.subplot(1, 4, 2)
plt.title('contours')
plt.imshow(dicom_np, cmap='gray')


示例#48
0
from .. import dicomwrappers as didw
from .. import dicomreaders as didr
from ...volumeutils import endian_codes

from unittest import TestCase
from nose.tools import (assert_true, assert_false, assert_equal,
                        assert_not_equal, assert_raises)

from numpy.testing import assert_array_equal, assert_array_almost_equal

IO_DATA_PATH = pjoin(dirname(__file__), 'data')
DATA_FILE = pjoin(IO_DATA_PATH, 'siemens_dwi_1000.dcm.gz')
DATA_FILE_PHILIPS = pjoin(IO_DATA_PATH, 'philips_mprage.dcm.gz')
if have_dicom:
    DATA = dicom.read_file(gzip.open(DATA_FILE))
    DATA_PHILIPS = dicom.read_file(gzip.open(DATA_FILE_PHILIPS))
else:
    DATA = None
    DATA_PHILIPS = None
DATA_FILE_B0 = pjoin(IO_DATA_PATH, 'siemens_dwi_0.dcm.gz')
DATA_FILE_SLC_NORM = pjoin(IO_DATA_PATH, 'csa_slice_norm.dcm')
DATA_FILE_DEC_RSCL = pjoin(IO_DATA_PATH, 'decimal_rescale.dcm')
DATA_FILE_4D = pjoin(IO_DATA_PATH, '4d_multiframe_test.dcm')

# This affine from our converted image was shown to match our image spatially
# with an image from SPM DICOM conversion. We checked the matching with SPM
# check reg.  We have flipped the first and second rows to allow for rows, cols
# transpose in current return compared to original case.
EXPECTED_AFFINE = np.array(  # do this for philips?
    [[-1.796875, 0, 0, 115],
示例#49
0
def read_dicom_ed(PathDicom, contour_type='icontour'):
    # path to dicom files
    p2dcom = PathDicom + '/P' + patientID + 'dicom'

    # delete tif folder if exist
    path2tif = PathDicom + '/tifED'
    if os.path.exists(path2tif):
        shutil.rmtree(path2tif)
        print 'tif folder was deleted.'
    # create new tif folder
    os.mkdir(path2tif)

    # get the list and and path to dicom files
    lstFilesDCM = []  # create an empty list
    for dirName, subdirList, fileList in os.walk(p2dcom):
        for filename in fileList:
            if ".dcm" in filename.lower():  # check whether the file's DICOM
                lstFilesDCM.append(os.path.join(dirName, filename))

    # Get ref file
    RefDs = dicom.read_file(lstFilesDCM[0])

    # load total number of phases
    nphases = RefDs.CardiacNumberofImages

    # read text file which contains the list of manual contours
    path2txt = glob.glob(PathDicom + '/*.txt')
    txt = open(path2txt[0])
    manuallst = txt.readlines()

    # Load dimensions based on the number of rows, columns, and slices (along the Z axis)
    ConstPixelDims = (int(RefDs.Rows), int(RefDs.Columns), len(manuallst) / 2)

    # loop through all the DICOM files
    k = 0
    for manualfilename in manuallst:
        # only dicom file with contour_type is loaded
        filenameDCM = dirName + '/' + manualfilename[31:-22] + '.dcm'
        if manualfilename[40:48] == contour_type:  # only internal contours
            if int(manualfilename[36:39]) % nphases == 0:
                print 'dicom file: ', filenameDCM
                ds = dicom.read_file(filenameDCM)
                # read manual polygon
                manfn = dirName[:-8] + manualfilename[
                    12:-31] + '/' + manualfilename[31:-2]
                polygonxy = np.loadtxt(manfn)
                # store the raw image data
                if k == 0:
                    ArrayDicom = np.expand_dims(ds.pixel_array, axis=2)
                    tmp1 = poly2mask(polygonxy[:, 1], polygonxy[:, 0],
                                     ConstPixelDims[0:2])
                    ArrayMask = np.expand_dims(tmp1, axis=2)
                else:
                    ArrayDicom = np.append(ArrayDicom,
                                           np.expand_dims(ds.pixel_array,
                                                          axis=2),
                                           axis=2)
                    tmp1 = poly2mask(polygonxy[:, 1], polygonxy[:, 0],
                                     ConstPixelDims[0:2])
                    ArrayMask = np.append(ArrayMask,
                                          np.expand_dims(tmp1, axis=2),
                                          axis=2)

                plt.imsave(path2tif + '/' + manualfilename[31:-22] + '.tif',
                           ArrayDicom[:, :, k],
                           cmap=plt.cm.gray)
                plt.imsave(path2tif + '/' + manualfilename[31:-22] +
                           '_mask.tif',
                           ArrayMask[:, :, k],
                           cmap=plt.cm.gray)

                k = k + 1
    return ArrayDicom, ArrayMask
示例#50
0
import dicom # for reading dicom files
import os # for doing directory operations
import pandas as pd # for some simple data analysis (right now, just to load in the labels data and quickly reference it)
import numpy as np

labels = pd.read_csv('mass-data.csv', usecols=[0,2,3,4,8])
labels['path'] = ("")
for index, row in labels.iterrows():
	labels.iloc[index, labels.columns.get_loc('path')] = 'Mass-Training_'+str(row['patient_id'])+'_'+row['side']+'_'+row['view']+'_'+str(row['abn_num'])
	# row['path'] = 'Mass-Training_'+row['patient_id']+'_'+row['side']+'_'+row['view']+'_'+row['abn_num']
labels.pop('side')
labels.pop('view')
labels.pop('abn_num')
labels.pop('patient_id')
dir = os.walk("DOI")
for index, row in labels.iterrows():
	if(os.path.isdir("DOI/"+row["path"])):
		folder = os.listdir("DOI/"+row["path"])
		folder = [x for x in folder if x != ".DS_Store"]
		if(os.path.isdir("DOI/"+row["path"]+"/"+folder[0])):
			folder2 = os.listdir("DOI/"+row["path"]+"/"+folder[0])
			folder2 = [x for x in folder2 if x != ".DS_Store"]
			ds=dicom.read_file("DOI/"+row["path"]+"/"+folder[0]+"/"+folder2[0]+"/"+"000000.dcm")
			print(ds)
		
def readSIEMENSFlow(args):
          
    print( colored.green("\nLooking for flow data... \n"))
    MagPathStr = args.input
    foldersList = [os.path.join(MagPathStr,o) for o in os.listdir(MagPathStr) if os.path.isdir(os.path.join(MagPathStr,o))]
        
    if not foldersList:
        filesListTEMP = glob.glob(MagPathStr + "/*") 
            
        ds = dicom.read_file(filesListTEMP[0])
        if "SIEMENS" in ds.Manufacturer: 
                print("It's SIEMENS sequence!")
        else:
                print("We currently can not load files from " + ds.Manufacturer + ".")
    else:
            
                for dirName in foldersList:
                    filesListTEMP = glob.glob(dirName + "/*") 
                    
                    ds = dicom.read_file(filesListTEMP[0])
                    if "SIEMENS" in ds.Manufacturer:
                        
                        proceed = True
                        if "magnitude"  in ds.ImageComments:
                            PathFlowDataMAG = dirName
                            print(colored.cyan("Mag folder is: " + PathFlowDataMAG))
                        if "phase" in ds.ImageComments:
                            PathFlowData = dirName
                            print(colored.cyan("Flow folder is: " + PathFlowData))
                            #ConstDimsTemp = (int(ds.Rows), int(ds.Columns), len(filesListTEMP))
                            #dXY = ds.PixelSpacing
                            #dZ = ds.SpacingBetweenSlices
                            #pixel_spc = (dXY[0],dXY[1],dZ)
                            #print(pixel_spc)
                        
                            
                    else:
                        proceed = False
                        print(colored.red("FatalError: We currently can not load files from " + ds.Manufacturer + "."))
                        sys.exit()
          
 #   MagPathStr = str(FolderPath)
   # PathList=MagPathStr.split("/")
   # basePath = MagPathStr.replace(PathList[-1],"")


    if proceed:
      flowData = None 
      for folderNumber in range(0,2):
    #    sliceLocation = []
        # flow files list
        lstFilesDCM = []
     #   triggerTime = []
            
        if folderNumber == 0:
            folderPath = PathFlowDataMAG
            print(colored.cyan("Reading the Magnitude files."))
           
        if folderNumber == 1:
            if args.segmentation:
                break
            folderPath = PathFlowData
            print(colored.cyan("Reading the flow files ."))
           
       
           
            
          
            ################## Reading time of flight files
            # listing magnitude files
        for dirName, subdirList, fileList in os.walk( folderPath + "/"):
            for filename in fileList:
            # if ".dcm" in filename.lower():  # check whether the file's DICOM
                lstFilesDCM.append(os.path.join(dirName,filename))
      #          ds = dicom.read_file(lstFilesDCM[-1])
      #          sliceLocation.append(ds.SliceLocation)
      #          triggerTime.append(ds.TriggerTime)
                
            # Get ref file
        RefDs = dicom.read_file(lstFilesDCM[0])
            
            
      #  triggerTimeTemp = sorted(set(triggerTime), key=float)
        #print(triggerTimeTemp)
        #sliceLocationTemp = set(sliceLocation)       
       # sliceLocationTemp = sorted(set(sliceLocation), key=float)
        #print(sliceLocationTemp)

       

            
        if folderNumber == 0:
                ConstPixelDims = (int(RefDs.Rows), int(RefDs.Columns), len(lstFilesDCM))
                dXY = ds.PixelSpacing
                dZ = ds.SliceThickness
                pixel_spc = (dXY[0],dXY[1],dZ)
                MagData = numpy.zeros(ConstPixelDims, dtype=numpy.double)
                for iFile in lstFilesDCM:
                    dsTemp = dicom.read_file (iFile)
                    MagData[:,:,int(dsTemp.InstanceNumber)-1]= dsTemp.pixel_array.astype('float')
             
                #print(MagData.shape)
               # print(RefDs)
                MagDataAve = numpy.reshape(MagData, (int(RefDs.Rows), int(RefDs.Columns),len(lstFilesDCM)/int(RefDs.CardiacNumberofImages), RefDs.CardiacNumberofImages), order='F')
                #print(MagDataAve.shape)
                magDataTemp = MagDataAve.mean(3)
                
               # magDataRevX = numpy.flip(magDataTemp, 0)
               # magDataRevZ = numpy.flip(magDataRevX, 2)
                
                magSize = magDataTemp.shape
                totalNodes = magSize[0] * magSize[1] * magSize[2]
                
                if args.vtk:
                    saveVTKSeg(magDataTemp,False,False, pixel_spc, totalNodes, args.output)
                if args.mat:
                    scipy.io.savemat(args.output + "/mag.mat", mdict={'magDataTemp': magDataTemp})
             #   numpy.save(args.output +"/mag", magDataTemp) 
                
        else :
                if flowData is None:
                    ConstFlowPixelDims = (int(RefDs.Rows), int(RefDs.Columns),len(lstFilesDCM))
                    flowDataTemp = numpy.zeros(ConstFlowPixelDims, dtype=numpy.double)
                    sliceLocationTemp = numpy.zeros([len(lstFilesDCM),2], dtype=numpy.double)
                   # icounter = 0
                for iFile in lstFilesDCM:
                    dsTemp = dicom.read_file (iFile)        
                    flowDataTemp[:,:,int(dsTemp.InstanceNumber)-1]= dsTemp.pixel_array.astype('int')
                    sliceLocationTemp[int(dsTemp.InstanceNumber)-1] = numpy.array([int(dsTemp.InstanceNumber)-1, float(dsTemp.SliceLocation)])
                   # icounter += 1
                    
                    
                print(sliceLocationTemp.shape)
                print(sliceLocationTemp)
                sys.exit()
                #print(flowDataTemp.shape)
                flowDataTemp = numpy.reshape(flowDataTemp, (int(RefDs.Rows), int(RefDs.Columns),len(lstFilesDCM)/3, 3), order='F')
                
                UAll = flowDataTemp[:,:,:,args.velocityorder[0]].squeeze()
                VAll = flowDataTemp[:,:,:,args.velocityorder[1]].squeeze()
                WAll = flowDataTemp[:,:,:,args.velocityorder[2]].squeeze()
                
                UOrg = numpy.zeros([int(RefDs.Rows), int(RefDs.Columns),len(lstFilesDCM)/30,10], dtype=numpy.double)
                VOrg = numpy.zeros([int(RefDs.Rows), int(RefDs.Columns),len(lstFilesDCM)/30,10], dtype=numpy.double)
                WOrg = numpy.zeros([int(RefDs.Rows), int(RefDs.Columns),len(lstFilesDCM)/30,10], dtype=numpy.double)
                
                UOrg[:,:,:,0] = UAll[:,:,0:30]
                UOrg[:,:,:,1] = UAll[:,:,30:60]
                
                VOrg[:,:,:,0] = VAll[:,:,0:30]
                VOrg[:,:,:,1] = VAll[:,:,30:60]
                
                WOrg[:,:,:,0] = WAll[:,:,0:30]
                WOrg[:,:,:,1] = WAll[:,:,30:60]
                
               # flowDataTemp = numpy.reshape(flowDataTemp, (int(RefDs.Rows), int(RefDs.Columns),len(lstFilesDCM)/3/int(RefDs.CardiacNumberofImages), 3, int(RefDs.CardiacNumberofImages)), order='F')
                #sliceLocationTemp = numpy.reshape(sliceLocationTemp, (len(lstFilesDCM)/3,2, 3), order='F')
                
                #flowDataRevX = numpy.flip(flowDataTemp, 0)
                #flowDataRevZ = numpy.flip(flowDataRevX, 2)
#                sliceLocations = numpy.unique(sliceLocationTemp[:,1])
#                print(len(sliceLocations))
#                sliceLocationsIndeces = (numpy.array(numpy.where(sliceLocationTemp[:,1] == sliceLocations[0])))
#                print(numpy.array(numpy.where(sliceLocationTemp[:,1] == sliceLocations[0])).shape)
#                sys.exit()
                
                
#                for jj in range(0,len(sliceLocations)-1):
#                    #for ii in range(0,int(RefDs.CardiacNumberofImages)-1):
#                        if sliceLocationsIndeces[1,jj] < 300:
#                            UOrg[:,:,jj,ii] = flowDataTemp[:,:,jj,0].squeeze()
#                    
                        
                 #USlice = numpy.sort(sliceLocationTemp[0:300], axis=1)
                  #      print(USlice)
                      
                        #UOrg = flowDataTemp[:,:,ii,0].squeeze()
                        #USliceLocation = sliceLocationTemp[ii,:]
                        #USliceLocationSort = numpy.sort(USliceLocation, axis=1)
             #   sliceUnique = numpy.unique(sliceLocationTemp[0:300,:], axis = 0)
             #   print(sliceUnique)
             #           
                #    elif 299 < ii < 600:
                 #       VOrg = flowDataTemp[:,:,ii,1].squeeze()
                  #      VOrgSliceLocation = sliceLocationTemp[ii,:]
                        
                  #  elif 599 < ii < 900:
                  #      WOrg = flowDataTemp[:,:,ii,2].squeeze()
                  #      WOrgSliceLocation = sliceLocationTemp[ii,:]
                        
                        
#                selector = 0
#                if args.segmentation is False:
#                     ### The combination of x +y and -z and permuted x and y is working. Ali Aug24 2017
#                     UOrg = args.velocitysign[0] * (flowDataTemp[:, :, :, args.velocityorder[0]].squeeze())
#                     VOrg = args.velocitysign[1] * (flowDataTemp[:, :, :, args.velocityorder[1]].squeeze())
#                     WOrg = args.velocitysign[2] * (flowDataTemp[:, :, :, args.velocityorder[2]].squeeze())
#        
                flowCorrected = numpy.zeros([flowDataTemp.shape[0], flowDataTemp.shape[1], flowDataTemp.shape[2]/10,3,10])
#                #if args.eddycurrent:
#                #    flowCorrected = eddyCurrentCorrection(UOrg, VOrg, WOrg, args.randomnoise, args.eddythreshold, args.eddyplane)

                #elif args.randomnoise is not None:
                #    flowCorrected = randNoise(args, UOrg, VOrg, WOrg, args.randomnoise/100, 0, 1)
            
            
                #else:
                flowCorrected[:, :, :,0, :] = UOrg
                flowCorrected[:, :, :,1, :] = VOrg
                flowCorrected[:, :, :,2, :] = WOrg
        
                
                if args.mat:
                    scipy.io.savemat(args.output + "/vel.mat", mdict={'flowData': flowData})
                #print(flowData.shape)
                
                if args.vtk:
    #    if args.segmentation:
            
     #       saveVTKSeg(magDataTemp,False,False, pixel_spc, totalNodes, args.output)
     #   else:
            
                    saveVTK(magDataTemp, flowCorrected,pixel_spc, totalNodes, args.output)
    
                
                


   
          
    #    if args.eddycurrent:
    #        flowCorrected = eddyCurrentCorrection(UOrg, VOrg, WOrg, args.randomnoise, args.eddythreshold, args.eddyplane)

    #    elif args.randomnoise is not None:
    #        flowCorrected = randNoise(args, UOrg, VOrg, WOrg, args.randomnoise/100, 0, 1)
            
            
    #    else:
     #       flowCorrected[:, :, :,0, :] = UOrg
     #       flowCorrected[:, :, :,1, :] = VOrg
     #       flowCorrected[:, :, :,2, :] = WOrg
            
        
        
        
    print(colored.green("\nGetting ready to write files... This takes a little bit of time"))
    
   # magSize = magDataTemp.shape
   #totalNodes = magSize[0] * magSize[1] * magSize[2]

    #if (args.vtk == False and args.mat == False):
     #   print(colored.yellow("We will ONLY save in npy format, since you didnt select your preference! (VTK or MAT)"))
        
    #if not args.segmentation:
     #   numpy.save(args.output +"/FlowData", flowCorrected)    
    #if args.vtk:
    #    if args.segmentation:
            
     #       saveVTKSeg(magDataTemp,False,False, pixel_spc, totalNodes, args.output)
     #   else:
            
      #      saveVTK(magDataTemp, flowCorrected,pixel_spc, totalNodes, args.output)
    
    
    #if args.mat:
    #    if args.segmentation:
    #        with open(args.output + "/FlowData.mat", 'wb') as matlabFile:
    #            scipy.io.savemat(matlabFile, mdict={'magnitude': magDataTemp})
            
    #    else:
     #       with open(args.output + "/FlowData.mat", 'wb') as matlabFile:
      #          scipy.io.savemat(matlabFile, mdict={'velocity': flowData})
       #         scipy.io.savemat(matlabFile, mdict={'magnitude': magDataTemp})
    
    
    
    return RefDs
    def loadPhilips4DUSAsMultiVolume(self, loadable):
        """Load the selection as an Ultrasound, store in MultiVolume
    """

        # get the key info from the "fake" dicom file
        filePath = loadable.files[0]
        ds = dicom.read_file(filePath, stop_before_pixels=True)
        columns = ds.Columns
        rows = ds.Rows
        slices = ds[(0x3001, 0x1001)].value  # private tag!
        spacing = (
            ds.PhysicalDeltaX * 10,
            ds.PhysicalDeltaY * 10,
            ds[(0x3001, 0x1003)].value * 10  # private tag!
        )
        frames = int(ds.NumberOfFrames)
        imageComponents = frames

        # create the correct size and shape vtkImageData
        image = vtk.vtkImageData()
        imageShape = (slices, rows, columns, frames)
        image.SetDimensions(columns, rows, slices)
        image.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, imageComponents)
        from vtk.util.numpy_support import vtk_to_numpy
        imageArray = vtk_to_numpy(
            image.GetPointData().GetScalars()).reshape(imageShape)

        # put the data in a numpy array
        # -- we need to read the file as raw bytes
        pixelShape = (frames, slices, rows, columns)
        pixels = numpy.fromfile(filePath, dtype=numpy.uint8)
        pixelSize = reduce(lambda x, y: x * y, pixelShape)
        headerSize = len(pixels) - pixelSize
        pixels = pixels[headerSize:]
        pixels = pixels.reshape(pixelShape)

        slicer.modules.imageArray = imageArray
        slicer.modules.pixels = pixels

        # copy the data from numpy to vtk (need to shuffle frames to components)
        for frame in range(frames):
            imageArray[:, :, :, frame] = pixels[frame]

        # create the multivolume node and display it
        multiVolumeNode = slicer.vtkMRMLMultiVolumeNode()

        multiVolumeNode.SetScene(slicer.mrmlScene)

        multiVolumeDisplayNode = slicer.mrmlScene.CreateNodeByClass(
            'vtkMRMLMultiVolumeDisplayNode')
        multiVolumeDisplayNode.SetReferenceCount(
            multiVolumeDisplayNode.GetReferenceCount() - 1)
        multiVolumeDisplayNode.SetScene(slicer.mrmlScene)
        multiVolumeDisplayNode.SetDefaultColorMap()
        slicer.mrmlScene.AddNode(multiVolumeDisplayNode)

        multiVolumeNode.SetAndObserveDisplayNodeID(
            multiVolumeDisplayNode.GetID())
        multiVolumeNode.SetAndObserveImageData(image)
        multiVolumeNode.SetNumberOfFrames(frames)
        multiVolumeNode.SetName(loadable.name)
        slicer.mrmlScene.AddNode(multiVolumeNode)

        #
        # automatically select the volume to display
        #
        appLogic = slicer.app.applicationLogic()
        selNode = appLogic.GetSelectionNode()
        selNode.SetReferenceActiveVolumeID(multiVolumeNode.GetID())
        appLogic.PropagateVolumeSelection()

        return multiVolumeNode
def dicom_to_array(filename):
    d = dicom.read_file(filename)
    a = d.pixel_array
    return np.array(a)
示例#54
0
def make_svs_anatomical(population, workspace, voxel_name):

    for subject in population:

        subject_dir = os.path.join(workspace, subject)
        dicom_dir   = os.path.join(subject_dir, 'DICOM')
        svs_dir     = os.path.join(subject_dir, 'SVS')
        nifti_dir   = mkdir_path(os.path.join(subject_dir, 'NIFTI'))

        ########## Get MP2RAGE UNI
        if not os.path.isfile( os.path.join(nifti_dir, 'ANATOMICAL.nii')):
            print 'Converting MP2RAGE '

            dicoms = [os.path.join(dicom_dir, dicom) for dicom in os.listdir(dicom_dir)]
            T1_list = []

            for dicom in dicoms:
                try:

                    dcm_read = pydicom.read_file(dicom, force=True)
                    sequence = dcm_read.SeriesDescription
                except AttributeError:
                    continue

                if 'mp2rage_p3_602B_UNI_Images' in sequence:
                    T1_list.append(dicom)

            # convert T1 anatomical to NIFTI with SPM
            print 'Converting Dicom to Nifti for %s' % subject
            spm_dicom_convert = spmu.DicomImport()
            spm_dicom_convert.inputs.format = 'nii'
            spm_dicom_convert.inputs.in_files = T1_list
            spm_dicom_convert.inputs.output_dir = nifti_dir
            spm_dicom_convert.run()

            # rename output file
            os.system('mv %s/*nii %s/ANATOMICAL.nii' %(nifti_dir, nifti_dir))


        # make svs mask
        rda =[]
        if not os.path.isfile(os.path.join(svs_dir, voxel_name, 'RDA', '.nii')):
            for root, dirs, files, in os.walk(os.path.join(svs_dir, voxel_name, 'RDA'), topdown=False):
                for name in files:
                    if 'supp' in name and 'edit1' in name:
                        rda.append(os.path.join(name))

            if rda is []:
                print 'RDA metabolite data does not exist for subject %s' % subject


            T1Path = os.path.join(subject_dir, 'NIFTI' + '/')
            T1Image = 'ANATOMICAL.nii'
            svs_path = os.path.join(svs_dir, voxel_name, 'RDA' + '/')
            svs_file = rda[0]

            matlab_command = ['matlab', '--version', '8.2', '-nodesktop', '-nosplash', '-nojvm',
                              '-r "RDA_TO_NIFTI(\'%s\', \'%s\', \'%s\', \'%s\') ; quit;"'
                              % (T1Path, T1Image, svs_path, svs_file)]
            subprocess.call(matlab_command)

            os.system('mv %s/*Mask.nii %s' % (nifti_dir, os.path.join(svs_dir, voxel_name, 'RDA')))
            os.system('mv %s/*coord.txt %s' % (nifti_dir, os.path.join(svs_dir, voxel_name, 'RDA')))
method = "1-localizer"
method = "3-ep2d_diff_M128_b0_1000_DIN_ADC"
method = "6-t2_spc_ns_sag_p2_iso"
method = "7-spctra"
method = "4-t2_tse_tra_512_5mm"
method = "2-ep2d_diff_M128_b0_1000_DIN"
method = "5-t1_fl2d_tra"

baseName = base + "/" + patient + "/" + patient + "-" + date + "/" + method

if __name__ == "__main__":
    print("Hallo Gallo")
    print(baseName)
    files = os.listdir(baseName)
    c = 1
    for file in files:
        print(file)
        try:
            plan = dicom.read_file(baseName + "/" + file)
            plt.subplot(5, 5, c)
            pix = plan.pixel_array
            print(plan.InstanceNumber)
            plt.title("In Num " + str(plan.InstanceNumber))
            plt.imshow(pix)
            c += 1
        except:
            print "Unexpected error:", sys.exc_info()[0]

    plt.draw()
    plt.waitforbuttonpress()
示例#56
0
 def _read_dicom_image(self, filename):
     d = dicom.read_file(filename)
     img = d.pixel_array
     return np.array(img)
示例#57
0
def load_by_type(path, file_type, contains=""):
    return [
        dicom.read_file(os.path.join(path, s)) for s in os.listdir(path)
        if s.startswith(file_type) and (contains in s)
    ]
    def loadPhilips4DUSAsSequence(self, loadable):
        """Load the selection as an Ultrasound, store in a Sequence node
    """

        # get the key info from the "fake" dicom file
        filePath = loadable.files[0]
        ds = dicom.read_file(filePath, stop_before_pixels=True)
        columns = ds.Columns
        rows = ds.Rows
        slices = ds[(0x3001, 0x1001)].value  # private tag!
        spacing = (
            ds.PhysicalDeltaX * 10,
            ds.PhysicalDeltaY * 10,
            ds[(0x3001, 0x1003)].value * 10  # private tag!
        )
        frames = int(ds.NumberOfFrames)
        imageComponents = frames
        frameTimeMsec = ds.FrameTime

        pixelShape = (frames, slices, rows, columns)
        pixelSize = reduce(lambda x, y: x * y, pixelShape)
        totalFileSize = os.path.getsize(filePath)
        headerSize = totalFileSize - pixelSize

        outputSequenceNode = slicer.vtkMRMLSequenceNode()

        for frame in range(frames):

            imgReader = vtk.vtkImageReader()
            imgReader.SetFileDimensionality(3)
            imgReader.SetFileName(filePath)
            imgReader.SetNumberOfScalarComponents(1)
            imgReader.SetDataScalarTypeToUnsignedChar()
            imgReader.SetDataExtent(0, columns - 1, 0, rows - 1, 0, slices - 1)
            imgReader.SetHeaderSize(headerSize +
                                    frame * slices * rows * columns)
            imgReader.FileLowerLeftOn()
            imgReader.Update()

            outputNode = slicer.vtkMRMLScalarVolumeNode()
            outputNode.SetAndObserveImageData(imgReader.GetOutput())
            outputNode.SetSpacing(spacing)

            timeStampSec = "{:.3f}".format(frame * frameTimeMsec * 0.001)
            outputSequenceNode.SetDataNodeAtValue(outputNode, timeStampSec)

        outputSequenceNode.SetName(
            slicer.mrmlScene.GenerateUniqueName(loadable.name))
        slicer.mrmlScene.AddNode(outputSequenceNode)

        # Create storage node that allows saving node as nrrd
        outputSequenceStorageNode = slicer.vtkMRMLVolumeSequenceStorageNode()
        slicer.mrmlScene.AddNode(outputSequenceStorageNode)
        outputSequenceNode.SetAndObserveStorageNodeID(
            outputSequenceStorageNode.GetID())

        if not hasattr(loadable,
                       'createBrowserNode') or loadable.createBrowserNode:
            # Add a browser node and show the volume in the slice viewer for user convenience
            outputSequenceBrowserNode = slicer.vtkMRMLSequenceBrowserNode()
            outputSequenceBrowserNode.SetName(
                slicer.mrmlScene.GenerateUniqueName(
                    outputSequenceNode.GetName() + ' browser'))
            slicer.mrmlScene.AddNode(outputSequenceBrowserNode)
            outputSequenceBrowserNode.SetAndObserveMasterSequenceNodeID(
                outputSequenceNode.GetID())
            masterOutputNode = outputSequenceBrowserNode.GetProxyNode(
                outputSequenceNode)

            # Automatically select the volume to display
            appLogic = slicer.app.applicationLogic()
            selNode = appLogic.GetSelectionNode()
            selNode.SetReferenceActiveVolumeID(masterOutputNode.GetID())
            appLogic.PropagateVolumeSelection()
            appLogic.FitSliceToAll()
            slicer.modules.sequencebrowser.setToolBarActiveBrowserNode(
                outputSequenceBrowserNode)

            # create Subject hierarchy nodes for the loaded series
            self.addSeriesInSubjectHierarchy(loadable, masterOutputNode)

        return outputSequenceNode
示例#59
0
    #    continue
    # print ("Up folder name ", i)
    if os.path.isdir(path + "/" + i):
        print("Current folder ", (path + "/" + i))

        for fname in os.listdir(path + "/" + i):
            if fname.endswith(tuple(f_ext)):
                next_level = path + "/" + i + "/" + fname
                break

        splitup = next_level.split('/')

        list_no = len(os.listdir(path + "/" + i))
        print("Number of files", list_no)

        dcmhdr = dicom.read_file(next_level)
        filenum = int(dcmhdr['0020', '0011'].value)
        filename = dcmhdr['0008', '103e'].value
        #TR = dcmhdr['0018', '0080'].value # Repetition Time
        #TE = dcmhdr['0018', '0081'].value # Echo Time

        # filename given example: fMRI_Resting_1_AP, T1W_MPR
        print("filename", filename)
        c_folder.append(filename)
        #print ("Repetition Time  TR ", TR)
        #print ("Echo Time TE ", TE)

        # DICOM directory name (long number)
        mapoutname = str(splitup[6])
        print("folder number", mapoutname)
        """
示例#60
0
for dir_name, subdir_list, file_list in os.walk(path):
  for filename in file_list:
    if ".dcm" in filename.lower():
      print filename
      if "ct" in dir_name.lower():
        ct_files.append(os.path.join(dir_name,filename))
      if "rtst" in dir_name.lower():
        rtst_files.append(os.path.join(dir_name,filename))

if 1:
  print 'Extracting structure labels...',
  sys.stdout.flush()
  f = open('structure.dat','w')
  sys.stdout.flush()
  for file in rtst_files:
    dcm_data = dicom.read_file(file)
    patient_id = dcm_data[0x10, 0x20].value
    structure_set_roi_sequence = dcm_data[0x3006,0x20].value
    for i, structure_set_roi in enumerate(structure_set_roi_sequence):
      if structure_set_roi[0x3006, 0x0022].value != i+1:
        print 'Script cannot accomodate your dicom data. Exiting now.'
        exit()
    structure_line = patient_id+'|'+'|'.join( [ elem[0x3006,0x26].value for elem in structure_set_roi_sequence ])
    f.write(structure_line+'\n')
  print 'DONE'
  sys.stdout.flush()
  f.close()

if 1:
  print 'Extracting slice data...'
  sys.stdout.flush()