Esempio n. 1
0
    def _run_interface(self, runtime):
        if not isdefined(self.inputs.output_file):
            self.inputs.output_file = self._gen_output(self.inputs.in_file,
                                                       self._suffix)
        print self.inputs.in_file
        print self.inputs.reference
        header = self.inputs.header
        pet = volumeFromFile(self.inputs.in_file)
        reference = volumeFromFile(self.inputs.reference)
        out = volumeLikeFile(self.inputs.reference, self.inputs.output_file)
        ndim = len(pet.data.shape)

        vol = pet.data
        if ndim > 3:
            try:
                time_frames = [
                    float(s) for s, e in header['Time']["FrameTimes"]["Values"]
                ]
            except ValueError:
                time_frames = [1.]

            vol = simps(pet.data, time_frames, axis=4)

        idx = reference.data > 0
        ref = np.mean(vol[idx])
        print "SUVR Reference = ", ref
        vol = vol / ref
        out.data = vol
        out.writeFile()
        out.closeVolume()

        return runtime
Esempio n. 2
0
def distance(pet_fn, mri_fn, t1_brain_fn, pet_brain_fn, dist_f_list):
    pet = pyminc.volumeFromFile(pet_fn)
    mri = pyminc.volumeFromFile(mri_fn)
    t1_mask = pyminc.volumeFromFile(t1_brain_fn)
    pet_mask = pyminc.volumeFromFile(pet_brain_fn)

    pet_data = pet.data.flatten()
    mri_data = mri.data.flatten()
    t1_mask_data = t1_mask.data.flatten()
    pet_mask_data = pet_mask.data.flatten()

    n = len(pet_data)
    overlap = t1_mask_data * pet_mask_data
    masked_pet_data = [pet_data[i] for i in range(n) if int(overlap[i]) == 1]
    masked_mri_data = [mri_data[i] for i in range(n) if int(overlap[i]) == 1]
    del pet
    del mri
    del t1_mask
    del pet_mask
    del t1_mask_data
    del pet_mask_data
    dist_list = []
    for dist_f in dist_f_list:
        dist_list.append(dist_f(masked_pet_data, masked_mri_data))
    return (dist_list)
Esempio n. 3
0
def getFinestResolution(inSource):
    """
        This function will return the highest (or finest) resolution 
        present in the inSource file.     
    """
    imageResolution = []
    if isFileHandler(inSource):
        # make sure that pyminc does not complain about non-existing files. During the
        # creation of the overall compute graph the following file might not exist. In
        # that case, use the inputFileName, or raise an exception
        if (isfile(inSource.getLastBasevol())):
            imageResolution = volumeFromFile(
                inSource.getLastBasevol()).separations
        elif (isfile(inSource.inputFileName)):
            imageResolution = volumeFromFile(
                inSource.inputFileName).separations
        else:
            # neither the last base volume, nor the input file name exist at this point
            # this could happen when we evaluate an average for instance
            raise
    else:
        imageResolution = volumeFromFile(inSource).separations

    # the abs function does not work on lists... so we have to loop over it.  This
    # to avoid issues with negative step sizes.  Initialize with first dimension
    finestRes = abs(imageResolution[0])
    for i in range(1, len(imageResolution)):
        if (abs(imageResolution[i]) < finestRes):
            finestRes = abs(imageResolution[i])

    return finestRes
def getFinestResolution(inSource):
    """
        This function will return the highest (or finest) resolution 
        present in the inSource file.     
    """
    imageResolution = []
    if isFileHandler(inSource):
        # make sure that pyminc does not complain about non-existing files. During the
        # creation of the overall compute graph the following file might not exist. In
        # that case, use the inputFileName, or raise an exception
        if(isfile(inSource.getLastBasevol())):
            imageResolution = volumeFromFile(inSource.getLastBasevol()).separations
        elif(isfile(inSource.inputFileName)):
            imageResolution = volumeFromFile(inSource.inputFileName).separations
        else:
            # neither the last base volume, nor the input file name exist at this point
            # this could happen when we evaluate an average for instance
            raise
    else: 
        imageResolution = volumeFromFile(inSource).separations
    
    # the abs function does not work on lists... so we have to loop over it.  This 
    # to avoid issues with negative step sizes.  Initialize with first dimension
    finestRes = abs(imageResolution[0])
    for i in range(1, len(imageResolution)):
        if(abs(imageResolution[i]) < finestRes):
            finestRes = abs(imageResolution[i])
    
    return finestRes
Esempio n. 5
0
    def _run_interface(self, runtime):
        header = json.load(open(self.inputs.header, "r"))
        if not isdefined(self.inputs.out_file):
            self.inputs.out_file = self._gen_output(self.inputs.in_file,
                                                    self._suffix)

        try:
            dose = float(header["RadioChem"]["InjectedRadioactivity"])
        except ValueError:
            print(
                "Error: Could not find injected dose in subject's header. Make sure subject has a .json header in BIDS format with [RadioChem][InjectedRadioactivity]"
            )
            exit(1)

        try:
            weight = float(header["Info"]["BodyWeight"])
        except ValueError:
            print(
                "Error: Could not find subject's body weight in header. Make sure subject has a .json header in BIDS format with [Info][BodyWeight]"
            )
            exit(1)
        pet = volumeFromFile(self.inputs.in_file)
        reference = volumeFromFile(self.inputs.reference)
        out = volumeLikeFile(self.inputs.reference, self.inputs.out_file)
        ndim = len(pet.data.shape)

        vol = pet.data
        if ndim > 3:
            dims = pet.getDimensionNames()
            i = dims.index('time')

            if not isdefined(self.inputs.start_time):
                start_time = 0
            else:
                start_time = self.inputs.start_time

            if not isdefined(self.inputs.end_time):
                end_time = header['Time']['FrameTimes']['Values'][-1][1]
            else:
                end_time = self.inputs.end_time

            #time_frames = time_indices = []
            #for i in range(vol.shape[i]) :
            #    s=header['Time']["FrameTimes"]["Values"][i][0]
            #    e=header['Time']["FrameTimes"]["Values"][i][1]
            #    print(i)
            #    if s >= start_time and e <= end_time :
            #        time_indices.append(i)
            #        time_frames.append(float(e) - float(s)  )
            #print(time_indices)
            #print(time_frames)
            time_frames = [
                float(s) for s, e in header['Time']["FrameTimes"]["Values"]
            ]
            vol = simps(pet.data, time_frames, axis=i)
        vol = vol / (dose / weight)
        out.data = vol
        out.writeFile()
        out.closeVolume()
        return runtime
 def set_params(stage: CmdStage):
     img_pyminc = pyminc.volumeFromFile(img.path)
     ref_pyminc = pyminc.volumeFromFile(ref.path)
     count = np.maximum(ref_pyminc.data.count, img_pyminc.data.count)
     sum = ref_pyminc.data.count[0] + img_pyminc.data.count[0]
     for index, arg in enumerate(stage.cmd):
         stage.cmd[index] = arg.format(start='0,0,0,',
                                       count='%s,%s,%s' %
                                       (sum, count[1], count[2]))
Esempio n. 7
0
def read_minc_image(minc_filename):

    split = minc_filename.split(',')
    minc_vol = pyminc.volumeFromFile(split[0])
    vol = minc_vol.data
    vol = np.expand_dims(vol, axis=0)

    if (np.size(split) > 1):
        for i in range(1, np.size(split)):
            minc_vol = pyminc.volumeFromFile(split[i])
            vol = np.concatenate((vol, np.expand_dims(minc_vol.data, axis=0)),
                                 axis=0)
    return vol
Esempio n. 8
0
    def _run_interface(self, runtime):
        in_file = self.inputs.in_file
        float_val = self.inputs.float_val
        tol = self.inputs.tol
        dim_to_interpolate = self.inputs.dim_to_interpolate

        self.out_files = []
        volume = volumeFromFile(in_file)
        data = np.copy(volume.data)
        volume.closeVolume()

        data = select_structure(data, float_val, tol)

        _, base, _ = split_filename(in_file)

        assert dim_to_interpolate in [0, 1, 2]
        assert len(data.shape) == 3

        if dim_to_interpolate == 0:
            slices = [data[i, :, :] for i in range(data.shape[0])]
        elif dim_to_interpolate == 1:
            slices = [data[:, i, :] for i in range(data.shape[1])]
        elif dim_to_interpolate == 2:
            slices = [data[:, :, i] for i in range(data.shape[2])]

        for (i, s) in enumerate(slices):
            fname = 'slice_%08d.npz' % i
            np.savez_compressed(fname, s)
            self.out_files.append(os.path.abspath(fname))

        return runtime
Esempio n. 9
0
    def _run_interface(self, runtime):
        in_files = self.inputs.in_files
        labels = self.inputs.labels

        self.out_file = os.path.abspath('merged.mnc')

        v = volumeFromDescription(self.out_file,
                                  self.inputs.dimension_names,
                                  self.inputs.sizes,
                                  self.inputs.starts,
                                  self.inputs.separations,
                                  volumeType='ubyte')

        components = {}

        for (i, lab) in enumerate(labels):
            in_volume = volumeFromFile(in_files[i])
            components[i] = np.copy(in_volume.data.astype('uint8'))
            in_volume.closeVolume()

            v.data += lab * components[
                i]  # FIXME We shouldn't be adding things here... or should we?

        for i in range(len(labels)):
            for j in range(i + 1, len(labels)):
                assert not overlap(components[i], components[j])

        v.writeFile()
        v.closeVolume()

        return runtime
def perfusion_volumes(perfusion_file, l):
    cnt = 0
    ## nc_data_type=py_minc.NC_BYTE is writing a byte (floating point) but we want the voxel intensities to be int labels
    ## nc_data_type=py_minc.NC_SHORT is writing a short integer data and we want the voxel intensities to be int labels
    #perfusion_pattern = py_minc.ArrayVolume(perfusion_file, nc_data_type=py_minc.NC_BYTE )# without this always [z,y,x], with ,dim_names=py_minc.FILE_ORDER_DIMENSION_NAMES order as the image
    #sizes = perfusion_pattern.get_sizes()
    #print sizes[0], sizes[1], sizes[2]
    #spacing = perfusion_pattern.get_separations()
    #print spacing[0], spacing[1], spacing[2]

    perfusion_pattern = pymincf.volumeFromFile(perfusion_file,
                                               dtype='ubyte')  #ushort
    perfusion_pattern.openFile()
    sizes = perfusion_pattern.getSizes()
    spacing = perfusion_pattern.getSeparations()

    for z_vox in range(sizes[0]):
        for y_vox in range(sizes[1]):
            for x_vox in range(sizes[2]):
                #if int(round(perfusion_pattern.array[z_vox,y_vox,x_vox]))==l:
                if perfusion_pattern[z_vox, y_vox, x_vox] == l:
                    cnt += 1
    #print cnt
    perfusion_pattern.closeVolume()
    return cnt * spacing[0] * spacing[1] * spacing[2]
Esempio n. 11
0
    def _parse_inputs(self, skip=None):
        self.inputs.output_file = self.inputs.in_file  #
        header = self.inputs.header
        if skip is None:
            skip = []
        data = json.load(open(header, "rb"))

        vol = pyminc.volumeFromFile(self.inputs.in_file)
        dims = vol.getDimensionNames()
        if 'time' in dims:
            #See if there is a start time defined, else set to 0
            try:
                data["time"]["start"][0]
                self.inputs.tstart = data["time"]["start"][0]
            except KeyError:
                self.inputs.tstart = 0

            try:
                data["time"]["start"][0]
                self.inputs.tstep = data["time"]["step"][0]
            except KeyError:
                self.inputs.tstep = 1

        if not self.inputs.time_only:
            self.inputs.zstart = data["zspace"]["start"][0]
            self.inputs.ystart = data["yspace"]["start"][0]
            self.inputs.xstart = data["xspace"]["start"][0]
            self.inputs.zstep = data["zspace"]["step"][0]
            self.inputs.ystep = data["yspace"]["step"][0]
            self.inputs.xstep = data["xspace"]["step"][0]

        return super(FixHeaderCommand, self)._parse_inputs(skip=skip)
Esempio n. 12
0
    def readFile(self):
        """Read the pixel data and dimensions from file."""
        if self.file_type == 'minc':
            self.minc = pyminc.volumeFromFile(self.file_path, labels=True)
            self.nifti = None
            self.pixdim = np.abs(np.array(self.minc.separations), dtype=float)
            self.data = np.array(self.minc.data, dtype=int)

            # MINC files apparently sometimes store the x, y, z dimensions in strange orders. Try to fix this such that the data and pixdim arrays are ordered (x, y, z)
            desired_dimnames = ['xspace', 'yspace', 'zspace']
            transpose_axes = [0, 0, 0] # generate 'axes' argument for numpy.transpose(), to rearrange the data.
            if self.minc.dimnames != desired_dimnames:
                # Reorder the pixdim and data arrays.
                new_pixdim = np.zeros(shape=(3,), dtype=float)
                for desired_index, desired_dimname in enumerate(desired_dimnames):
                    current_index = self.minc.dimnames.index(desired_dimname)
                    new_pixdim[desired_index] = self.pixdim[current_index]
                    transpose_axes[desired_index] = current_index
                self.pixdim = new_pixdim
                self.data = np.transpose(self.data, axes=transpose_axes)

        elif self.file_type == 'nifti':
            self.minc = None
            self.nifti = nib.load(self.file_path)
            self.pixdim = np.array(self.nifti.header['pixdim'][1:4], dtype=float)
            self.data = np.array(self.nifti.get_fdata(), dtype=int)

        # Combine unique labels if requested.
        if self.combine_labels:
            self.data[self.data != 0] = 1 # Set all nonzero values to 1.
 def set_memory(st, mem_cfg):
     # see comments re: mincblur memory configuration
     voxels = reduce(mul, volumeFromFile(source.path).getSizes())
     mem_per_voxel = (mem_cfg.mem_per_voxel_coarse
                      if 0 in conf.convergence.iterations[-1:]  #-2?
                      # yikes ... this parsing should be done earlier
                      else mem_cfg.mem_per_voxel_fine)
     st.setMem(mem_cfg.base_mem + voxels * mem_per_voxel)
Esempio n. 14
0
def set_memory(st, source: MincAtom, conf: ANTSConf, mem_cfg):
    # see comments re: mincblur memory configuration
    voxels = reduce(mul, volumeFromFile(source.path).getSizes())
    mem_per_voxel = (mem_cfg.mem_per_voxel_coarse
                     if int(conf.iterations.split('x')[-1]) == 0
                     # yikes ... this parsing should be done earlier
                     else mem_cfg.mem_per_voxel_fine)
    st.setMem(mem_cfg.base_mem + voxels * mem_per_voxel)
Esempio n. 15
0
File: qc.py Progetto: bilgelm/APPIAN
def distance(pet_fn, mri_fn, t1_brain_fn, pet_brain_fn, dist_f_list):
    pet = pyminc.volumeFromFile(pet_fn)
    mri = pyminc.volumeFromFile(mri_fn)
    t1_mask= pyminc.volumeFromFile(t1_brain_fn)
    pet_mask= pyminc.volumeFromFile(pet_brain_fn)


    pet_data=pet.data.flatten()
    mri_data=mri.data.flatten()
    t1_mask_data=t1_mask.data.flatten()
    pet_mask_data=pet_mask.data.flatten()
    
    if not pet.data.shape == mri.data.shape : 
        print("Dimension mismatch between pet and mri:")
        print(pet_fn, pet_mask.data.shape) 
        print(mri_fn, t1_mask.data.shape)
        exit(1)

    if not t1_mask_data.shape == pet_mask_data.shape : 
        print("Dimension mismatch between masks pet and mri:")
        print(pet_brain_fn, pet_mask.data.shape) 
        print(t1_brain_fn, t1_mask.data.shape)
        exit(1)

    overlap = t1_mask_data * pet_mask_data
    overlap[ overlap >= 1 ] = 1
    #temp_qc(np.array(pet.data), np.array(mri.data), np.array(t1_mask.data+pet_mask.data), pet_mask.data, os.path.basename(pet_fn)+'.png')
    #print(pet_fn)
    #print(mri_fn)
    #print(t1_brain_fn)
    #print(pet_brain_fn)
    
    n=overlap.shape[0]
    masked_pet_data = [ pet_data[i] for i in range(n) if int(overlap[i])  == 1 ] 
    masked_mri_data = [ mri_data[i] for i in range(n) if  int(overlap[i]) == 1 ] 
    del pet
    del mri
    del t1_mask
    del pet_mask
    del t1_mask_data
    del pet_mask_data
    dist_list=[]
    for dist_f in dist_f_list:
        dist_list.append(dist_f(masked_pet_data, masked_mri_data))
    return(dist_list)
Esempio n. 16
0
    def _run_interface(self, runtime):
        if not isdefined(self.inputs.out_file):
            self.inputs.out_file = self._gen_output(self.inputs.in_file,
                                                    self._suffix)
        header = json.load(open(self.inputs.header, "r"))
        pet = volumeFromFile(self.inputs.in_file)
        reference = volumeFromFile(self.inputs.reference)
        out = volumeLikeFile(self.inputs.reference, self.inputs.out_file)
        ndim = len(pet.data.shape)

        vol = pet.data
        if ndim > 3:

            dims = pet.getDimensionNames()
            i = dims.index('time')

            if not isdefined(self.inputs.start_time):
                start_time = 0
            else:
                start_time = self.inputs.start_time

            if not isdefined(self.inputs.end_time):
                end_time = header['Time']['FrameTimes']['Values'][-1][1]
            else:
                end_time = self.inputs.end_time

            try:
                #time_frames = [ float(s) for s,e in  header['Time']["FrameTimes"]["Values"] ]
                time_frames = [
                    float(s) for s, e in header['Time']["FrameTimes"]["Values"]
                    if s >= start_time and e <= end_time
                ]
            except ValueError:
                time_frames = [1.]
            vol = simps(pet.data, time_frames, axis=i)

        idx = reference.data > 0
        ref = np.mean(vol[idx])
        print "SUVR Reference = ", ref
        vol = vol / ref
        out.data = vol
        out.writeFile()
        out.closeVolume()

        return runtime
Esempio n. 17
0
 def set_memory(st, mem_cfg):
     # see comments re: mincblur memory configuration
     voxels = reduce(mul, volumeFromFile(source.path).getSizes())
     mem_per_voxel = (
         mem_cfg.mem_per_voxel_coarse
         if 0 in conf.convergence.iterations[-1:]  #-2?
         # yikes ... this parsing should be done earlier
         else mem_cfg.mem_per_voxel_fine)
     st.setMem(mem_cfg.base_mem + voxels * mem_per_voxel)
Esempio n. 18
0
def check_overlap((f_i, f_j,)):
    data_i = volumeFromFile(f_i).data
    data_j = volumeFromFile(f_j).data

    data_i[np.where(data_i > 0)] = 1
    data_j[np.where(data_j > 0)] = 1

    data_i = data_i.astype('uint8')
    data_j = data_j.astype('uint8')

    for k in range(data_i.shape[1]):
        if overlap(data_i[:, k, :], data_j[:, k, :]):
            print (f_i, f_j)
            return (f_i, f_j)

    print f_i, f_j, None

    return None
Esempio n. 19
0
def set_memory(st, source: MincAtom, conf: ANTSConf, mem_cfg):
    # see comments re: mincblur memory configuration
    voxels = reduce(mul, volumeFromFile(source.path).getSizes())
    mem_per_voxel = (
        mem_cfg.mem_per_voxel_coarse
        if int(conf.iterations.split('x')[-1]) == 0
        # yikes ... this parsing should be done earlier
        else mem_cfg.mem_per_voxel_fine)
    st.setMem(mem_cfg.base_mem + voxels * mem_per_voxel)
Esempio n. 20
0
def write_minc_image(array, example_image_filename, output_name):

    in_vol = pyminc.volumeFromFile(example_image_filename)

    out_vol = pyminc.volumeFromInstance(in_vol, output_name)
    out_vol.data = np.squeeze(array)
    out_vol.writeFile()

    in_vol.closeVolume()
    out_vol.closeVolume()
def getFinestResolution(inSource):
    """
        This function will return the highest (or finest) resolution 
        present in the inSource file.     
    """
    imageResolution = []
    if isFileHandler(inSource):
        imageResolution = volumeFromFile(inSource.getLastBasevol()).separations
    else: 
        imageResolution = volumeFromFile(inSource).separations
    
    # the abs function does not work on lists... so we have to loop over it.  This 
    # to avoid issues with negative step sizes.  Initialize with first dimension
    finestRes = abs(imageResolution[0])
    for i in range(1, len(imageResolution)):
        if(abs(imageResolution[i]) < finestRes):
            finestRes = abs(imageResolution[i])
    
    return finestRes
    
Esempio n. 22
0
def get_nhdr_info(filename):
    infile = pyminc.volumeFromFile(
        filename
    )  # mincreshape -dimorder time,xspace,yspace,zspace dyn.mnc dyn_reorder.mnc -clobber
    img = np.array(infile.data)
    infile.closeVolume()
    #b = b.flatten('F').reshape(20,192,192,35)
    header = {}
    header['type'] = infile.dtype
    header['dimension'] = infile.ndims
    header['space'] = 'right-anterior-superior'  # Hardcoded!!
    header['sizes'] = np.array(infile.data.shape)
    header['endian'] = 'little'
    header['encoding'] = 'gzip'
    header['measurement frame'] = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
    if infile.ndims == 4:
        header['space directions'] = np.array([[np.nan, np.nan, np.nan],
                                               [infile.separations[1], 0, 0],
                                               [0, infile.separations[2], 0],
                                               [0, 0, infile.separations[3]]])
        header['kinds'] = ['list', 'domain', 'domain', 'domain']
        header['space origin'] = np.array(
            [infile.starts[1], infile.starts[2], infile.starts[3]])
        TE = str(
            float(
                os.popen('mincinfo -attvalue acquisition:echo_time ' +
                         filename + ' -error_string noTE').read().rstrip()) *
            1000)
        header['MultiVolume.DICOM.EchoTime'] = TE
        flip = str(
            float(
                os.popen('mincinfo -attvalue acquisition:flip_angle ' +
                         filename + ' -error_string noKVP').read().rstrip()))
        header['MultiVolume.DICOM.FlipAngle'] = flip
        TR = str(
            float(
                os.popen('mincinfo -attvalue acquisition:repetition_time ' +
                         filename + ' -error_string noKVP').read().rstrip()) *
            1000)
        header['MultiVolume.DICOM.RepetitionTime'] = TR
        header['MultiVolume.FrameIdentifyingDICOMTagName'] = 'AcquisitionTime'
        header['MultiVolume.FrameIdentifyingDICOMTagUnits'] = 'ms'
        header[
            'MultiVolume.FrameLabels'] = '0.0,7585.0,15167.5,22750.0,30332.5,37917.5,45500.0,53082.5,60665.0,68250.0,75832.5,83415.0,90997.5,98582.5,106165.0,113747.5,121330.0,128915.0,136497.5,144080.0,151662.5,159247.5,166830.0,174412.5,181995.0,189580.0,197162.5,204745.0,212327.5,219912.5,227495.0,235077.5,242660.0,250245.0,257827.5'
        header['MultiVolume.NumberOfFrames'] = '35'
    if infile.ndims == 3:
        header['space directions'] = np.array([[infile.separations[0], 0, 0],
                                               [0, infile.separations[1], 0],
                                               [0, 0, infile.separations[2]]])
        header['kinds'] = ['domain', 'domain', 'domain']
        header['space origin'] = np.array(
            [infile.starts[0], infile.starts[1], infile.starts[2]])
    return img, header
Esempio n. 23
0
def get_mask_list(sourceDir, ROIMask):
    gen = os.walk(sourceDir)
    for dirName, subdirList, fileList in gen:
        for f in fileList:
            if ROIMask[0] in f:
                #Load in volume and get unique values
                mask = pyminc.volumeFromFile(dirName + os.sep + f)
                mask_flat = mask.data.flatten()
                label = [str(int(round(i))) for i in np.unique(mask_flat)]
                if 0 in label: label.remove(0)
                return (label)
    return ([1])
Esempio n. 24
0
def pvc_mse(pvc_fn, pve_fn, fwhm):
    pvc = pyminc.volumeFromFile(pvc_fn)
    pve = pyminc.volumeFromFile(pve_fn)
    mse = 0
    if len(pvc.data.shape) > 3:  #if volume has more than 3 dimensions
        t = int(pvc.sizes[0] / 2)
        #for t in range(pvc.sizes[0]):
        pve_frame = pve.data[t, :, :, :]
        pvc_frame = pvc.data[t, :, :, :]

        n = np.sum(pve.data[t, :, :, :])  # np.prod(pve.data.shape[0:4])
        pvc_blur = gaussian_filter(pvc_frame, fwhm)
        m = np.sum(np.sqrt((pve_frame - pvc_blur)**2))
        mse += m
        print t, m
    else:  #volume has 3 dimensions
        n = np.sum(pve.data)  # np.prod(pve.data.shape[0:3])
        pvc_blur = gaussian_filter(pvc.data, fwhm)
        m = np.sum(np.sqrt((pve.data - pvc_blur)**2))
        mse += m
    mse = -mse / n  #np.sum(pve.data)
    print("PVC MSE:", mse)
    return mse
Esempio n. 25
0
 def __init__(self, filesToResample, resolution):
     """During initialization make sure all files are resampled
        at resolution we'd like to use for each pipeline stage
     """
     self.p = Pipeline()
     
     for FH in filesToResample:
         dirForOutput = self.getOutputDirectory(FH)
         currentRes = volumeFromFile(FH.getLastBasevol()).separations
         if not abs(abs(currentRes[0]) - abs(resolution)) < 0.01:
             crop = ma.autocrop(resolution, FH, defaultDir=dirForOutput)
             self.p.addStage(crop)
             mask = FH.getMask()
             if mask:
                 #Need to resample the mask as well.
                 cropMask = ma.mincresampleMask(FH,
                                                FH,
                                                outputLocation=FH,
                                                likeFile=FH)
                 self.p.addStage(cropMask)
Esempio n. 26
0
 def __init__(self, filesToResample, resolution):
     """During initialization make sure all files are resampled
        at resolution we'd like to use for each pipeline stage
     """
     self.p = Pipeline()
     
     for FH in filesToResample:
         dirForOutput = self.getOutputDirectory(FH)
         currentRes = volumeFromFile(FH.getLastBasevol()).separations
         if not abs(abs(currentRes[0]) - abs(resolution)) < 0.01:
             crop = ma.autocrop(resolution, FH, defaultDir=dirForOutput)
             self.p.addStage(crop)
             mask = FH.getMask()
             if mask:
                 #Need to resample the mask as well.
                 cropMask = ma.mincresampleMask(FH,
                                                FH,
                                                outputLocation=FH,
                                                likeFile=FH)
                 self.p.addStage(cropMask)
Esempio n. 27
0
def do_component(component_nr):
    input_volume = volumeFromFile(
        '/scratch/intersection_output_disjoint/input_%d.mnc' % component_nr)

    output_volume = volumeLikeFile(
        '/scratch/intersection_output_disjoint/input_%d.mnc' % component_nr,
        '/scratch/final_smoothed_disjoint_components/component_%d.mnc' %
        component_nr,
        dtype='ubyte')

    for j in range(input_volume.data.shape[1]):
        print component_nr, j

        output_volume.data[:, j, :] = blerp(input_volume.data[:, j, :])

    output_volume.writeFile()
    output_volume.closeVolume()

    input_volume.closeVolume()
    """
Esempio n. 28
0
 def load_2D_mnc(self, filename):
     """loads and squeezes a 2D mncfile"""
     import pyminc.volumes.factory as pyminc
     mncfile = pyminc.volumeFromFile(filename)
     array_data = np.squeeze(np.array(mncfile.data))
     return array_data
Esempio n. 29
0
# Standard modules
import os, sys
#import argparse

# Non-standard modules
import numpy as np
import pyminc.volumes.factory as pyminc

# My modules in other directories
sufkes_git_repo_dir = "/Users/steven ufkes/scripts"  # change this to the path to which the sufkes Git repository was cloned.
sys.path.append(os.path.join(sufkes_git_repo_dir, "misc"))
from Color import Color

minc_file_path = str(sys.argv[1])
minc_vol = pyminc.volumeFromFile(minc_file_path, labels=True)
separations = minc_vol.separations
volume = minc_vol.data


def getVolumeSet(volume, val_list):
    """Separate a single volume into multiple volumes of the same size
    by sorting voxels into groups based on the number assigned to them.
    For example, suppose you labelled right-hemisphere lesions with '1' 
    and left-hemisphere lesions with '2', this function will return a
    list of 2 volumes, each with the original size. One will contain all
    zeros except for the voxels labelled '1'; the other will contain all 
    zeros except for the voxels labelled '2'. 
    This function will also convert all the labels to the int type by 
    rounding to the nearest integer."""
    volume_list = [
Esempio n. 30
0
def load_minc_as_np(mncfile):
    print(mncfile)
    _img = pyminc.volumeFromFile(mncfile)
    img = np.array(_img.data,dtype='double')
    _img.closeVolume()
    return img
        #g= graph_analysis.input_graph(input_file)
        ##g= graph_analysis.input_graph("/micehome/sghanavati/Documents/data/journal1data_c57_feb13/LOO_final_revised/autolabel_c57_1_4_S_cyl.db")
        ##g= graph_analysis.input_graph("./c57_1_9Nov12/c57_1_graph_add_coverage_delleave_radi1.06_smooth2_simplified_rmisolate_features_groundtruthlabel_cyl_revised.db")

        #mr_atlas_file = "/projects/souris/sghanavati/data/c57_male_female_mri_atlas/c57_brain_segmentation_mnc2_merged_reg2vascular.mnc"
        ###mr_atlas_file = "/projects/souris/sghanavati/data/c57_male_female_mri_atlas/c57_brain_segmentation_mnc2_merged_reg2vascular_downsample_merge.mnc"

        ###labels = [2,43,102,143,122,8,5,108,105,35,135,13,236,111,191,190,91,90,200,9,7,10,196,96,198,68,227,168,169,46,12,49,45,14,15,17,18,3,4]
        #labels = [122, 8, 5, 108, 105, 35, 135, 13, 236, 111, 191, 190, 91, 90, 68, 227, 168, 169, 46, 12, 49, 45, 14, 15, 17, 18, 3, 4]

        labels = {}
        #perfusion_pattern = py_minc.ArrayVolume(perfusion_file, nc_data_type=py_minc.NC_BYTE)# without this always [z,y,x], with ,dim_names=py_minc.FILE_ORDER_DIMENSION_NAMES order as the image
        #sizes = perfusion_pattern.get_sizes()
        #spacing = perfusion_pattern.get_separations()
        perfusion_pattern = pymincf.volumeFromFile(perfusion_file,
                                                   dtype='ubyte')  #ushort
        perfusion_pattern.openFile()
        sizes = perfusion_pattern.getSizes()
        spacing = perfusion_pattern.getSeparations()
        #print sizes[0], sizes[1], sizes[2],":",spacing[0],spacing[1],spacing[2]
        for z_vox in range(sizes[0]):
            for y_vox in range(sizes[1]):
                for x_vox in range(sizes[2]):
                    value = perfusion_pattern[z_vox, y_vox, x_vox]
                    #value = int(round(perfusion_pattern.array[z_vox,y_vox,x_vox]))
                    if value > 0:
                        if value not in labels.keys():
                            labels[value] = 1
                        else:
                            labels[value] += 1
        print labels.keys()
def perfusion_region_noremap(g,
                             mr_atlas_file,
                             labels,
                             perfusion_file,
                             Perfusionradius=1e10):
    # 	mr_atlas_file = "/projects/souris/sghanavati/data/c57_male_female_mri_atlas/c57_brain_segmentation_mnc2_merged_reg2vascular.mnc"
    #	mr_atlas_file = "/projects/souris/sghanavati/data/c57_male_female_mri_atlas/c57_brain_segmentation_mnc2_merged_reg2vascular_downsample_merge.mnc"
    endpoint = []
    vpoint = []
    for e in g.edge_list():
        #if len(find_neighbor_edges(g,e))==2 and g.edge_property(e,'label') in labels:
        if g.edge_property(e, 'label') in labels:
            if len(g.vertices[e[0]].edges) == 1:
                vpoint.append(e[0])
                endpoint.append(e)
            elif len(g.vertices[e[1]].edges) == 1:
                vpoint.append(e[1])
                endpoint.append(e)
    #### mri_distance feature:
    ## nc_data_type=py_minc.NC_BYTE is writing a byte (floating point) but we want the voxel intensities to be int labels
    ## nc_data_type=py_minc.NC_SHORT is writing a short integer data and we want the voxel intensities to be int labels
    #mri_atlas = py_minc.ArrayVolume(mr_atlas_file, nc_data_type=py_minc.NC_BYTE )# without this always [z,y,x], with ,dim_names=py_minc.FILE_ORDER_DIMENSION_NAMES order as the image
    #perfusion_pattern = py_minc.ArrayVolume(mr_atlas_file, nc_data_type=py_minc.NC_BYTE )# without this always [z,y,x], with ,dim_names=py_minc.FILE_ORDER_DIMENSION_NAMES order as the image
    #sizes = mri_atlas.get_sizes()
    mri_atlas = pymincf.volumeFromFile(mr_atlas_file, dtype='ubyte')  #ushort
    mri_atlas.openFile()
    sizes = mri_atlas.getSizes()
    spacing = mri_atlas.getSeparations()
    perfusion_pattern = pymincf.volumeFromInstance(mri_atlas,
                                                   perfusion_file,
                                                   dtype="ubyte")  #ushort

    #make all voxels 0, give label for vpoints
    for z_vox in range(sizes[0]):
        for y_vox in range(sizes[1]):
            for x_vox in range(sizes[2]):
                #perfusion_pattern.array[z_vox,y_vox,x_vox]=0
                perfusion_pattern.data[z_vox, y_vox, x_vox] = 0
    for i in range(len(vpoint)):
        v = vpoint[i]
        world = g.vertices[v].centre
        #voxel = floor(mri_atlas.convert_world_to_voxel(array([world[0],world[1],world[2]])))
        voxel = floor(
            mri_atlas.convertWorldToVoxel(
                np.array([world[0], world[1], world[2]])))
        if voxel[0] in range(sizes[0]) and voxel[1] in range(
                sizes[1]) and voxel[2] in range(sizes[2]):
            perfusion_pattern.data[int(voxel[0]),
                                   int(voxel[1]),
                                   int(voxel[2])] = g.edge_property(
                                       endpoint[i], 'label')
            #perfusion_pattern.array[int(voxel[0]),int(voxel[1]),int(voxel[2])] = g.edge_property(endpoint[i],'label')

    for z_vox in range(sizes[0]):
        for y_vox in range(sizes[1]):
            for x_vox in range(sizes[2]):
                #world=mri_atlas.convert_voxel_to_world(array([z_vox,y_vox,x_vox]))
                world = mri_atlas.convertVoxelToWorld(
                    np.array([z_vox, y_vox, x_vox]))

                min_dist = 1e10
                min_label = 0
                for i in range(len(vpoint)):
                    v = vpoint[i]
                    if distance(world, g.vertices[v].centre
                                ) < Perfusionradius and distance(
                                    world, g.vertices[v].centre) < min_dist:
                        min_dist = distance(world, g.vertices[v].centre)
                        min_label = g.edge_property(endpoint[i], 'label')
                #perfusion_pattern.array[z_vox,y_vox,x_vox]=	int(min_label)
                perfusion_pattern.data[z_vox, y_vox, x_vox] = int(min_label)

    #perfusion_pattern.output(perfusion_file)
    perfusion_pattern.writeFile()
    perfusion_pattern.closeVolume()
    mri_atlas.closeVolume()
Esempio n. 33
0
parser.add_argument('RTMINC', help='Path to the OUTPUT MINC RT file')
parser.add_argument("--verbose", help="increase output verbosity", action="store_true")
parser.add_argument("--visualize", help="Show plot of slices for debugging", action="store_true")
parser.add_argument("--copy_name", help="Copy the name of the RTstruct (defined in Mirada) to the name of the MNC file", action="store_true")

args = parser.parse_args()

try:
	RTSS = dicom.read_file(args.RTX) 
	print RTSS.StructureSetROISequence[0].ROIName
	ROIs = RTSS.ROIContourSequence

	if args.verbose:
		print "Found",len(ROIs),"ROIs"

	volume = pyminc.volumeFromFile(args.MINC)

	for ROI_id,ROI in enumerate(ROIs):

		# Create one MNC output file per ROI
		RTMINC_outname = args.RTMINC if len(ROIs) == 1 else args.RTMINC[:-4] + "_" + str(ROI_id) + ".mnc"
		RTMINC = pyminc.volumeLikeFile(args.MINC,RTMINC_outname)
		contour_sequences = ROI.ContourSequence

		if args.verbose:
			print " --> Found",len(contour_sequences),"contour sequences for ROI:",RTSS.StructureSetROISequence[ROI_id].ROIName

		for contour in contour_sequences:
			assert contour.ContourGeometricType == "CLOSED_PLANAR"

			current_slice_i_print = 0
Esempio n. 34
0
def go(component_index):
    # Top-level parameters:
    input_file = '/mnt/home/carlo/00-init-label-vol.mnc'
    dim_to_interpolate = 1
    nr_interpolation_steps = 3
    workflow_name = 'morpho_%d' % component_index

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

    input_file = os.path.abspath(input_file)

    volume = volumeFromFile(input_file)
    data = volume.data

    volume_dimnames = volume.dimnames
    volume_starts = volume.starts

    assert len(data.shape) == 3
    assert dim_to_interpolate in [0, 1, 2]
    assert nr_interpolation_steps >= 1

    old_separations = volume.separations

    new_separations = old_separations[:]
    new_separations[dim_to_interpolate] /= 2**nr_interpolation_steps

    new_sizes = volume.sizes[:3]
    for s in new_sizes:
        assert s > 0
    new_sizes[dim_to_interpolate] = calc_new_sizes(
        new_sizes[dim_to_interpolate], nr_interpolation_steps)

    volume.closeVolume()

    workflow = pe.Workflow(name=workflow_name)

    cs = sorted(uniq(data.flatten()))
    assert cs[0] == 0
    cs = cs[1:]

    # cs = cs[21:][:2] # FIXME Just for testing...
    cs = [cs[component_index]]

    extractors = []

    minc_sink = {}

    for c in cs:
        slice_name = ('feature_%0.4f' % c).replace('.', '_')
        print 'building workflow for:', slice_name

        extract_node = pe.Node(interface=ExtractFeature(
            in_file=input_file,
            float_val=c,
            tol=0.5,
            dim_to_interpolate=dim_to_interpolate),
                               name='extract_feature_' + slice_name)

        extractors.append(extract_node)

        slice_size = data.shape[dim_to_interpolate]

        minc_sink[slice_name] = build_workflow(
            workflow, extract_node, slice_name, slice_size, dim_to_interpolate,
            volume_dimnames, nr_interpolation_steps, volume_starts,
            new_separations, new_sizes)

    merge_minc_names = pe.Node(interface=Merge(len(minc_sink)),
                               name='merge_minc_names')

    for (i, minc) in enumerate(minc_sink.itervalues()):
        workflow.connect(minc, 'out_file', merge_minc_names, 'in%d' % (i + 1))

    actual_final_merge = pe.Node(interface=MergeMincs(),
                                 name='actual_final_merge_mincs')

    workflow.connect(merge_minc_names, 'out', actual_final_merge, 'in_files')

    actual_final_merge.inputs.labels = map(float, cs)

    actual_final_merge.inputs.dimension_names = volume_dimnames
    actual_final_merge.inputs.sizes = new_sizes
    actual_final_merge.inputs.starts = volume_starts
    actual_final_merge.inputs.separations = new_separations

    merged_minc_sink = pe.Node(interface=nio.DataSink(),
                               name='merged_minc_sink')
    workflow.connect(actual_final_merge, 'out_file', merged_minc_sink,
                     'merged_minc_file')

    # FIXME Hardcoded...
    # os.system('rm -fr /tmp/tmp_carlo')
    # os.system('mkdir /tmp/tmp_carlo')
    # workflow.base_dir = '/scratch/morph_debug'
    #workflow.base_dir = '/scratch/init_00_morph'

    # workflow.run()
    workflow.run(plugin='MultiProc', plugin_args={'n_procs': 4})
def perfusion_region_nomask(g,
                            mr_atlas_file,
                            labels,
                            label_remap,
                            perfusion_file,
                            Perfusionradius=1e10):
    #   mr_atlas_file = "/projects/souris/sghanavati/data/c57_male_female_mri_atlas/c57_brain_segmentation_mnc2_merged_reg2vascular.mnc"
    #   mr_atlas_file = "/projects/souris/sghanavati/data/c57_male_female_mri_atlas/c57_brain_segmentation_mnc2_merged_reg2vascular_downsample_merge.mnc"

    if label_remap:
        lpairs = label_remap.split(',')
        labelpairs = []
        for pair in lpairs:
            plabels = pair.split(':')
            plabels = [int(l) for l in plabels]
            labelpairs.append(plabels)
        tomap_l = [int(l[0]) for l in labelpairs]
        print labelpairs

        for e in g.edge_list():
            if g.edge_property(e, 'label') in tomap_l:
                g.set_edge_property(
                    e, 'label',
                    int(labelpairs[tomap_l.index(g.edge_property(
                        e, 'label'))][1]))

    endpoint = []
    vpoint = []
    for e in g.edge_list():
        #if len(find_neighbor_edges(g,e))==2 and g.edge_property(e,'label') in labels:
        if g.edge_property(e, 'label') in labels:
            if len(g.vertices[e[0]].edges) == 1:
                vpoint.append(e[0])
                endpoint.append(e)
            elif len(g.vertices[e[1]].edges) == 1:
                vpoint.append(e[1])
                endpoint.append(e)

    if not len(vpoint) == len(endpoint):
        print "ERROR: The length of endpoints and leaf edges should match but they don't!"
        exit(0)

    #### mri_distance feature:
    ## nc_data_type=py_minc.NC_BYTE is writing a byte (floating point) but we want the voxel intensities to be int labels
    ## nc_data_type=py_minc.NC_SHORT is writing a short integer data and we want the voxel intensities to be int labels
    #mri_atlas = py_minc.ArrayVolume(mr_atlas_file, nc_data_type=py_minc.NC_BYTE )# without this always [z,y,x], with ,dim_names=py_minc.FILE_ORDER_DIMENSION_NAMES order as the image
    #perfusion_pattern = py_minc.ArrayVolume(mr_atlas_file, nc_data_type=py_minc.NC_BYTE )# without this always [z,y,x], with ,dim_names=py_minc.FILE_ORDER_DIMENSION_NAMES order as the image
    #sizes = mri_atlas.get_sizes()
    mri_atlas = pymincf.volumeFromFile(mr_atlas_file, dtype='ubyte')  #ushort
    mri_atlas.openFile()
    sizes = mri_atlas.getSizes()
    spacing = mri_atlas.getSeparations()
    perfusion_pattern = pymincf.volumeFromInstance(mri_atlas,
                                                   perfusion_file,
                                                   dtype="ubyte")

    #make all voxels 0, give label for vpoints
    for z_vox in range(sizes[0]):
        for y_vox in range(sizes[1]):
            for x_vox in range(sizes[2]):
                label_dist = {l: Perfusionradius for l in labels}
                #world = mri_atlas.convert_voxel_to_world(array([z_vox,y_vox,x_vox]))
                world = mri_atlas.convertVoxelToWorld(
                    np.array([z_vox, y_vox, x_vox]))
                for i in range(len(vpoint)):
                    v = vpoint[i]
                    l = g.edge_property(endpoint[i], 'label')
                    d = distance(world, g.vertices[v].centre)
                    if d < label_dist[l]:
                        label_dist[l] = d
                label_dist_sorted = sorted(
                    label_dist.items(), key=operator.itemgetter(1)
                )  #### sort dictionary by value: result list of tuples   #### sorted(label_dist.items(), key=operator.itemgetter(0)) ##sort dictionary by key
                #perfusion_pattern.array[z_vox,y_vox,x_vox] =  int(round(label_dist_sorted[0][0]))
                perfusion_pattern.data[z_vox, y_vox, x_vox] = int(
                    round(label_dist_sorted[0][0]))

    #perfusion_pattern.output(perfusion_file)
    perfusion_pattern.writeFile()
    perfusion_pattern.closeVolume()
    mri_atlas.closeVolume()