Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def make_sct_image(data):
"""
:return: an Image (3D) in RAS+ (aka SCT LPI) space
data: scalar
"""
affine = np.eye(4)
nii = nibabel.nifti1.Nifti1Image(np.array([data, data]), affine)
img = Image(nii.get_data(), hdr=nii.header, orientation="LPI", dim=nii.header.get_data_shape())
return img
def fake_3dimage_nib_big():
"""
:return: an empty 3-d nibabel Image
"""
nx, ny, nz = 29, 39, 19 # image dimension
data = np.zeros((nx, ny, nz), dtype=np.int8)
data[14, 19, 9] = 1.
affine = np.eye(4)
# Create nibabel object
nii = nib.nifti1.Nifti1Image(data, affine)
return nii
"""
# Author: Oualid Benkarim
# License: BSD 3 clause
from vtk import vtkPolyData
from vtk.util.vtkAlgorithm import VTKPythonAlgorithmBase
from ..decorators import wrap_input
from ...mesh.mesh_creation import build_polydata
try:
import nibabel as nb
INTENT_POINTS = nb.nifti1.intent_codes['NIFTI_INTENT_POINTSET']
INTENT_CELLS = nb.nifti1.intent_codes['NIFTI_INTENT_TRIANGLE']
INTENT_POINTDATA = nb.nifti1.intent_codes['NIFTI_INTENT_ESTIMATE']
has_nibabel = True
except:
has_nibabel = False
def _read_gifti(ipth):
g = nb.load(ipth)
points = g.get_arrays_from_intent(INTENT_POINTS)[0].data
cells = g.get_arrays_from_intent(INTENT_CELLS)[0].data
s = build_polydata(points, cells=cells)
for a1 in g.darrays:
if output == 'image':
return nb.nifti1.Nifti1Image(image, None, self.get_header())
elif output == 'array':
return image
else:
image = image.ravel()
if output == 'vector':
return image.ravel()
image = np.reshape(image, self.volume.shape)
if output == 'array':
return image
return nb.nifti1.Nifti1Image(image, None, self.get_header())
def _spm_nan_to_number(self, filename, temp_filename):
nan_img = nib.load(filename)
nan_data = nan_img.get_data()
nan_header = nan_img.get_header()
nan_data = np.nan_to_num(nan_data)
nan_image = nib.nifti1.Nifti1Image(nan_data, None, nan_header)
nib.nifti1.save(nan_image, temp_filename)
return temp_filename
values, it can be 'gray', 'red2yellow', 'blue2green', 'ranbow'...
cross_pos : a list containing [x, y, z]
Default is None
Returns
-------
VolumeDataset
"""
if isinstance(source, np.ndarray):
self._data = np.rot90(source)
if name == None:
self._name = 'new_image'
else:
self._name = str(name)
if not isinstance(header, nib.nifti1.Nifti1Header):
raise ValueError("Parameter header must be specified!")
elif header.get_data_shape() == source.shape:
self._header = header
self._img = None
else:
raise ValueError("Data dimension does not match.")
else:
self._img = nib.load(source)
self._header = self._img.get_header()
basename = os.path.basename(source.strip('/'))
self._name = re.sub(r'(.*)\.nii(\.gz)?', r'\1', basename)
self.save_mem_load()
# For convenience, define a shift variable
self._y_shift = self.get_data_shape()[1] - 1
is_trk = False
is_sft = False
if isinstance(reference, str):
try:
header = nib.load(reference).header
is_nifti = True
except nib.filebasedimages.ImageFileError:
pass
try:
header = nib.streamlines.load(reference, lazy_load=True).header
_, extension = os.path.splitext(reference)
if extension == '.trk':
is_trk = True
except ValueError:
pass
elif isinstance(reference, nib.nifti1.Nifti1Image):
header = reference.header
is_nifti = True
elif isinstance(reference, nib.streamlines.trk.TrkFile):
header = reference.header
is_trk = True
elif isinstance(reference, nib.nifti1.Nifti1Header):
header = reference
is_nifti = True
elif isinstance(reference, dict) and 'magic_number' in reference:
header = reference
is_trk = True
elif isinstance(reference, dipy.io.stateful_tractogram.StatefulTractogram):
is_sft = True
if is_nifti:
affine = header.get_best_affine()
def label_with_dilation(to_label_nii_fname, dilated_nii_fname, out_nii_fname):
"Label one nifti with its dilation, cf seeg-ct.sh"
# TODO could make dilation with ndimage also.
import nibabel, scipy.ndimage
mask = nibabel.load('CT-mask.nii.gz')
dil_mask = nibabel.load('CT-dil-mask.nii.gz')
lab, n = scipy.ndimage.label(dil_mask.get_data())
print('[label_with_dilation] %d objects found.' % (n, ))
lab_mask_nii = nibabel.nifti1.Nifti1Image(lab * mask.get_data(), mask.affine)
nibabel.save(lab_mask_nii, 'CT-lab-mask.nii.gz')
bvals, bvecs = pr_hdr.get_bvals_bvecs()
if not opts.keep_trace: # discard Philips DTI trace if present
if bvecs is not None:
bad_mask = np.logical_and(bvals != 0, (bvecs == 0).all(axis=1))
if bad_mask.sum() > 0:
pl = 's' if bad_mask.sum() != 1 else ''
verbose('Removing %s DTI trace volume%s'
% (bad_mask.sum(), pl))
good_mask = ~bad_mask
in_data = in_data[..., good_mask]
bvals = bvals[good_mask]
bvecs = bvecs[good_mask]
# Make corresponding NIfTI image
nimg = nifti1.Nifti1Image(in_data, affine, pr_hdr)
nhdr = nimg.header
nhdr.set_data_dtype(out_dtype)
nhdr.set_slope_inter(slope, intercept)
nhdr.set_sform(affine, code=1)
nhdr.set_qform(affine, code=1)
if 'parse' in opts.minmax:
# need to get the scaled data
verbose('Loading (and scaling) the data to determine value range')
if opts.minmax[0] == 'parse':
nhdr['cal_min'] = in_data.min() * slope + intercept
else:
nhdr['cal_min'] = float(opts.minmax[0])
if opts.minmax[1] == 'parse':
nhdr['cal_max'] = in_data.max() * slope + intercept
else:
new_sub_dirs = []
for sub_dir in self.subject_dirs:
REC_files = glob(op.join(sub_dir, '*.REC'))
PAR_files = glob(op.join(sub_dir, '*.PAR'))
# Create scaninfo from PAR and convert .REC to nifti
for REC, PAR in zip(REC_files, PAR_files):
self.create_scaninfo(PAR)
REC_name = REC[:-4]
if not op.exists(REC_name + '.nii'):
print("Processing file %s ..." % REC_name, end="")
PR_obj = nib.parrec.load(REC)
nib.nifti1.save(PR_obj,REC_name)
print(" done.")
else:
print("File %s was already converted." % REC_name)
niftis = glob(op.join(sub_dir, '*.nii'))
if niftis:
os.system('gzip %s' % op.join(sub_dir, '*.nii'))
if remove_nifti:
os.system('rm %s' % op.join(sub_dir, '*.nii'))
new_dir = op.join(self.working_dir, op.basename(sub_dir))
shutil.copytree(sub_dir, new_dir)
shutil.rmtree(sub_dir)