Exemplo n.º 1
0
def test_labels1():
    img = load_image(funcfile)
    parcelmap = fromarray(np.asarray(img[0]), 'kji', 'zyx')    
    parcelmap = (np.asarray(parcelmap) * 100).astype(np.int32)
    v = 0
    for i, d in fmri_generator(img, parcels(parcelmap)):
        v += d.shape[1]
    assert_equal(v, parcelmap.size)
Exemplo n.º 2
0
    def aniso2iso(self, image, spacing, dimensions):
        '''
    from dipy.align.aniso2iso
    '''
        header = image.header
        oldspacing = header.get_zooms()
        olddimensions = image.shape[:3]

        if spacing == 'no':
            newspacing = (min(oldspacing), min(oldspacing), min(oldspacing))
        else:
            newspacing = (float(spacing.split(',')[0]),
                          float(spacing.split(',')[1]),
                          float(spacing.split(',')[2]))

        if dimensions == 'no':
            newdimensions = olddimensions
        else:
            newdimensions = (int(dimensions.split(',')[0]),
                             int(dimensions.split(',')[1]),
                             int(dimensions.split(',')[2]))

        c.info('Resampling the master image..')
        c.info('    old spacing ' + str(oldspacing))
        c.info('    old dimensions ' + str(olddimensions))

        # work on a numpy array to resample to isotropic spacing
        R = numpy.diag(numpy.array(newspacing) / numpy.array(oldspacing))
        new_shape = numpy.array(oldspacing) / numpy.array(
            newspacing) * numpy.array(newdimensions)
        new_shape = numpy.round(new_shape).astype('i8')
        newImage = affine_transform(input=image,
                                    matrix=R,
                                    offset=numpy.zeros(3, ),
                                    output_shape=tuple(new_shape),
                                    order=0)
        Rx = numpy.eye(4)
        Rx[:3, :3] = R
        # get the mew world-image matrix
        affine = numpy.dot(image.coordmap.affine, Rx)

        # convert to NiPy image

        # copy the old coordmap and replace the affine matrix
        newCoordMap = image.coordmap
        newCoordMap.affine = affine

        # create a new NiPy image with the resampled data and the new coordmap (including the affine matrix)
        nipyImage = fromarray(newImage, '', '', newCoordMap)

        c.info('    new spacing ' + str(newspacing))
        c.info('    new dimensions ' + str(nipyImage.shape[:3]))

        return nipyImage
Exemplo n.º 3
0
def uint8_to_dtype(dtype, name):
    dtype = dtype
    shape = (2,3,4)
    dmax = np.iinfo(np.uint8).max
    data = np.random.randint(0, dmax, size=shape)
    data[0,0,0] = 0
    data[1,0,0] = dmax
    data = data.astype(np.uint8) # randint returns np.int32
    img = fromarray(data, 'kji', 'zxy')
    newimg = save_image(img, name, dtype=dtype)
    return newimg.get_data(), data
Exemplo n.º 4
0
def test_slicing_returns_image():
    data = np.ones((2,3,4))
    img = fromarray(data, 'kji', 'zyx')
    assert isinstance(img, Image)
    assert img.ndim == 3
    # 2D slice
    img2D = img[:,:,0]
    assert isinstance(img2D, Image)
    assert img2D.ndim == 2
    # 1D slice
    img1D = img[:,0,0]
    assert isinstance(img1D, Image)
    assert img1D.ndim == 1
Exemplo n.º 5
0
def float32_to_dtype(dtype, name):
    # Utility function for the scaling_float32 function
    dtype = dtype
    shape = (2,3,4)
    # set some value value for scaling our data
    scale = np.iinfo(np.uint16).max * 2.0
    data = np.random.normal(size=(2,3,4), scale=scale)
    data[0,0,0] = np.finfo(np.float32).max
    data[1,0,0] = np.finfo(np.float32).min
    # random.normal will return data as native machine type
    data = data.astype(np.float32)
    img = fromarray(data, 'kji', 'zyx')
    newimg = save_image(img, name, dtype=dtype)
    return newimg.get_data(), data
Exemplo n.º 6
0
def test_roundtrip_fromarray():
    data = np.random.rand(10,20,30)
    img = fromarray(data, 'kji', 'xyz')
    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)
Exemplo n.º 7
0
def test_roundtrip_fromarray():
    data = np.random.rand(10,20,30)
    img = fromarray(data, 'kji', 'xyz')
    fd, name = mkstemp(suffix='.nii.gz')
    tmpfile = open(name)
    save_image(img, tmpfile.name)
    img2 = load_image(tmpfile.name)
    data2 = np.asarray(img2)
    tmpfile.close()
    os.unlink(name)
    # verify data
    yield assert_true, np.allclose(data2, data)
    yield assert_true, np.allclose(data2.mean(), data.mean())
    yield assert_true, np.allclose(data2.min(), data.min())
    yield assert_true, np.allclose(data2.max(), data.max())
    # verify shape and ndims
    yield assert_equal, img2.shape, img.shape
    yield assert_equal, img2.ndim, img.ndim
    # verify affine
    yield assert_true, np.allclose(img2.affine, img.affine)
Exemplo n.º 8
0
from nipy.core.image import image
from nipy.core.api import Image, fromarray, merge_images, is_image
from nipy.core.api import parcels, data_generator, write_data
from nipy.core.reference.coordinate_map import Affine
from nipy.io.api import load_image

def setup():
    # Suppress warnings during tests to reduce noise
    warnings.simplefilter("ignore")

def teardown():
    # Clear list of warning filters
    warnings.resetwarnings()

_data = np.arange(24).reshape((4,3,2))
gimg = fromarray(_data, 'ijk', 'xyz')


def test_init():
    new = Image(np.asarray(gimg), gimg.coordmap)
    yield assert_array_almost_equal, np.asarray(gimg), np.asarray(new)
    yield assert_raises, ValueError, Image, None, None


def test_maxmin_values():
    y = np.asarray(gimg)
    yield assert_equal, y.shape, tuple(gimg.shape)
    yield assert_equal, y.max(), 23
    yield assert_equal, y.min(), 0.0

Exemplo n.º 9
0
# Specify the axis order of the input coordinates
input_coords = ['k', 'j', 'i']
output_coords = ['z','y','x']
#or
innames = ('kji')
outnames = ('zyx')
# either way works

# Build a CoordinateMap to create the image with
affine_coordmap = Affine.from_params(innames, outnames, affine_array)

# 2) Create a nipy image from the array and CoordinateMap

# Create new image
newimg = fromarray(arr, innames=innames, outnames=outnames, 
                                         coordmap=affine_coordmap)

################################################################################
# END HERE, for testing purposes only.
################################################################################
# Imports used just for development and testing.  Users typically
# would not uses these when creating an image.
from tempfile import mkstemp
from nipy.testing import assert_equal

# We use a temporary file for this example so as to not create junk
# files in the nipy directory.
fd, name = mkstemp(suffix='.nii.gz')
tmpfile = open(name)

# Save the nipy image to the specified filename
Exemplo n.º 10
0
"""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.core.api import fromarray, save_image

# create an array of zeros, the shape of your data array
zero_array = np.zeros((91,109,91))

# create an image from our array
img = fromarray(zero_array)

# 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 comap.

# from nipy.core.api import load_image
# img = load_image('foo.nii.gz')
# zeroarray = np.zeros(img.comap.shape)
# zeroimg = fromarray(zeroarray, comap=img.comap)
# newimg = save_image(zeroimg, 'tempimage.nii.gz')