本文整理汇总了Python中msct_image.Image.setFileName方法的典型用法代码示例。如果您正苦于以下问题:Python Image.setFileName方法的具体用法?Python Image.setFileName怎么用?Python Image.setFileName使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类msct_image.Image
的用法示例。
在下文中一共展示了Image.setFileName方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: crop_from_mask_with_background
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import setFileName [as 别名]
def crop_from_mask_with_background(self):
from numpy import asarray, einsum
image_in = Image(self.input_filename)
data_array = asarray(image_in.data)
data_mask = asarray(Image(self.mask).data)
assert data_array.shape == data_mask.shape
# Element-wise matrix multiplication:
new_data = None
dim = len(data_array.shape)
if dim == 3:
new_data = einsum('ijk,ijk->ijk', data_mask, data_array)
elif dim == 2:
new_data = einsum('ij,ij->ij', data_mask, data_array)
if self.background != 0:
from sct_maths import get_data_or_scalar
data_background = get_data_or_scalar(str(self.background), data_array)
data_mask_inv = data_mask.max() - data_mask
if dim == 3:
data_background = einsum('ijk,ijk->ijk', data_mask_inv, data_background)
elif dim == 2:
data_background = einsum('ij,ij->ij', data_mask_inv, data_background)
new_data += data_background
# set image out
image_in.setFileName(self.output_filename)
image_in.data = new_data
image_in.save()
示例2: remove_label
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import setFileName [as 别名]
def remove_label(self, symmetry=False):
"""
Compare two label images and remove any labels in input image that are not in reference image.
The symmetry option enables to remove labels from reference image that are not in input image
"""
# image_output = Image(self.image_input.dim, orientation=self.image_input.orientation, hdr=self.image_input.hdr, verbose=self.verbose)
image_output = Image(self.image_input, verbose=self.verbose)
image_output.data *= 0 # put all voxels to 0
result_coord_input, result_coord_ref = self.remove_label_coord(self.image_input.getNonZeroCoordinates(coordValue=True),
self.image_ref.getNonZeroCoordinates(coordValue=True), symmetry)
for coord in result_coord_input:
image_output.data[int(coord.x), int(coord.y), int(coord.z)] = int(round(coord.value))
if symmetry:
# image_output_ref = Image(self.image_ref.dim, orientation=self.image_ref.orientation, hdr=self.image_ref.hdr, verbose=self.verbose)
image_output_ref = Image(self.image_ref, verbose=self.verbose)
for coord in result_coord_ref:
image_output_ref.data[int(coord.x), int(coord.y), int(coord.z)] = int(round(coord.value))
image_output_ref.setFileName(self.fname_output[1])
image_output_ref.save('minimize_int')
self.fname_output = self.fname_output[0]
return image_output
示例3: clean_labeled_segmentation
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import setFileName [as 别名]
def clean_labeled_segmentation(fname_labeled_seg, fname_seg, fname_labeled_seg_new):
"""
Clean labeled segmentation by:
(i) removing voxels in segmentation_labeled that are not in segmentation and
(ii) adding voxels in segmentation that are not in segmentation_labeled
:param fname_labeled_seg:
:param fname_seg:
:param fname_labeled_seg_new: output
:return: none
"""
# remove voxels in segmentation_labeled that are not in segmentation
run('sct_maths -i '+fname_labeled_seg+' -mul '+fname_seg+' -o segmentation_labeled_mul.nii.gz')
# add voxels in segmentation that are not in segmentation_labeled
run('sct_maths -i '+fname_labeled_seg+' -dilate 2 -o segmentation_labeled_dilate.nii.gz') # dilate labeled segmentation
data_label_dilate = Image('segmentation_labeled_dilate.nii.gz').data
run('sct_maths -i segmentation_labeled_mul.nii.gz -bin 0 -o segmentation_labeled_mul_bin.nii.gz')
data_label_bin = Image('segmentation_labeled_mul_bin.nii.gz').data
data_seg = Image(fname_seg).data
data_diff = data_seg - data_label_bin
ind_nonzero = np.where(data_diff)
im_label = Image('segmentation_labeled_mul.nii.gz')
for i_vox in range(len(ind_nonzero[0])):
# assign closest label value for this voxel
ix, iy, iz = ind_nonzero[0][i_vox], ind_nonzero[1][i_vox], ind_nonzero[2][i_vox]
im_label.data[ix, iy, iz] = data_label_dilate[ix, iy, iz]
# save new label file (overwrite)
im_label.setFileName(fname_labeled_seg_new)
im_label.save()
示例4: main
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import setFileName [as 别名]
def main(args = None):
dim_list = ['x', 'y', 'z', 't']
if not args:
args = sys.argv[1:]
# Get parser info
parser = get_parser()
arguments = parser.parse(sys.argv[1:])
fname_in = arguments["-i"]
fname_out = arguments["-o"]
verbose = int(arguments['-v'])
# Build fname_out
if fname_out == '':
path_in, file_in, ext_in = extract_fname(fname_in)
fname_out = path_in+file_in+'_mean'+ext_in
# Open file.
nii = Image(fname_in)
data = nii.data
# run command
if '-otsu' in arguments:
param = arguments['-otsu']
data_out = otsu(data, param)
elif '-otsu_adap' in arguments:
param = arguments['-otsu_adap']
data_out = otsu_adap(data, param[0], param[1])
elif '-otsu_median' in arguments:
param = arguments['-otsu_median']
data_out = otsu_median(data, param[0], param[1])
elif '-thr' in arguments:
param = arguments['-thr']
data_out = threshold(data, param)
elif '-percent' in arguments:
param = arguments['-percent']
data_out = perc(data, param)
elif '-mean' in arguments:
dim = dim_list.index(arguments['-mean'])
data_out = compute_mean(data, dim)
elif '-std' in arguments:
dim = dim_list.index(arguments['-std'])
data_out = compute_std(data, dim)
elif '-dilate' in arguments:
data_out = dilate(data, arguments['-dilate'])
elif '-erode' in arguments:
data_out = erode(data, arguments['-dilate'])
else:
printv('No process applied.', 1, 'warning')
return
# Write output
nii.data = data_out
nii.setFileName(fname_out)
nii.save()
# display message
printv('Created file:\n--> '+fname_out+'\n', verbose, 'info')
示例5: set_orientation
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import setFileName [as 别名]
def set_orientation(im, orientation, data_inversion=False, filename=False, fname_out=''):
"""
Set orientation on image
:param im: either Image object or file name. Carefully set param filename.
:param orientation:
:param data_inversion:
:param filename:
:return:
"""
if fname_out:
pass
elif filename:
path, fname, ext = extract_fname(im)
fname_out = fname+'_'+orientation+ext
else:
fname_out = im.file_name+'_'+orientation+im.ext
if not data_inversion:
from sct_utils import run
if filename:
run('isct_orientation3d -i '+im+' -orientation '+orientation+' -o '+fname_out, 0)
im_out = fname_out
else:
run('isct_orientation3d -i '+im.absolutepath+' -orientation '+orientation+' -o '+fname_out, 0)
im_out = Image(fname_out)
else:
im_out = im.copy()
im_out.change_orientation(orientation, True)
im_out.setFileName(fname_out)
return im_out
示例6: concat_data
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import setFileName [as 别名]
def concat_data(fname_in, fname_out, dim):
"""
Concatenate data
:param fname_in: list of file names.
:param fname_out:
:param dim: dimension: 0, 1, 2, 3.
:return: none
"""
# create empty list
list_data = []
# loop across files
for i in range(len(fname_in)):
# append data to list
list_data.append(Image(fname_in[i]).data)
# expand dimension of all elements in the list if necessary
if dim > list_data[0].ndim-1:
list_data = [expand_dims(i, dim) for i in list_data]
# concatenate
try:
data_concat = concatenate(list_data, axis=dim)
except Exception as e:
sct.printv('\nERROR: Concatenation on line {}'.format(sys.exc_info()[-1].tb_lineno)+'\n'+str(e)+'\n', 1, 'error')
# write file
im = Image(fname_in[0])
im.data = data_concat
im.setFileName(fname_out)
im.save()
示例7: savePredictions
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import setFileName [as 别名]
def savePredictions(predictions, path_output, list_images, segmentation_image_size):
number_of_images = len(list_images)
predictions = numpy.reshape(predictions, [number_of_images, segmentation_image_size, segmentation_image_size, NUM_LABELS])
predictions = predictions[:, :, :, 1]
for i, pref in enumerate(predictions):
im_pred = Image(pref)
im_pred.setFileName(path_output+sct.add_suffix(list_images[i], '_pred'))
im_pred.save()
示例8: set_orientation
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import setFileName [as 别名]
def set_orientation(fname_in, orientation, fname_out, inversion=False):
if not inversion:
sct.run('isct_orientation3d -i '+fname_in+' -orientation '+orientation+' -o '+fname_out, 0)
else:
from msct_image import Image
input_image = Image(fname_in)
input_image.change_orientation(orientation, True)
input_image.setFileName(fname_out)
input_image.save()
# return full path
return os.path.abspath(fname_out)
示例9: concat_data
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import setFileName [as 别名]
def concat_data(fname_in_list, dim, pixdim=None):
"""
Concatenate data
:param im_in_list: list of images.
:param dim: dimension: 0, 1, 2, 3.
:param pixdim: pixel resolution to join to image header
:return im_out: concatenated image
"""
# WARNING: calling concat_data in python instead of in command line causes a non understood issue (results are different with both options)
from numpy import concatenate, expand_dims, squeeze
dat_list = []
data_concat_list = []
# check if shape of first image is smaller than asked dim to concatenate along
data0 = Image(fname_in_list[0]).data
if len(data0.shape) <= dim:
expand_dim = True
else:
expand_dim = False
for i, fname in enumerate(fname_in_list):
# if there is more than 100 images to concatenate, then it does it iteratively to avoid memory issue.
if i != 0 and i % 100 == 0:
data_concat_list.append(concatenate(dat_list, axis=dim))
im = Image(fname)
dat = im.data
if expand_dim:
dat = expand_dims(dat, dim)
dat_list = [dat]
del im
del dat
else:
im = Image(fname)
dat = im.data
if expand_dim:
dat = expand_dims(dat, dim)
dat_list.append(dat)
del im
del dat
if data_concat_list:
data_concat_list.append(concatenate(dat_list, axis=dim))
data_concat = concatenate(data_concat_list, axis=dim)
else:
data_concat = concatenate(dat_list, axis=dim)
# write file
im_out = Image(fname_in_list[0]).copy()
im_out.data = data_concat
im_out.setFileName(im_out.file_name+'_concat'+im_out.ext)
if pixdim is not None:
im_out.hdr['pixdim'] = pixdim
return im_out
示例10: copy_header
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import setFileName [as 别名]
def copy_header(fname_src, fname_dest):
"""
Copy header
:param fname_src: source file name
:param fname_dest: destination file name
:return:
"""
nii_src = Image(fname_src)
data_dest = Image(fname_dest).data
nii_src.setFileName(fname_dest)
nii_src.data = data_dest
nii_src.save()
示例11: get_im_from_list
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import setFileName [as 别名]
def get_im_from_list(self, data):
im = Image(data)
# set pix dimension
im.hdr.structarr['pixdim'][1] = self.param_data.axial_res
im.hdr.structarr['pixdim'][2] = self.param_data.axial_res
# set the correct orientation
im.setFileName('im_to_orient.nii.gz')
im.save()
im = set_orientation(im, 'IRP')
im = set_orientation(im, 'PIL', data_inversion=True)
return im
示例12: convert
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import setFileName [as 别名]
def convert(fname_in, fname_out, squeeze_data=True, type=None, verbose=1):
"""
Convert data
:return True/False
"""
from msct_image import Image
from sct_utils import printv
printv('sct_convert -i '+fname_in+' -o '+fname_out, verbose, 'code')
# Open file
im = Image(fname_in)
# Save file
im.setFileName(fname_out)
if type is not None:
im.changeType(type=type)
im.save(squeeze_data=squeeze_data)
return im
示例13: compute_dti
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import setFileName [as 别名]
def compute_dti(fname_in, fname_bvals, fname_bvecs, prefix):
"""
Compute DTI.
:param fname_in: input 4d file.
:param bvals: bvals txt file
:param bvecs: bvecs txt file
:param prefix: output prefix. Example: "dti_"
:return: True/False
"""
# Open file.
from msct_image import Image
nii = Image(fname_in)
data = nii.data
print('data.shape (%d, %d, %d, %d)' % data.shape)
# open bvecs/bvals
from dipy.io import read_bvals_bvecs
bvals, bvecs = read_bvals_bvecs(fname_bvals, fname_bvecs)
from dipy.core.gradients import gradient_table
gtab = gradient_table(bvals, bvecs)
# # mask and crop the data. This is a quick way to avoid calculating Tensors on the background of the image.
# from dipy.segment.mask import median_otsu
# maskdata, mask = median_otsu(data, 3, 1, True, vol_idx=range(10, 50), dilate=2)
# print('maskdata.shape (%d, %d, %d, %d)' % maskdata.shape)
# fit tensor model
import dipy.reconst.dti as dti
tenmodel = dti.TensorModel(gtab)
tenfit = tenmodel.fit(data)
# Compute metrics
printv('Computing metrics...', param.verbose)
# FA
from dipy.reconst.dti import fractional_anisotropy
nii.data = fractional_anisotropy(tenfit.evals)
nii.setFileName(prefix+'FA.nii.gz')
nii.save('float32')
# MD
from dipy.reconst.dti import mean_diffusivity
nii.data = mean_diffusivity(tenfit.evals)
nii.setFileName(prefix+'MD.nii.gz')
nii.save('float32')
# RD
from dipy.reconst.dti import radial_diffusivity
nii.data = radial_diffusivity(tenfit.evals)
nii.setFileName(prefix+'RD.nii.gz')
nii.save('float32')
# AD
from dipy.reconst.dti import axial_diffusivity
nii.data = axial_diffusivity(tenfit.evals)
nii.setFileName(prefix+'AD.nii.gz')
nii.save('float32')
return True
示例14: remove_overlap
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import setFileName [as 别名]
def remove_overlap(file_centerline_generated_by_labels, file_with_seg_or_centerline, output_file_name, parameter=0):
# Image file process
if parameter == 0 :
image_with_seg_or_centerline = Image(file_with_seg_or_centerline).copy()
z_test = ComputeZMinMax(image_with_seg_or_centerline)
zmax = z_test.Zmax
zmin = z_test.Zmin
tab1 = Image(file_centerline_generated_by_labels).copy()
size_x=tab1.data.shape[0]
size_y=tab1.data.shape[1]
#X_coor, Y_coor, Z_coor = (tab1.data).nonzero()
#nb_one = X_coor.shape[0]
#for i in range(0, nb_one):
# tab1.data[X_coor[i], Y_coor[i], X_coor[i]] = 0
#each slice under zmax is filled with zeros
print zmax
for i in range(zmin, zmax):
tab1.data[:,:,i] = np.zeros((size_x,size_y))
#Save file
tab1.setFileName(output_file_name)
tab1.save('minimize') #size of image should be minimized
# Text file process
if parameter == 1 :
z_test = ComputeZMinMax(file_with_seg_or_centerline)
zmax = z_test.Zmax
zmin = z_test.Zmin
print zmax
#create output txt file
tab2 = open(output_file_name , "w")
tab2.close()
#Delete lines under zmax
with open(file_centerline_generated_by_labels) as f:
data_line = f.readlines()
with open(output_file_name, "w") as f1:
for line in data_line:
words = line.split()
if int(words [0]) < zmin or int(words [0]) > zmax :
f1.write(line)
示例15: visualize_warp
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import setFileName [as 别名]
def visualize_warp(fname_warp, fname_grid=None, step=3, rm_tmp=True):
if fname_grid is None:
from numpy import zeros
tmp_dir = sct.tmp_create()
im_warp = Image(fname_warp)
os.chdir(tmp_dir)
assert len(im_warp.data.shape) == 5, "ERROR: Warping field does bot have 5 dimensions..."
nx, ny, nz, nt, ndimwarp = im_warp.data.shape
# nx, ny, nz, nt, px, py, pz, pt = im_warp.dim
# This does not work because dimensions of a warping field are not correctly read : it would be 1,1,1,1,1,1,1,1
sq = zeros((step, step))
sq[step - 1] = 1
sq[:, step - 1] = 1
dat = zeros((nx, ny, nz))
for i in range(0, dat.shape[0], step):
for j in range(0, dat.shape[1], step):
for k in range(dat.shape[2]):
if dat[i : i + step, j : j + step, k].shape == (step, step):
dat[i : i + step, j : j + step, k] = sq
fname_grid = "grid_" + str(step) + ".nii.gz"
im_grid = Image(param=dat)
grid_hdr = im_warp.hdr
im_grid.hdr = grid_hdr
im_grid.setFileName(fname_grid)
im_grid.save()
fname_grid_resample = sct.add_suffix(fname_grid, "_resample")
sct.run("sct_resample -i " + fname_grid + " -f 3x3x1 -x nn -o " + fname_grid_resample)
fname_grid = tmp_dir + fname_grid_resample
os.chdir("..")
path_warp, file_warp, ext_warp = sct.extract_fname(fname_warp)
grid_warped = path_warp + "grid_warped_gm" + ext_warp
sct.run("sct_apply_transfo -i " + fname_grid + " -d " + fname_grid + " -w " + fname_warp + " -o " + grid_warped)
if rm_tmp:
sct.run("rm -rf " + tmp_dir, error_exit="warning")
return grid_warped