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 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 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 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_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 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 test_save2b(): # A test to ensure that when a file is saved, the affine and the # data agree. This image comes from a NIFTI file. This example has a # non-diagonal affine matrix for the spatial part, but is 'diagonal' for the # space part. # # make a 5x5 transformation (for 4d image) step = np.array([3.45, 2.3, 4.5, 6.9]) A = np.random.standard_normal((3,3)) B = np.diag(list(step)+[1]) B[:3, :3] = A shape = (13,5,7,3) cmap = api.vox2mni(B) data = np.random.standard_normal(shape) img = api.Image(data, cmap) with InTemporaryDirectory(): save_image(img, TMP_FNAME) img2 = load_image(TMP_FNAME) assert_array_almost_equal(img.affine, img2.affine) assert_equal(img.shape, img2.shape) assert_array_almost_equal(img2.get_data(), img.get_data()) del img2
def test_save2b(): # A test to ensure that when a file is saved, the affine and the # data agree. This image comes from a NIFTI file. This example has a # non-diagonal affine matrix for the spatial part, but is 'diagonal' for the # space part. # # make a 5x5 transformation (for 4d image) step = np.array([3.45, 2.3, 4.5, 6.9]) A = np.random.standard_normal((3, 3)) B = np.diag(list(step) + [1]) B[:3, :3] = A shape = (13, 5, 7, 3) cmap = api.vox2mni(B) data = np.random.standard_normal(shape) img = api.Image(data, cmap) with InTemporaryDirectory(): save_image(img, TMP_FNAME) img2 = load_image(TMP_FNAME) assert_array_almost_equal(img.affine, img2.affine) assert_equal(img.shape, img2.shape) assert_array_almost_equal(img2.get_data(), img.get_data()) del img2
#!/usr/bin/env python # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """This example shows how to create a temporary image to use during processing. The array is filled with zeros. """ import numpy as np from nipy import load_image, save_image from nipy.core.api import Image, vox2mni # create an array of zeros, the shape of your data array zero_array = np.zeros((91,109,91)) # create an image from our array. The image will be in MNI space img = Image(zero_array, vox2mni(np.diag([2, 2, 2, 1]))) # save the image to a file newimg = save_image(img, 'tempimage.nii.gz') # Example of creating a temporary image file from an existing image with a # matching coordinate map. img = load_image('tempimage.nii.gz') zeroarray = np.zeros(img.shape) zeroimg = Image(zeroarray, img.coordmap) newimg = save_image(zeroimg, 'another_tempimage.nii.gz')
def save_nii(image, file_path): nipy.save_image(Image(image, vox2mni(np.eye(4))), file_path)
rot[:3, :3] = euler.euler2mat(0, 0, -angle) # downsample to make smaller output image downsamp = 1/3 epi_scale = np.diag([downsamp, downsamp, downsamp, 1]) # template voxels to epi box image voxels vox2epi_vox = epi_scale.dot(rot.dot(epi_trans)) # epi image voxels to mm epi_vox2mm = t2_img.affine.dot(npl.inv(vox2epi_vox)) # downsampled image shape epi_vox_shape = np.array([data.shape[0], epi_x_len, epi_y_len]) * downsamp # Make sure dimensions are odd by rounding up or down # This makes the voxel center an integer index, which is convenient epi_vox_shape = [np.floor(d) if np.floor(d) % 2 else np.ceil(d) for d in epi_vox_shape] # resample, preserving affine epi_cmap = nca.vox2mni(epi_vox2mm) epi = rsm.resample(t2_img, epi_cmap, np.eye(4), epi_vox_shape) epi_data = epi.get_data() # Do the same kind of thing for the anatomical scan anat_vox_sizes = [2.75, 2.75, 2.75] anat_scale = npl.inv(np.diag(anat_vox_sizes + [1])) anat_trans = np.eye(4) anat_trans[:3, 3] = -np.array([0, anat_box[0, 0], anat_box[0, 1]]) vox2anat_vox = anat_scale.dot(anat_trans) anat_vox2mm = t1_img.affine.dot(npl.inv(vox2anat_vox)) anat_vox_shape = np.round(np.divide( [data.shape[0], anat_x_len, anat_y_len], anat_vox_sizes)) anat_cmap = nca.vox2mni(anat_vox2mm) anat = rsm.resample(t1_img, anat_cmap, np.eye(4), anat_vox_shape) anat_data = anat.get_data()
#-*- coding: utf-8 -*- from nipy import save_image import numpy as np from nipy.core.api import Image, vox2mni rawarray = np.ones((43,128,128), dtype=np.uint8) arr_img = Image(rawarray, vox2mni(np.eye(4))) ##affine print arr_img.shape newimg = save_image(arr_img, 'G:\\Userworkspace\\brain-pca\\niwe.nii.gz') #用affine,将image转 成3d的东西 nipy.pdf在brain里面 #print save_image.func_doc #cmap = AffineTransform('kji', 'zxy', np.eye(4)) #img = Image(data, cmap)