NiBabel

Access a cacophony of neuro-imaging file formats

Previous topic

nibabel.volumeutils.array_from_file

Next topic

nibabel.volumeutils.calculate_scale

Reggie -- the one

nibabel.volumeutils.array_to_file

nibabel.volumeutils.array_to_file(data, fileobj, out_dtype=None, offset=0, intercept=0.0, divslope=1.0, mn=None, mx=None, order='F', nan2zero=True)

Helper function for writing arrays to disk

Writes arrays as scaled by intercept and divslope, and clipped at (prescaling) mn minimum, and mx maximum.

Parameters :

data : array

array to write

fileobj : file-like

file-like object implementing write method.

out_dtype : None or dtype, optional

dtype to write array as. Data array will be coerced to this dtype before writing. If None (default) then use input data type.

offset : int, optional

offset into fileobj at which to start writing data. Default is 0.

intercept : scalar, optional

scalar to subtract from data, before dividing by divslope. Default is 0.0

divslope : None or scalar, optional

scalefactor to divide data by before writing. Default is 1.0. If None, there is no valid data, we write zeros.

mn : scalar, optional

minimum threshold in (unscaled) data, such that all data below this value are set to this value. Default is None (no threshold)

mx : scalar, optional

maximum threshold in (unscaled) data, such that all data above this value are set to this value. Default is None (no threshold)

order : {‘F’, ‘C’}, optional

memory order to write array. Default is ‘F’

nan2zero : {True, False}, optional

Whether to set NaN values to 0 when writing integer output. Defaults to True. If False, NaNs will be represented as numpy does when casting, and this can be odd (often the lowest available integer value)

Examples

>>> from StringIO import StringIO #23dt : BytesIO
>>> sio = StringIO() #23dt : BytesIO
>>> data = np.arange(10, dtype=np.float)
>>> array_to_file(data, sio, np.float)
>>> sio.getvalue() == data.tostring('F')
True
>>> _ = sio.truncate(0); _ = sio.seek(0) # outputs 0 in python 3
>>> array_to_file(data, sio, np.int16)
>>> sio.getvalue() == data.astype(np.int16).tostring()
True
>>> _ = sio.truncate(0); _ = sio.seek(0)
>>> array_to_file(data.byteswap(), sio, np.float)
>>> sio.getvalue() == data.byteswap().tostring('F')
True
>>> _ = sio.truncate(0); _ = sio.seek(0)
>>> array_to_file(data, sio, np.float, order='C')
>>> sio.getvalue() == data.tostring('C')
True