本文整理汇总了Python中msct_image.Image.save方法的典型用法代码示例。如果您正苦于以下问题:Python Image.save方法的具体用法?Python Image.save怎么用?Python Image.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类msct_image.Image
的用法示例。
在下文中一共展示了Image.save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: remove_label
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import save [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
示例2: clean_labeled_segmentation
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import save [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()
示例3: main
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import save [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')
示例4: crop_from_mask_with_background
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import save [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()
示例5: concat_data
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import save [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()
示例6: savePredictions
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import save [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()
示例7: get_minimum_path_nii
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import save [as 别名]
def get_minimum_path_nii(fname):
from msct_image import Image
data=Image(fname)
vesselness_data = data.data
raw_orient=data.change_orientation()
data.data=get_minimum_path(data.data, invert=1)
data.change_orientation(raw_orient)
data.file_name += '_minimalpath'
data.save()
示例8: set_orientation
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import save [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: copy_header
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import save [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()
示例10: get_im_from_list
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import save [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
示例11: convert
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import save [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
示例12: compute_dti
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import save [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
示例13: remove_overlap
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import save [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)
示例14: output_debug_file
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import save [as 别名]
def output_debug_file(self, img, data, file_name):
"""
This method writes a nifti file that corresponds to a step in the algorithm for easy debug.
The new nifti file uses the header from the the image passed as parameter
:param data: data to be written to file
:param file_name: filename...
:return: None
"""
if self.verbose == 2:
current_folder = os.getcwd()
# os.chdir(self.path_tmp)
try:
img = Image(img)
img.data = data
img.change_orientation(self.raw_orientation)
img.file_name = file_name
img.save()
except Exception, e:
print e
示例15: __init__
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import save [as 别名]
def __init__(self, target_fname, sc_seg_fname, t2_data=None, denoising=True):
self.t2star = 't2star.nii.gz'
self.sc_seg = 't2star_sc_seg.nii.gz'
self.t2 = 't2.nii.gz'
self.t2_seg = 't2_seg.nii.gz'
self.t2_landmarks = 't2_landmarks.nii.gz'
self.resample_to = 0.3
sct.run('cp ../' + target_fname + ' ./' + self.t2star)
sct.run('cp ../' + sc_seg_fname + ' ./' + self.sc_seg)
nx, ny, nz, nt, self.original_px, self.original_py, pz, pt = sct.get_dimension(self.t2star)
if round(self.original_px, 2) != self.resample_to or round(self.original_py, 2) != self.resample_to:
self.t2star = resample_image(self.t2star, npx=self.resample_to, npy=self.resample_to)
self.sc_seg = resample_image(self.sc_seg, binary=True, npx=self.resample_to, npy=self.resample_to)
t2star_im = Image(self.t2star)
if denoising:
t2star_im.denoise_ornlm()
t2star_im.save()
self.t2star = t2star_im.file_name + t2star_im.ext
'''
status, t2_star_orientation = sct.run('sct_orientation -i ' + self.t2star)
self.original_orientation = t2_star_orientation[4:7]
'''
self.original_orientation = t2star_im.orientation
self.square_mask = crop_t2_star(self.t2star, self.sc_seg, box_size=75)
self.treated_target = sct.extract_fname(self.t2star)[1] + '_seg_in_croped.nii.gz'
self.level_fname = None
if t2_data is not None:
sct.run('cp ../' + t2_data[0] + ' ./' + self.t2)
sct.run('cp ../' + t2_data[1] + ' ./' + self.t2_seg)
sct.run('cp ../' + t2_data[2] + ' ./' + self.t2_landmarks)
self.level_fname = compute_level_file(self.t2star, self.sc_seg, self.t2, self.t2_seg, self.t2_landmarks)