Exemple #1
0
    def saveResults(self, savePath, worldToWorldTransformMatrix,
                    imageToImageTransformMatrix):

        # Save the image-to-image and the world-to-world affine registration matrices
        scipy.io.savemat(
            os.path.join(savePath, 'template_transforms.mat'), {
                'imageToImageTransformMatrix': imageToImageTransformMatrix,
                'worldToWorldTransformMatrix': worldToWorldTransformMatrix
            })

        # Save the template transform
        inputImage = fs.Volume.read(self.imageFileName)
        templateImage = fs.Volume.read(self.templateFileName)
        xform = fs.LinearTransform(
            convertLPSTransformToRAS(worldToWorldTransformMatrix))
        xform.type = fs.LinearTransform.Type.ras
        xform.source = templateImage.geometry()
        xform.target = inputImage.geometry()
        ltaFileName = os.path.join(savePath, 'template.lta')
        print('writing template transform to %s' % ltaFileName)
        xform.write(ltaFileName)

        # Compute and save the talairach.xfm
        xform = self.computeTalairach(imageToImageTransformMatrix)
        ltaFileName = os.path.join(savePath, 'samseg.talairach.lta')
        print('writing talairach transform to %s' % ltaFileName)
        xform.write(ltaFileName)

        # Save the coregistered template
        coregistered = fs.Volume(
            fs.geom.resample(templateImage.data, inputImage.shape[:3],
                             np.linalg.inv(imageToImageTransformMatrix)))
        coregistered.copy_geometry(inputImage)
        coregistered.write(os.path.join(savePath, 'template_coregistered.mgz'))
Exemple #2
0
    def writeImage(self, data, path, saveLabels=False):
        # Read source geometry
        geom = fs.Volume.read(self.imageFileNames[0]).geometry()

        # Account for multi-frame volumes
        if data.ndim == 4:
            shape = (*geom.shape, data.shape[-1])
        else:
            shape = geom.shape

        # Uncrop image
        uncropped = np.zeros(shape, dtype=data.dtype, order='F')
        uncropped[self.cropping] = data
        volume = fs.Volume(uncropped, affine=geom.affine, voxsize=geom.voxsize)
        if saveLabels:
            volume.lut = fs.LookupTable.read_default()
        volume.write(path)
Exemple #3
0
def compute_intensity_stats(paths,
                            vname_list,
                            method='mean',
                            ranges=None,
                            vol_list=None):
    nvols = len(vname_list)
    means = np.zeros(nvols)
    stds = np.zeros(nvols)
    for pno, path in enumerate(paths):
        for vno, vname in enumerate(vname_list):
            fname = os.path.join(path, vname)
            if (vol_list == None):
                print('%d of %d: file %s' % (pno, len(paths), fname))
                mri = fs.Volume(fname)
            else:
                mri = vol_list[pno][vno]
            im = mri.image.astype('float64')
            if (method == 'mean'):
                val = im.mean()
            elif method == 'histo':
                if ranges is not None:
                    ind = np.where(
                        np.logical_and(im > ranges[vno, 0],
                                       im < ranges[vno, 1]))
                    im = im[ind]
                try:
                    hist, edges = np.histogram(im.flatten(), bins='auto')
                except ValueError:
                    print('exception')
                    hist, edges = np.histogram(im.flatten(), bins=500)

                val = edges[hist.argmax()]
                del edges, hist
            shape = mri.image.shape
            if (vol_list == None):
                del mri
            means[vno] += val
            stds[vno] += (val * val)

    for vno in range(nvols):
        means[vno] /= len(paths)
        stds[vno] = np.sqrt(stds[vno] / len(paths) - means[vno] * means[vno])

    return means, stds, shape
import imageio, pydicom, gdcm, load_serial_cxr

bdir = '/autofs/cluster/lcnextdata1/CCDS_CXR/CXR-Serial/def_20200413'

il, sl, sn = load_serial_cxr.load_serial_cxr(bdir)

for sno, ilist in enumerate(il):
    if len(ilist) >= 2:
        date_list = []
        time_list = []
        for ino, im in enumerate(ilist):
            date_list.append(int(im.StudyDate))
            if hasattr(im, 'SeriesTime'):
                time_list.append(int(im.SeriesTime.split('.')[0]))
            else:
                time_list.append(int(im.StudyTime.split('.')[0]))

        ind = np.array(date_list).argsort()
        date_list2 = []
        time_list2 = []
        ilist2 = []
        for i in ind.tolist():
            date_list2.append(date_list[i])
            time_list2.append(time_list[i])
            ilist2.append(ilist[i])

        for ino, im in enumerate(ilist2):
            tokens = sl[sno][ind[ino]].split('/')
            fname = '/'.join(tokens[0:-2]) + '/time%2.2d.mgz' % ino
            fs.Volume(im.pixel_array.astype(np.float32)).write(fname)