NiBabel

Access a cacophony of neuro-imaging file formats

Previous topic

nibabel.volumeutils.array_from_file

Next topic

nibabel.volumeutils.best_write_scale_ftype

This Page

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 : None or int, optional

offset into fileobj at which to start writing data. Default is 0. None means start at current file position

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). The typical use is to set -np.inf in the data to have this value (which might be the minimum non-finite value in the data).

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). The typical use is to set np.inf in the data to have this value (which might be the maximum non-finite value in the data).

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; this depends on the underlying C library and is undefined. In practice nan2zero == False might be a good choice when you completely sure there will be no NaNs in the data. This value ignore for float ouptut types.

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