def __init__(self, resels=None, fwhm=None, **keywords): """ Initialize resel image Parameters ---------- resels : `core.api.Image` Image of resel per voxel values. fwhm : `core.api.Image` Image of FWHM values. keywords : ``dict`` Passed as keywords arguments to `core.api.Image` """ if not resels and not fwhm: raise ValueError('need either a resels image or an FWHM image') if fwhm is not None: fwhm = Image(fwhm, **keywords) Resels.__init__(self, fwhm, resels=resels, fwhm=fwhm) if resels is not None: resels = Image(resels, **keywords) Resels.__init__(self, resels, resels=resels, fwhm=fwhm) if not self.fwhm: self.fwhm = Image(self.resel2fwhm(self.resels[:]), coordmap=self.coordmap, **keywords) if not self.resels: self.resels = Image(self.fwhm2resel(self.fwhm[:]), coordmap=self.coordmap, **keywords)
def test_output_dtypes(): shape = (4, 2, 3) rng = np.random.RandomState(19441217) # IN-S BD data = rng.normal(4, 20, size=shape) aff = np.diag([2.2, 3.3, 4.1, 1]) cmap = vox2mni(aff) img = Image(data, cmap) fname_root = 'my_file' with InTemporaryDirectory(): for ext in 'img', 'nii': out_fname = fname_root + '.' + ext # Default is for data to come from data dtype save_image(img, out_fname) img_back = load_image(out_fname) hdr = img_back.metadata['header'] assert_dt_no_end_equal(hdr.get_data_dtype(), np.float) del img_back # lets window re-use the file # All these types are OK for both output formats for out_dt in 'i2', 'i4', np.int16, '<f4', '>f8': # Specified output dtype save_image(img, out_fname, out_dt) img_back = load_image(out_fname) hdr = img_back.metadata['header'] assert_dt_no_end_equal(hdr.get_data_dtype(), out_dt) del img_back # windows file re-use # Output comes from data by default data_typed = data.astype(out_dt) img_again = Image(data_typed, cmap) save_image(img_again, out_fname) img_back = load_image(out_fname) hdr = img_back.metadata['header'] assert_dt_no_end_equal(hdr.get_data_dtype(), out_dt) del img_back # Even if header specifies otherwise in_hdr = Nifti1Header() in_hdr.set_data_dtype(np.dtype('c8')) img_more = Image(data_typed, cmap, metadata={'header': in_hdr}) save_image(img_more, out_fname) img_back = load_image(out_fname) hdr = img_back.metadata['header'] assert_dt_no_end_equal(hdr.get_data_dtype(), out_dt) del img_back # But can come from header if specified save_image(img_more, out_fname, dtype_from='header') img_back = load_image(out_fname) hdr = img_back.metadata['header'] assert_dt_no_end_equal(hdr.get_data_dtype(), 'c8') del img_back # u2 only OK for nifti save_image(img, 'my_file.nii', 'u2') img_back = load_image('my_file.nii') hdr = img_back.metadata['header'] assert_dt_no_end_equal(hdr.get_data_dtype(), 'u2') # Check analyze can't save u2 datatype assert_raises(HeaderDataError, save_image, img, 'my_file.img', 'u2') del img_back
def test_resample_outvalue(): # Test resampling with different modes, constant values, datatypes, orders def func(xyz): return xyz + np.asarray([1, 0, 0]) coordmap = vox2mni(np.eye(4)) arr = np.arange(3 * 3 * 3).reshape(3, 3, 3) aff = np.eye(4) aff[0, 3] = 1. # x translation for mapping, dt, order in product( [aff, func], [np.int8, np.intp, np.int32, np.int64, np.float32, np.float64], [0, 1, 3]): img = Image(arr.astype(dt), coordmap) # Test constant value of 0 img2 = resample(img, coordmap, mapping, img.shape, order=order, mode='constant', cval=0.) exp_arr = np.zeros(arr.shape) exp_arr[:-1, :, :] = arr[1:, :, :] assert_array_almost_equal(img2.get_data(), exp_arr) # Test constant value of 1 img2 = resample(img, coordmap, mapping, img.shape, order=order, mode='constant', cval=1.) exp_arr[-1, :, :] = 1 assert_array_almost_equal(img2.get_data(), exp_arr) # Test nearest neighbor img2 = resample(img, coordmap, mapping, img.shape, order=order, mode='nearest') exp_arr[-1, :, :] = arr[-1, :, :] assert_array_almost_equal(img2.get_data(), exp_arr) # Test img2img target_coordmap = vox2mni(aff) target = Image(arr, target_coordmap) img2 = resample_img2img(img, target, 3, 'nearest') assert_array_almost_equal(img2.get_data(), exp_arr) img2 = resample_img2img(img, target, 3, 'constant', cval=1.) exp_arr[-1, :, :] = 1 assert_array_almost_equal(img2.get_data(), exp_arr)
def expandFrames(imgFn, saveDir): """ Expand a timeseries image into a set of individual frames in the specified directory Inputs: - imgFn: the timeseries image's filename - saveDir: the directory in which the frames will be stored Returns: - frameFns: the list of filenames """ # Load the image img = load_image(imgFn) coord = img.coordmap frameFns = [] # Make the save directory framesDir = saveDir + '/frames/' # need to check for // # check for duplicate // framesDir = framesDir.replace("//", '/') if not os.path.exists(framesDir): os.mkdir(framesDir) for i in xrange(img.get_data().shape[3]): frame = img[:, :, :, i].get_data()[:, :, :, None] frameImg = Image(frame, coord) outFn = framesDir + str(i).zfill(3) + ".nii.gz" save_image(frameImg, outFn) frameFns.append(outFn) return frameFns
def __init__(self, filename, coordmap, shape, clobber=False): self.filename = filename self._im_data = np.zeros(shape) self._im = Image(self._im_data, coordmap) # Using a dangerous undocumented API here self.clobber = clobber self._flushed = False
def test_nonaffine(): # resamples an image along a curve through the image. # # FIXME: use the reference.evaluate.Grid to perform this nicer # FIXME: Remove pylab references def curve(x): # function accept N by 1, returns N by 2 return (np.vstack([5 * np.sin(x.T), 5 * np.cos(x.T)]).T + [52, 47]) for names in (('xy', 'ij', 't', 'u'), ('ij', 'xy', 't', 's')): in_names, out_names, tin_names, tout_names = names g = AffineTransform.from_params(in_names, out_names, np.identity(3)) img = Image(np.ones((100, 90)), g) img.get_data()[50:55, 40:55] = 3. tcoordmap = AffineTransform.from_start_step(tin_names, tout_names, [0], [np.pi * 1.8 / 100]) ir = resample(img, tcoordmap, curve, (100, )) if gui_review: import pylab pylab.figure(num=3) pylab.imshow(img, interpolation='nearest') d = curve(np.linspace(0, 1.8 * np.pi, 100)) pylab.plot(d[0], d[1]) pylab.gca().set_ylim([0, 99]) pylab.gca().set_xlim([0, 89]) pylab.figure(num=4) pylab.plot(ir.get_data())
def randimg_in2out(rng, in_dtype, out_dtype, name): in_dtype = np.dtype(in_dtype) out_dtype = np.dtype(out_dtype) shape = (2, 3, 4) if in_dtype.kind in 'iu': info = np.iinfo(in_dtype) dmin, dmax = info.min, info.max # Numpy bug for np < 1.6.0 allows overflow for range that does not fit # into C long int (int32 on 32-bit, int64 on 64-bit) try: data = rng.randint(dmin, dmax, size=shape) except ValueError: from random import randint vals = [randint(dmin, dmax) for v in range(np.prod(shape))] data = np.array(vals).astype(in_dtype).reshape(shape) elif in_dtype.kind == 'f': info = np.finfo(in_dtype) dmin, dmax = info.min, info.max # set some value for scaling our data scale = np.iinfo(np.uint16).max * 2.0 data = rng.normal(size=shape, scale=scale) data[0, 0, 0] = dmin data[1, 0, 0] = dmax data = data.astype(in_dtype) img = Image(data, vox2mni(np.eye(4))) # The dtype_from dtype won't be visible until the image is loaded newimg = save_image(img, name, dtype_from=out_dtype) return newimg.get_data(), data
def save_to_image(data, template_file=DEFAULT_template, output_file=DEFAULT_output): template = load_image(template_file) newimg = Image(data, vox2mni(template.affine)) save_image(newimg, output_file) return output_file
def convertArrayToImage(seq, coords): # Condense the replicated sequence seqStack = np.stack(seq, axis=-1) # Convert the image sequence into an Image seqImg = Image(seqStack, coords) return seqImg
def save_nii(data, coord, save_file): """ Saves a numpy array (data) as a nifti file The coordinate space must match the array dimensions """ arr_img = Image(data, coord) save_image(arr_img, save_file) return 0
def test_labels1(): img = load_image(funcfile) data = img.get_data() parcelmap = Image(img[0].get_data(), AfT('kji', 'zyx', np.eye(4))) parcelmap = (parcelmap.get_data() * 100).astype(np.int32) v = 0 for i, d in axis0_generator(data, parcels(parcelmap)): v += d.shape[1] assert_equal(v, parcelmap.size)
def test_resample2d2(): g = AffineTransform.from_params('ij', 'xy', np.diag([0.5, 0.5, 1])) i = Image(np.ones((100, 90)), g) i.get_data()[50:55, 40:55] = 3. a = np.identity(3) a[:2, -1] = 4. A = np.identity(2) b = np.ones(2) * 4 ir = resample(i, i.coordmap, (A, b), (100, 90)) assert_array_almost_equal(ir.get_data()[42:47, 32:47], 3.)
def test_resample2d3(): # Same as test_resample2d, only a different way of specifying # the transform: here it is an (A,b) pair g = AffineTransform.from_params('ij', 'xy', np.diag([0.5, 0.5, 1])) i = Image(np.ones((100, 90)), g) i.get_data()[50:55, 40:55] = 3. a = np.identity(3) a[:2, -1] = 4. ir = resample(i, i.coordmap, a, (100, 90)) assert_array_almost_equal(ir.get_data()[42:47, 32:47], 3.)
def test_rotate2d(): # Rotate an image in 2d on a square grid, should result in transposed image g = AffineTransform.from_params('ij', 'xy', np.diag([0.7, 0.5, 1])) g2 = AffineTransform.from_params('ij', 'xy', np.diag([0.5, 0.7, 1])) i = Image(np.ones((100, 100)), g) # This sets the image data by writing into the array i.get_data()[50:55, 40:55] = 3. a = np.array([[0, 1, 0], [1, 0, 0], [0, 0, 1]], np.float) ir = resample(i, g2, a, (100, 100)) assert_array_almost_equal(ir.get_data().T, i.get_data())
def test_interpolator(): arr = np.arange(24).reshape((2, 3, 4)) coordmap = vox2mni(np.eye(4)) img = Image(arr, coordmap) # Interpolate off top right corner with different modes interp = ImageInterpolator(img, mode='nearest') assert_almost_equal(interp.evaluate([0, 0, 4]), arr[0, 0, -1]) interp = ImageInterpolator(img, mode='constant', cval=0) assert_array_equal(interp.evaluate([0, 0, 4]), 0) interp = ImageInterpolator(img, mode='constant', cval=1) assert_array_equal(interp.evaluate([0, 0, 4]), 1)
def Fmask(Fimg, dfnum, dfdenom, pvalue=1.0e-04): """ Create mask for use in estimating pooled covariance based on an F contrast. """ ## TODO check nipy.algorithms.statistics.models.contrast to see if rank is ## correctly set -- I don't think it is right now. print dfnum, dfdenom thresh = FDbn.ppf(pvalue, dfnum, dfdenom) return Image(np.greater(np.asarray(Fimg), thresh), Fimg.grid.copy())
def generateTestingPair(betaGT): betaGTRads = np.array(betaGT, dtype=np.float64) betaGTRads[0:3] = np.copy(np.pi * betaGTRads[0:3] / 180.0) ns = 181 nr = 217 nc = 181 left = np.fromfile('data/t2/t2_icbm_normal_1mm_pn0_rf0.rawb', dtype=np.ubyte).reshape(ns, nr, nc) left = left.astype(np.float64) right = np.fromfile('data/t1/t1_icbm_normal_1mm_pn0_rf0.rawb', dtype=np.ubyte).reshape(ns, nr, nc) right = right.astype(np.float64) right = rcommon.applyRigidTransformation3D(right, betaGTRads) affine_transform = AffineTransform( 'ijk', ['aligned-z=I->S', 'aligned-y=P->A', 'aligned-x=L->R'], np.eye(4)) left = Image(left, affine_transform) right = Image(right, affine_transform) nipy.save_image(left, 'moving.nii') nipy.save_image(right, 'fixed.nii')
def test_rotate3d(): # Rotate / transpose a 3d image on a non-square grid g = AffineTransform.from_params('ijk', 'xyz', np.diag([0.5, 0.6, 0.7, 1])) g2 = AffineTransform.from_params('ijk', 'xyz', np.diag([0.5, 0.7, 0.6, 1])) shape = (100, 90, 80) i = Image(np.ones(shape), g) i.get_data()[50:55, 40:55, 30:33] = 3. a = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1.]]) ir = resample(i, g2, a, (100, 80, 90)) assert_array_almost_equal(np.transpose(ir.get_data(), (0, 2, 1)), i.get_data())
def expandTimepoints(imgFn, baseDir): """ Expand an image sequence stored as a .nii.gz file into a collection of .nii.gz images (where each frame is its own .nii.gz file) Inputs: - imgFn: the time series image's filename - baseDir: the directory in which a new directory will be created to hold the collection of files Returns: - filenames: list of filenames """ # load the image img = load_image(imgFn) coord = img.coordmap if not os.path.exists(baseDir + 'timepoints/'): os.mkdir(baseDir + 'timepoints/') outDir = baseDir + 'timepoints/' # pull out the first image from the sequence (timepoint 0) first = img[:, :, :, 0].get_data()[:, :, :, None] first_img = Image(first, coord) # save the first image as 000 save_image(first_img, outDir + str(0).zfill(3) + '.nii.gz') # build the list of filenames filenames = [outDir + '000.nii.gz'] # for the remaining images for i in xrange(1, img.get_data().shape[3], 1): # pull out the image and save it tmp = img[:, :, :, i].get_data()[:, :, :, None] tmp_img = Image(tmp, coord) outFn = str(i).zfill(3) + '.nii.gz' save_image(tmp_img, outDir + outFn) # add the name of the image to the list of filenames filenames.append(outDir + outFn) return filenames
def peelTemplateBrain(): ns = 181 nr = 217 nc = 181 gt_template = np.fromfile('data/phantom_1.0mm_normal_crisp.rawb', dtype=np.ubyte).reshape((ns, nr, nc)) t1_template = np.fromfile('data/t1/t1_icbm_normal_1mm_pn0_rf0.rawb', dtype=np.ubyte).reshape((ns, nr, nc)) t2_template = np.fromfile('data/t2/t2_icbm_normal_1mm_pn0_rf0.rawb', dtype=np.ubyte).reshape((ns, nr, nc)) #t1_template*=((1<=gt_template)*(gt_template<=3)+(gt_template==8)) t1_template *= ((1 <= gt_template) * (gt_template <= 3)) t2_template *= ((1 <= gt_template) * (gt_template <= 3)) affine_transform = AffineTransform( 'ijk', ['aligned-z=I->S', 'aligned-y=P->A', 'aligned-x=L->R'], np.eye(4)) t1_template = Image(t1_template, affine_transform) t2_template = Image(t2_template, affine_transform) nipy.save_image(t1_template, 'data/t1/t1_icbm_normal_1mm_pn0_rf0_peeled.nii.gz') nipy.save_image(t2_template, 'data/t2/t2_icbm_normal_1mm_pn0_rf0_peeled.nii.gz')
def test_2d_from_3d(): # Resample a 3d image on a 2d affine grid # This example creates a coordmap that coincides with # the 10th slice of an image, and checks that # resampling agrees with the data in the 10th slice. shape = (100, 90, 80) g = AffineTransform.from_params('ijk', 'xyz', np.diag([0.5, 0.5, 0.5, 1])) i = Image(np.ones(shape), g) i.get_data()[50:55, 40:55, 30:33] = 3. a = np.identity(4) g2 = ArrayCoordMap.from_shape(g, shape)[10] ir = resample(i, g2.coordmap, a, g2.shape) assert_array_almost_equal(ir.get_data(), i[10].get_data())
def __iter__(self): """ Return iterator Returns ------- itor : iterator self """ if not self.fwhm: im = Image(np.zeros(self.resid.shape), coordmap=self.coordmap) else: im = \ Image(self.fwhm, clobber=self.clobber, mode='w', coordmap=self.coordmap) self.fwhm = im if not self.resels: im = Image(np.zeros(self.resid.shape), coordmap=self.coordmap) else: im = \ Image(self.resels, clobber=self.clobber, mode='w', coordmap=self.coordmap) self.resels = im return self
def test_slice_time_correction(): # Make smooth time course at slice resolution TR = 2. n_vols = 25 n_slices = 10 # Create single volume shape_3d = (20, 30, n_slices) spatial_sigma = 4 time_sigma = n_slices * 5 # time sigma in TRs one_vol = np.random.normal(100, 25, size=shape_3d) gaussian_filter(one_vol, spatial_sigma, output=one_vol) # Add smoothed time courses. Time courses are at time resolution of one # slice time. So, there are n_slices time points per TR. n_vol_slices = n_slices * n_vols time_courses = np.random.normal(0, 15, size=shape_3d + (n_vol_slices, )) gaussian_filter1d(time_courses, time_sigma, output=time_courses) big_data = one_vol[..., None] + time_courses # Can the first time point be approximated from the later ones? first_signal = big_data[..., 0:n_vol_slices:n_slices] for name, time_to_slice in (('ascending', list(range(n_slices))), ('descending', list(range(n_slices)[::-1])), ('asc_alt_2', (list(range(0, n_slices, 2)) + list(range(1, n_slices, 2)))), ('desc_alt_2', (list(range(0, n_slices, 2)) + list(range(1, n_slices, 2)))[::-1])): slice_to_time = np.argsort(time_to_slice) acquired_signal = np.zeros_like(first_signal) for space_sno, time_sno in enumerate(slice_to_time): acquired_signal[..., space_sno, :] = \ big_data[..., space_sno, time_sno:n_vol_slices:n_slices] # do STC - minimizer will fail acquired_image = Image(acquired_signal, vox2scanner(np.eye(5))) stc = SpaceTimeRealign(acquired_image, TR, name, 2) stc.estimate(refscan=None, loops=1, between_loops=1, optimizer='steepest') # Check no motion estimated assert_array_equal([t.param for t in stc._transforms[0]], 0) corrected = stc.resample()[0].get_data() # check we approximate first time slice with correction assert_false( np.allclose(acquired_signal, corrected, rtol=1e-3, atol=0.1)) check_stc(first_signal, corrected, ref_slice=slice_to_time[0], rtol=5e-4, atol=1e-6)
def get_mode(seg_stack, out_file): img = load_image(seg_stack) new_coord = img[:, :, :, 0].coordmap data = img.get_data() mode = np.zeros(data.shape[:3]) for i in xrange(data.shape[0]): for j in xrange(data.shape[1]): for k in xrange(data.shape[2]): u, indices = np.unique(data[i, j, k, :], return_inverse=True) voxel_mode = u[np.argmax(np.bincount(indices))] print "mode at {0},{1},{2} = {3}".format(i, j, k, voxel_mode) mode[i, j, k] = voxel_mode mode_image = Image(mode, new_coord) save_image(mode_image, out_file) return mode
def ComplexRatios(dataFile, ratiosFile): dataImg = load_image(dataFile) shape = (dataImg.shape[0], dataImg.shape[1], dataImg.shape[2], dataImg.shape[3]-1) dataRatios = np.zeros(shape, dtype=np.complex64) for i in range(shape[3]): print i dataImg0 = dataImg[:, :, :, i] data0 = dataImg0.get_data() dataImg1 = dataImg[:, :, :, i+1] data1 = dataImg1.get_data() dataRatios[:, :, :, i] = data1/data0 ratiosImg = Image(dataRatios, dataImg.coordmap) newimg = save_image(ratiosImg, ratiosFile)
def test_resample2d(): g = AffineTransform.from_params('ij', 'xy', np.diag([0.5, 0.5, 1])) i = Image(np.ones((100, 90)), g) i.get_data()[50:55, 40:55] = 3. # This mapping describes a mapping from the "target" physical # coordinates to the "image" physical coordinates. The 3x3 matrix # below indicates that the "target" physical coordinates are related # to the "image" physical coordinates by a shift of -4 in each # coordinate. Or, to find the "image" physical coordinates, given # the "target" physical coordinates, we add 4 to each "target # coordinate". The resulting resampled image should show the # overall image shifted -8,-8 voxels towards the origin a = np.identity(3) a[:2, -1] = 4. ir = resample(i, i.coordmap, a, (100, 90)) assert_array_almost_equal(ir.get_data()[42:47, 32:47], 3.)
def test_resample2d1(): # Tests the same as test_resample2d, only using a callable instead of # an AffineTransform instance g = AffineTransform.from_params('ij', 'xy', np.diag([0.5, 0.5, 1])) i = Image(np.ones((100, 90)), g) i.get_data()[50:55, 40:55] = 3. a = np.identity(3) a[:2, -1] = 4. A = np.identity(2) b = np.ones(2) * 4 def mapper(x): return np.dot(x, A.T) + b ir = resample(i, i.coordmap, mapper, (100, 90)) assert_array_almost_equal(ir.get_data()[42:47, 32:47], 3.)
def seg_recovery(y_pred, filename): label = load_image(PRE_LABEL_PATH + filename) shape = label.get_data().shape segment = np.zeros(shape) h1 = y_pred[0].around() h2 = y_pred[1].around() area = crop_setting['3d' + str(shape[2])] segment[area['x'][0]:area['x'][1], area['y'][0]:area['y'][1], area['z1'][0]:area['z1'][1], 0] = h1[0] segment[area['x'][0]:area['x'][1], area['y'][0]:area['y'][1], area['z2'][0]:area['z2'][1], 1] = h2[0] img = Image(segment, label.coordmap) save_image(img, OUTPUT + filename)
def test_roundtrip_from_array(): data = np.random.rand(10, 20, 30) img = Image(data, AfT('kji', 'xyz', np.eye(4))) with InTemporaryDirectory(): save_image(img, 'img.nii.gz') img2 = load_image('img.nii.gz') data2 = img2.get_data() # verify data assert_almost_equal(data2, data) assert_almost_equal(data2.mean(), data.mean()) assert_almost_equal(data2.min(), data.min()) assert_almost_equal(data2.max(), data.max()) # verify shape and ndims assert_equal(img2.shape, img.shape) assert_equal(img2.ndim, img.ndim) # verify affine assert_almost_equal(img2.affine, img.affine)
def test_resample3d(): g = AffineTransform.from_params('ijk', 'xyz', np.diag([0.5, 0.5, 0.5, 1])) shape = (100, 90, 80) i = Image(np.ones(shape), g) i.get_data()[50:55, 40:55, 30:33] = 3. # This mapping describes a mapping from the "target" physical # coordinates to the "image" physical coordinates. The 4x4 matrix # below indicates that the "target" physical coordinates are related # to the "image" physical coordinates by a shift of -4 in each # coordinate. Or, to find the "image" physical coordinates, given # the "target" physical coordinates, we add 4 to each "target # coordinate". The resulting resampled image should show the # overall image shifted [-6,-8,-10] voxels towards the origin a = np.identity(4) a[:3, -1] = [3, 4, 5] ir = resample(i, i.coordmap, a, (100, 90, 80)) assert_array_almost_equal(ir.get_data()[44:49, 32:47, 20:23], 3.)