本文整理汇总了Python中msct_image.Image.data方法的典型用法代码示例。如果您正苦于以下问题:Python Image.data方法的具体用法?Python Image.data怎么用?Python Image.data使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类msct_image.Image
的用法示例。
在下文中一共展示了Image.data方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: execute
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import data [as 别名]
def execute(self):
"""
This method executes the symmetry detection
:return: returns the symmetry data
"""
img = Image(self.input_image)
raw_orientation = img.change_orientation()
data = np.squeeze(img.data)
dim = data.shape
section_length = dim[1]/self.nb_sections
result = np.zeros(dim)
for i in range(0, self.nb_sections):
if (i+1)*section_length > dim[1]:
y_length = (i+1)*section_length - ((i+1)*section_length - dim[1])
result[:, i*section_length:i*section_length + y_length, :] = symmetry_detector_right_left(data[:, i*section_length:i*section_length + y_length, :], cropped_xy=self.crop_xy)
sym = symmetry_detector_right_left(data[:, i*section_length:(i+1)*section_length, :], cropped_xy=self.crop_xy)
result[:, i*section_length:(i+1)*section_length, :] = sym
result_image = Image(img)
if len(result_image.data) == 4:
result_image.data = result[:,:,:,np.newaxis]
else:
result_image.data = result
result_image.change_orientation(raw_orientation)
return result_image.data
示例2: compute_dti
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import data [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
示例3: crop_from_mask_with_background
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import data [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()
示例4: main
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import data [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: concat_data
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import data [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: get_minimum_path_nii
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import data [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()
示例7: concat_data
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import data [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
示例8: copy_header
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import data [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()
示例9: output_debug_file
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import data [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
示例10: label_discs
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import data [as 别名]
def label_discs(fname_seg_labeled, verbose=1):
"""
Label discs from labaled_segmentation
:param fname_seg_labeld: fname of the labeled segmentation
:param verbose:
:return:
"""
# open labeled segmentation
im_seg_labeled = Image(fname_seg_labeled)
orientation_native = im_seg_labeled.change_orientation('RPI')
nx, ny, nz = im_seg_labeled.dim[0], im_seg_labeled.dim[1], im_seg_labeled.dim[2]
data_disc = np.zeros([nx, ny, nz])
vertebral_level_previous = np.max(im_seg_labeled.data)
# loop across z
for iz in range(nz):
# get 2d slice
slice = im_seg_labeled.data[:, :, iz]
# check if at least one voxel is non-zero
if np.any(slice):
slice_one = np.copy(slice)
# set all non-zero values to 1
slice_one[slice.nonzero()] = 1
# compute center of mass
cx, cy = [int(x) for x in np.round(center_of_mass(slice_one)).tolist()]
# retrieve vertebral level
vertebral_level = slice[cx, cy]
# if smaller than previous level, then labeled as a disc
if vertebral_level < vertebral_level_previous:
# label disc
# print 'iz='+iz+', disc='+vertebral_level
data_disc[cx, cy, iz] = vertebral_level
# update variable
vertebral_level_previous = vertebral_level
# save disc labeled file
im_seg_labeled.file_name += '_disc'
im_seg_labeled.data = data_disc
im_seg_labeled.change_orientation(orientation_native)
im_seg_labeled.save()
示例11: create_label_z
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import data [as 别名]
def create_label_z(fname_seg, z, value):
"""
Create a label at coordinates x_center, y_center, z
:param fname_seg: segmentation
:param z: int
:return: fname_label
"""
fname_label = 'labelz.nii.gz'
nii = Image(fname_seg)
orientation_origin = nii.change_orientation('RPI') # change orientation to RPI
nx, ny, nz, nt, px, py, pz, pt = nii.dim # Get dimensions
# find x and y coordinates of the centerline at z using center of mass
from scipy.ndimage.measurements import center_of_mass
x, y = center_of_mass(nii.data[:, :, z])
x, y = int(round(x)), int(round(y))
nii.data[:, :, :] = 0
nii.data[x, y, z] = value
# dilate label to prevent it from disappearing due to nearestneighbor interpolation
from sct_maths import dilate
nii.data = dilate(nii.data, [3])
nii.setFileName(fname_label)
nii.change_orientation(orientation_origin) # put back in original orientation
nii.save()
return fname_label
示例12: main
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import data [as 别名]
def main():
# Initialization
fname_data = ''
suffix_out = '_crop'
remove_temp_files = param.remove_temp_files
verbose = param.verbose
fsloutput = 'export FSLOUTPUTTYPE=NIFTI; ' # for faster processing, all outputs are in NIFTI
remove_temp_files = param.remove_temp_files
# Parameters for debug mode
if param.debug:
print '\n*** WARNING: DEBUG MODE ON ***\n'
fname_data = path_sct+'/testing/data/errsm_23/t2/t2.nii.gz'
remove_temp_files = 0
else:
# Check input parameters
try:
opts, args = getopt.getopt(sys.argv[1:],'hi:r:v:')
except getopt.GetoptError:
usage()
if not opts:
usage()
for opt, arg in opts:
if opt == '-h':
usage()
elif opt in ('-i'):
fname_data = arg
elif opt in ('-r'):
remove_temp_files = int(arg)
elif opt in ('-v'):
verbose = int(arg)
# display usage if a mandatory argument is not provided
if fname_data == '':
usage()
# Check file existence
sct.printv('\nCheck file existence...', verbose)
sct.check_file_exist(fname_data, verbose)
# Get dimensions of data
sct.printv('\nGet dimensions of data...', verbose)
nx, ny, nz, nt, px, py, pz, pt = Image(fname_data).dim
sct.printv('.. '+str(nx)+' x '+str(ny)+' x '+str(nz), verbose)
# check if 4D data
if not nt == 1:
sct.printv('\nERROR in '+os.path.basename(__file__)+': Data should be 3D.\n', 1, 'error')
sys.exit(2)
# print arguments
print '\nCheck parameters:'
print ' data ................... '+fname_data
print
# Extract path/file/extension
path_data, file_data, ext_data = sct.extract_fname(fname_data)
path_out, file_out, ext_out = '', file_data+suffix_out, ext_data
# create temporary folder
path_tmp = 'tmp.'+time.strftime("%y%m%d%H%M%S")+'/'
sct.run('mkdir '+path_tmp)
# copy files into tmp folder
sct.run('isct_c3d '+fname_data+' -o '+path_tmp+'data.nii')
# go to tmp folder
os.chdir(path_tmp)
# change orientation
sct.printv('\nChange orientation to RPI...', verbose)
set_orientation('data.nii', 'RPI', 'data_rpi.nii')
# get image of medial slab
sct.printv('\nGet image of medial slab...', verbose)
image_array = nibabel.load('data_rpi.nii').get_data()
nx, ny, nz = image_array.shape
scipy.misc.imsave('image.jpg', image_array[math.floor(nx/2), :, :])
# Display the image
sct.printv('\nDisplay image and get cropping region...', verbose)
fig = plt.figure()
# fig = plt.gcf()
# ax = plt.gca()
ax = fig.add_subplot(111)
img = mpimg.imread("image.jpg")
implot = ax.imshow(img.T)
implot.set_cmap('gray')
plt.gca().invert_yaxis()
# mouse callback
ax.set_title('Left click on the top and bottom of your cropping field.\n Right click to remove last point.\n Close window when your done.')
line, = ax.plot([], [], 'ro') # empty line
cropping_coordinates = LineBuilder(line)
plt.show()
# disconnect callback
# fig.canvas.mpl_disconnect(line)
# check if user clicked two times
if len(cropping_coordinates.xs) != 2:
sct.printv('\nERROR: You have to select two points. Exit program.\n', 1, 'error')
sys.exit(2)
#.........这里部分代码省略.........
示例13: main
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import data [as 别名]
def main():
# get default parameters
step1 = Paramreg(step='1', type='seg', algo='slicereg', metric='MeanSquares', iter='10')
step2 = Paramreg(step='2', type='im', algo='syn', metric='MI', iter='3')
# step1 = Paramreg()
paramreg = ParamregMultiStep([step1, step2])
# step1 = Paramreg_step(step='1', type='seg', algo='bsplinesyn', metric='MeanSquares', iter='10', shrink='1', smooth='0', gradStep='0.5')
# step2 = Paramreg_step(step='2', type='im', algo='syn', metric='MI', iter='10', shrink='1', smooth='0', gradStep='0.5')
# paramreg = ParamregMultiStep([step1, step2])
# Initialize the parser
parser = Parser(__file__)
parser.usage.set_description('Register anatomical image to the template.')
parser.add_option(name="-i",
type_value="file",
description="Anatomical image.",
mandatory=True,
example="anat.nii.gz")
parser.add_option(name="-s",
type_value="file",
description="Spinal cord segmentation.",
mandatory=True,
example="anat_seg.nii.gz")
parser.add_option(name="-l",
type_value="file",
description="Labels. See: http://sourceforge.net/p/spinalcordtoolbox/wiki/create_labels/",
mandatory=True,
default_value='',
example="anat_labels.nii.gz")
parser.add_option(name="-t",
type_value="folder",
description="Path to MNI-Poly-AMU template.",
mandatory=False,
default_value=param.path_template)
parser.add_option(name="-p",
type_value=[[':'], 'str'],
description="""Parameters for registration (see sct_register_multimodal). Default:\n--\nstep=1\ntype="""+paramreg.steps['1'].type+"""\nalgo="""+paramreg.steps['1'].algo+"""\nmetric="""+paramreg.steps['1'].metric+"""\npoly="""+paramreg.steps['1'].poly+"""\n--\nstep=2\ntype="""+paramreg.steps['2'].type+"""\nalgo="""+paramreg.steps['2'].algo+"""\nmetric="""+paramreg.steps['2'].metric+"""\niter="""+paramreg.steps['2'].iter+"""\nshrink="""+paramreg.steps['2'].shrink+"""\nsmooth="""+paramreg.steps['2'].smooth+"""\ngradStep="""+paramreg.steps['2'].gradStep+"""\n--""",
mandatory=False,
example="step=2,type=seg,algo=bsplinesyn,metric=MeanSquares,iter=5,shrink=2:step=3,type=im,algo=syn,metric=MI,iter=5,shrink=1,gradStep=0.3")
parser.add_option(name="-r",
type_value="multiple_choice",
description="""Remove temporary files.""",
mandatory=False,
default_value='1',
example=['0', '1'])
parser.add_option(name="-v",
type_value="multiple_choice",
description="""Verbose. 0: nothing. 1: basic. 2: extended.""",
mandatory=False,
default_value=param.verbose,
example=['0', '1', '2'])
if param.debug:
print '\n*** WARNING: DEBUG MODE ON ***\n'
fname_data = '/Users/julien/data/temp/sct_example_data/t2/t2.nii.gz'
fname_landmarks = '/Users/julien/data/temp/sct_example_data/t2/labels.nii.gz'
fname_seg = '/Users/julien/data/temp/sct_example_data/t2/t2_seg.nii.gz'
path_template = param.path_template
remove_temp_files = 0
verbose = 2
# speed = 'superfast'
#param_reg = '2,BSplineSyN,0.6,MeanSquares'
else:
arguments = parser.parse(sys.argv[1:])
# get arguments
fname_data = arguments['-i']
fname_seg = arguments['-s']
fname_landmarks = arguments['-l']
path_template = arguments['-t']
remove_temp_files = int(arguments['-r'])
verbose = int(arguments['-v'])
if '-p' in arguments:
paramreg_user = arguments['-p']
# update registration parameters
for paramStep in paramreg_user:
paramreg.addStep(paramStep)
# initialize other parameters
file_template = param.file_template
file_template_label = param.file_template_label
file_template_seg = param.file_template_seg
output_type = param.output_type
zsubsample = param.zsubsample
# smoothing_sigma = param.smoothing_sigma
# start timer
start_time = time.time()
# get absolute path - TO DO: remove! NEVER USE ABSOLUTE PATH...
path_template = os.path.abspath(path_template)
# get fname of the template + template objects
fname_template = sct.slash_at_the_end(path_template, 1)+file_template
fname_template_label = sct.slash_at_the_end(path_template, 1)+file_template_label
fname_template_seg = sct.slash_at_the_end(path_template, 1)+file_template_seg
# check file existence
sct.printv('\nCheck template files...')
#.........这里部分代码省略.........
示例14: get_centerline_from_point
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import data [as 别名]
def get_centerline_from_point(input_image, point_file, gap=4, gaussian_kernel=4, remove_tmp_files=1):
# Initialization
fname_anat = input_image
fname_point = point_file
slice_gap = gap
remove_tmp_files = remove_tmp_files
gaussian_kernel = gaussian_kernel
start_time = time()
verbose = 1
# get path of the toolbox
status, path_sct = commands.getstatusoutput("echo $SCT_DIR")
path_sct = sct.slash_at_the_end(path_sct, 1)
# Parameters for debug mode
if param.debug == 1:
sct.printv("\n*** WARNING: DEBUG MODE ON ***\n\t\t\tCurrent working directory: " + os.getcwd(), "warning")
status, path_sct_testing_data = commands.getstatusoutput("echo $SCT_TESTING_DATA_DIR")
fname_anat = path_sct_testing_data + "/t2/t2.nii.gz"
fname_point = path_sct_testing_data + "/t2/t2_centerline_init.nii.gz"
slice_gap = 5
# check existence of input files
sct.check_file_exist(fname_anat)
sct.check_file_exist(fname_point)
# extract path/file/extension
path_anat, file_anat, ext_anat = sct.extract_fname(fname_anat)
path_point, file_point, ext_point = sct.extract_fname(fname_point)
# extract path of schedule file
# TODO: include schedule file in sct
# TODO: check existence of schedule file
file_schedule = path_sct + param.schedule_file
# Get input image orientation
input_image_orientation = get_orientation_3d(fname_anat, filename=True)
# Display arguments
print "\nCheck input arguments..."
print " Anatomical image: " + fname_anat
print " Orientation: " + input_image_orientation
print " Point in spinal cord: " + fname_point
print " Slice gap: " + str(slice_gap)
print " Gaussian kernel: " + str(gaussian_kernel)
print " Degree of polynomial: " + str(param.deg_poly)
# create temporary folder
print ("\nCreate temporary folder...")
path_tmp = "tmp." + strftime("%y%m%d%H%M%S")
sct.create_folder(path_tmp)
print "\nCopy input data..."
sct.run("cp " + fname_anat + " " + path_tmp + "/tmp.anat" + ext_anat)
sct.run("cp " + fname_point + " " + path_tmp + "/tmp.point" + ext_point)
# go to temporary folder
os.chdir(path_tmp)
# convert to nii
im_anat = convert("tmp.anat" + ext_anat, "tmp.anat.nii")
im_point = convert("tmp.point" + ext_point, "tmp.point.nii")
# Reorient input anatomical volume into RL PA IS orientation
print "\nReorient input volume to RL PA IS orientation..."
set_orientation(im_anat, "RPI")
im_anat.setFileName("tmp.anat_orient.nii")
# Reorient binary point into RL PA IS orientation
print "\nReorient binary point into RL PA IS orientation..."
# sct.run(sct.fsloutput + 'fslswapdim tmp.point RL PA IS tmp.point_orient')
set_orientation(im_point, "RPI")
im_point.setFileName("tmp.point_orient.nii")
# Get image dimensions
print "\nGet image dimensions..."
nx, ny, nz, nt, px, py, pz, pt = Image("tmp.anat_orient.nii").dim
print ".. matrix size: " + str(nx) + " x " + str(ny) + " x " + str(nz)
print ".. voxel size: " + str(px) + "mm x " + str(py) + "mm x " + str(pz) + "mm"
# Split input volume
print "\nSplit input volume..."
im_anat_split_list = split_data(im_anat, 2)
file_anat_split = []
for im in im_anat_split_list:
file_anat_split.append(im.absolutepath)
im.save()
im_point_split_list = split_data(im_point, 2)
file_point_split = []
for im in im_point_split_list:
file_point_split.append(im.absolutepath)
im.save()
# Extract coordinates of input point
data_point = Image("tmp.point_orient.nii").data
x_init, y_init, z_init = unravel_index(data_point.argmax(), data_point.shape)
sct.printv("Coordinates of input point: (" + str(x_init) + ", " + str(y_init) + ", " + str(z_init) + ")", verbose)
# Create 2D gaussian mask
sct.printv("\nCreate gaussian mask from point...", verbose)
#.........这里部分代码省略.........
示例15: main
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import data [as 别名]
def main(args=None):
# Initialization
# fname_anat = ''
# fname_centerline = ''
sigma = 3 # default value of the standard deviation for the Gaussian smoothing (in terms of number of voxels)
# remove_temp_files = param.remove_temp_files
# verbose = param.verbose
start_time = time.time()
parser = get_parser()
arguments = parser.parse(sys.argv[1:])
fname_anat = arguments['-i']
fname_centerline = arguments['-s']
if '-smooth' in arguments:
sigma = arguments['-smooth']
if '-r' in arguments:
remove_temp_files = int(arguments['-r'])
if '-v' in arguments:
verbose = int(arguments['-v'])
# Display arguments
print '\nCheck input arguments...'
print ' Volume to smooth .................. ' + fname_anat
print ' Centerline ........................ ' + fname_centerline
print ' Sigma (mm) ........................ '+str(sigma)
print ' Verbose ........................... '+str(verbose)
# Check that input is 3D:
from msct_image import Image
nx, ny, nz, nt, px, py, pz, pt = Image(fname_anat).dim
dim = 4 # by default, will be adjusted later
if nt == 1:
dim = 3
if nz == 1:
dim = 2
if dim == 4:
sct.printv('WARNING: the input image is 4D, please split your image to 3D before smoothing spinalcord using :\n'
'sct_image -i '+fname_anat+' -split t -o '+fname_anat, verbose, 'warning')
sct.printv('4D images not supported, aborting ...', verbose, 'error')
# Extract path/file/extension
path_anat, file_anat, ext_anat = sct.extract_fname(fname_anat)
path_centerline, file_centerline, ext_centerline = sct.extract_fname(fname_centerline)
# create temporary folder
sct.printv('\nCreate temporary folder...', verbose)
path_tmp = sct.slash_at_the_end('tmp.'+time.strftime("%y%m%d%H%M%S"), 1)
sct.run('mkdir '+path_tmp, verbose)
# Copying input data to tmp folder
sct.printv('\nCopying input data to tmp folder and convert to nii...', verbose)
sct.run('cp '+fname_anat+' '+path_tmp+'anat'+ext_anat, verbose)
sct.run('cp '+fname_centerline+' '+path_tmp+'centerline'+ext_centerline, verbose)
# go to tmp folder
os.chdir(path_tmp)
# convert to nii format
convert('anat'+ext_anat, 'anat.nii')
convert('centerline'+ext_centerline, 'centerline.nii')
# Change orientation of the input image into RPI
print '\nOrient input volume to RPI orientation...'
fname_anat_rpi = set_orientation('anat.nii', 'RPI', filename=True)
move(fname_anat_rpi, 'anat_rpi.nii')
# Change orientation of the input image into RPI
print '\nOrient centerline to RPI orientation...'
fname_centerline_rpi = set_orientation('centerline.nii', 'RPI', filename=True)
move(fname_centerline_rpi, 'centerline_rpi.nii')
# Straighten the spinal cord
# straighten segmentation
sct.printv('\nStraighten the spinal cord using centerline/segmentation...', verbose)
# check if warp_curve2straight and warp_straight2curve already exist (i.e. no need to do it another time)
if os.path.isfile('../warp_curve2straight.nii.gz') and os.path.isfile('../warp_straight2curve.nii.gz') and os.path.isfile('../straight_ref.nii.gz'):
# if they exist, copy them into current folder
sct.printv('WARNING: Straightening was already run previously. Copying warping fields...', verbose, 'warning')
shutil.copy('../warp_curve2straight.nii.gz', 'warp_curve2straight.nii.gz')
shutil.copy('../warp_straight2curve.nii.gz', 'warp_straight2curve.nii.gz')
shutil.copy('../straight_ref.nii.gz', 'straight_ref.nii.gz')
# apply straightening
sct.run('sct_apply_transfo -i anat_rpi.nii -w warp_curve2straight.nii.gz -d straight_ref.nii.gz -o anat_rpi_straight.nii -x spline', verbose)
else:
sct.run('sct_straighten_spinalcord -i anat_rpi.nii -s centerline_rpi.nii -qc 0 -x spline', verbose)
# Smooth the straightened image along z
print '\nSmooth the straightened image along z...'
sct.run('sct_maths -i anat_rpi_straight.nii -smooth 0,0,'+str(sigma)+' -o anat_rpi_straight_smooth.nii', verbose)
# Apply the reversed warping field to get back the curved spinal cord
print '\nApply the reversed warping field to get back the curved spinal cord...'
sct.run('sct_apply_transfo -i anat_rpi_straight_smooth.nii -o anat_rpi_straight_smooth_curved.nii -d anat.nii -w warp_straight2curve.nii.gz -x spline', verbose)
# replace zeroed voxels by original image (issue #937)
sct.printv('\nReplace zeroed voxels by original image...', verbose)
nii_smooth = Image('anat_rpi_straight_smooth_curved.nii')
data_smooth = nii_smooth.data
data_input = Image('anat.nii').data
#.........这里部分代码省略.........