本文整理汇总了Python中msct_image.Image.changeType方法的典型用法代码示例。如果您正苦于以下问题:Python Image.changeType方法的具体用法?Python Image.changeType怎么用?Python Image.changeType使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类msct_image.Image
的用法示例。
在下文中一共展示了Image.changeType方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plan_ref
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import changeType [as 别名]
def plan_ref(self):
"""
Generate a plane in the reference space for each label present in the input image
"""
image_output = Image(self.image_ref, self.verbose)
image_output.data *= 0
image_input_neg = Image(self.image_input, self.verbose).copy()
image_input_pos = Image(self.image_input, self.verbose).copy()
image_input_neg.data *=0
image_input_pos.data *=0
X, Y, Z = (self.image_input.data< 0).nonzero()
for i in range(len(X)):
image_input_neg.data[X[i], Y[i], Z[i]] = -self.image_input.data[X[i], Y[i], Z[i]] # in order to apply getNonZeroCoordinates
X_pos, Y_pos, Z_pos = (self.image_input.data> 0).nonzero()
for i in range(len(X_pos)):
image_input_pos.data[X_pos[i], Y_pos[i], Z_pos[i]] = self.image_input.data[X_pos[i], Y_pos[i], Z_pos[i]]
coordinates_input_neg = image_input_neg.getNonZeroCoordinates()
coordinates_input_pos = image_input_pos.getNonZeroCoordinates()
image_output.changeType('float32')
for coord in coordinates_input_neg:
image_output.data[:, :, int(coord.z)] = -coord.value #PB: takes the int value of coord.value
for coord in coordinates_input_pos:
image_output.data[:, :, int(coord.z)] = coord.value
return image_output
示例2: continuous_vertebral_levels
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import changeType [as 别名]
def continuous_vertebral_levels(self):
"""
This function transforms the vertebral levels file from the template into a continuous file.
Instead of having integer representing the vertebral level on each slice, a continuous value that represents
the position of the slice in the vertebral level coordinate system.
The image must be RPI
:return:
"""
im_input = Image(self.image_input, self.verbose)
im_output = Image(self.image_input, self.verbose)
im_output.data *= 0
# 1. extract vertebral levels from input image
# a. extract centerline
# b. for each slice, extract corresponding level
nx, ny, nz, nt, px, py, pz, pt = im_input.dim
from sct_straighten_spinalcord import smooth_centerline
x_centerline_fit, y_centerline_fit, z_centerline_fit, x_centerline_deriv, y_centerline_deriv, z_centerline_deriv = smooth_centerline(self.image_input, algo_fitting='nurbs', verbose=0)
value_centerline = np.array([im_input.data[int(x_centerline_fit[it]), int(y_centerline_fit[it]), int(z_centerline_fit[it])] for it in range(len(z_centerline_fit))])
# 2. compute distance for each vertebral level --> Di for i being the vertebral levels
vertebral_levels = {}
for slice_image, level in enumerate(value_centerline):
if level not in vertebral_levels:
vertebral_levels[level] = slice_image
length_levels = {}
for level in vertebral_levels:
indexes_slice = np.where(value_centerline == level)
length_levels[level] = np.sum([math.sqrt(((x_centerline_fit[indexes_slice[0][index_slice + 1]] - x_centerline_fit[indexes_slice[0][index_slice]])*px)**2 +
((y_centerline_fit[indexes_slice[0][index_slice + 1]] - y_centerline_fit[indexes_slice[0][index_slice]])*py)**2 +
((z_centerline_fit[indexes_slice[0][index_slice + 1]] - z_centerline_fit[indexes_slice[0][index_slice]])*pz)**2)
for index_slice in range(len(indexes_slice[0]) - 1)])
# 2. for each slice:
# a. identify corresponding vertebral level --> i
# b. calculate distance of slice from upper vertebral level --> d
# c. compute relative distance in the vertebral level coordinate system --> d/Di
continuous_values = {}
for it, iz in enumerate(z_centerline_fit):
level = value_centerline[it]
indexes_slice = np.where(value_centerline == level)
indexes_slice = indexes_slice[0][indexes_slice[0] >= it]
distance_from_level = np.sum([math.sqrt(((x_centerline_fit[indexes_slice[index_slice + 1]] - x_centerline_fit[indexes_slice[index_slice]]) * px * px) ** 2 +
((y_centerline_fit[indexes_slice[index_slice + 1]] - y_centerline_fit[indexes_slice[index_slice]]) * py * py) ** 2 +
((z_centerline_fit[indexes_slice[index_slice + 1]] - z_centerline_fit[indexes_slice[index_slice]]) * pz * pz) ** 2)
for index_slice in range(len(indexes_slice) - 1)])
continuous_values[iz] = level + 2.0 * distance_from_level / float(length_levels[level])
# 3. saving data
# for each slice, get all non-zero pixels and replace with continuous values
coordinates_input = self.image_input.getNonZeroCoordinates()
im_output.changeType('float32')
# for all points in input, find the value that has to be set up, depending on the vertebral level
for i, coord in enumerate(coordinates_input):
im_output.data[int(coord.x), int(coord.y), int(coord.z)] = continuous_values[coord.z]
return im_output
示例3: convert
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import changeType [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
示例4: Image
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import changeType [as 别名]
#!/usr/bin/env python
# change type of template data
import os
import commands
import sys
from shutil import move
# Get path of the toolbox
status, path_sct = commands.getstatusoutput('echo $SCT_DIR')
# Append path that contains scripts, to be able to load modules
sys.path.append(path_sct + '/scripts')
from msct_image import Image
import sct_utils as sct
path_template = '/Users/julien/data/PAM50/template'
folder_PAM50 = 'PAM50/template/'
os.chdir(path_template)
sct.create_folder(folder_PAM50)
for file_template in ['MNI-Poly-AMU_T1.nii.gz', 'MNI-Poly-AMU_T2.nii.gz', 'MNI-Poly-AMU_T2star.nii.gz']:
im = Image(file_template)
# remove negative values
data = im.data
data[data<0] = 0
im.data = data
im.changeType('uint16')
file_new = file_template.replace('MNI-Poly-AMU', 'PAM50')
im.setFileName(file_new)
im.save()
# move to folder
move(file_new, folder_PAM50+file_new)
示例5: compute_csa
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import changeType [as 别名]
#.........这里部分代码省略.........
csa = csa_smooth
else:
sct.printv('.. No smoothing!', verbose)
# Create output text file
sct.printv('\nWrite text file...', verbose)
file_results = open('csa.txt', 'w')
for i in range(min_z_index, max_z_index+1):
file_results.write(str(int(i)) + ',' + str(csa[i-min_z_index])+'\n')
# Display results
sct.printv('z='+str(i-min_z_index)+': '+str(csa[i-min_z_index])+' mm^2', verbose, 'bold')
file_results.close()
# output volume of csa values
sct.printv('\nCreate volume of CSA values...', verbose)
data_csa = data_seg.astype(np.float32, copy=False)
# loop across slices
for iz in range(min_z_index, max_z_index+1):
# retrieve seg pixels
x_seg, y_seg = (data_csa[:, :, iz] > 0).nonzero()
seg = [[x_seg[i],y_seg[i]] for i in range(0, len(x_seg))]
# loop across pixels in segmentation
for i in seg:
# replace value with csa value
data_csa[i[0], i[1], iz] = csa[iz-min_z_index]
# replace data
im_seg.data = data_csa
# set original orientation
# TODO: FIND ANOTHER WAY!!
# im_seg.change_orientation(orientation) --> DOES NOT WORK!
# set file name -- use .gz because faster to write
im_seg.setFileName('csa_volume_RPI.nii.gz')
im_seg.changeType('float32')
# save volume
im_seg.save()
# get orientation of the input data
im_seg_original = Image('segmentation.nii.gz')
orientation = im_seg_original.orientation
sct.run('sct_image -i csa_volume_RPI.nii.gz -setorient '+orientation+' -o '+file_csa_volume)
# come back to parent folder
os.chdir('..')
# Generate output files
sct.printv('\nGenerate output files...', verbose)
copyfile(path_tmp+'csa.txt', path_data+param.fname_csa)
# sct.generate_output_file(path_tmp+'csa.txt', path_data+param.fname_csa) # extension already included in param.fname_csa
sct.generate_output_file(path_tmp+file_csa_volume, path_data+file_csa_volume) # extension already included in name_output
# average csa across vertebral levels or slices if asked (flag -z or -l)
if slices or vert_levels:
from sct_extract_metric import save_metrics
warning = ''
if vert_levels and not fname_vertebral_labeling:
sct.printv('\nERROR: Vertebral labeling file is missing. See usage.\n', 1, 'error')
elif vert_levels and fname_vertebral_labeling:
# from sct_extract_metric import get_slices_matching_with_vertebral_levels
sct.printv('\tSelected vertebral levels... '+vert_levels)
# convert the vertebral labeling file to RPI orientation
im_vertebral_labeling = set_orientation(Image(fname_vertebral_labeling), 'RPI', fname_out=path_tmp+'vertebral_labeling_RPI.nii')
示例6: extract_centerline
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import changeType [as 别名]
#.........这里部分代码省略.........
nx, ny, nz, nt, px, py, pz, pt = im_seg.dim
sct.printv('.. matrix size: '+str(nx)+' x '+str(ny)+' x '+str(nz), verbose)
sct.printv('.. voxel size: '+str(px)+'mm x '+str(py)+'mm x '+str(pz)+'mm', verbose)
# # Get dimension
# sct.printv('\nGet dimensions...', verbose)
# nx, ny, nz, nt, px, py, pz, pt = im_seg.dim
#
# # Extract orientation of the input segmentation
# orientation = get_orientation(im_seg)
# sct.printv('\nOrientation of segmentation image: ' + orientation, verbose)
#
# sct.printv('\nOpen segmentation volume...', verbose)
# data = im_seg.data
# hdr = im_seg.hdr
# Extract min and max index in Z direction
X, Y, Z = (data>0).nonzero()
min_z_index, max_z_index = min(Z), max(Z)
x_centerline = [0 for i in range(0,max_z_index-min_z_index+1)]
y_centerline = [0 for i in range(0,max_z_index-min_z_index+1)]
z_centerline = [iz for iz in range(min_z_index, max_z_index+1)]
# Extract segmentation points and average per slice
for iz in range(min_z_index, max_z_index+1):
x_seg, y_seg = (data[:,:,iz]>0).nonzero()
x_centerline[iz-min_z_index] = np.mean(x_seg)
y_centerline[iz-min_z_index] = np.mean(y_seg)
for k in range(len(X)):
data[X[k], Y[k], Z[k]] = 0
# extract centerline and smooth it
x_centerline_fit, y_centerline_fit, z_centerline_fit, x_centerline_deriv, y_centerline_deriv, z_centerline_deriv = smooth_centerline('segmentation_RPI.nii.gz', type_window = type_window, window_length = window_length, algo_fitting = algo_fitting, verbose = verbose)
if verbose == 2:
import matplotlib.pyplot as plt
#Creation of a vector x that takes into account the distance between the labels
nz_nonz = len(z_centerline)
x_display = [0 for i in range(x_centerline_fit.shape[0])]
y_display = [0 for i in range(y_centerline_fit.shape[0])]
for i in range(0, nz_nonz, 1):
x_display[int(z_centerline[i]-z_centerline[0])] = x_centerline[i]
y_display[int(z_centerline[i]-z_centerline[0])] = y_centerline[i]
plt.figure(1)
plt.subplot(2,1,1)
plt.plot(z_centerline_fit, x_display, 'ro')
plt.plot(z_centerline_fit, x_centerline_fit)
plt.xlabel("Z")
plt.ylabel("X")
plt.title("x and x_fit coordinates")
plt.subplot(2,1,2)
plt.plot(z_centerline_fit, y_display, 'ro')
plt.plot(z_centerline_fit, y_centerline_fit)
plt.xlabel("Z")
plt.ylabel("Y")
plt.title("y and y_fit coordinates")
plt.show()
# Create an image with the centerline
for iz in range(min_z_index, max_z_index+1):
data[round(x_centerline_fit[iz-min_z_index]), round(y_centerline_fit[iz-min_z_index]), iz] = 1 # if index is out of bounds here for hanning: either the segmentation has holes or labels have been added to the file
# Write the centerline image in RPI orientation
# hdr.set_data_dtype('uint8') # set imagetype to uint8
sct.printv('\nWrite NIFTI volumes...', verbose)
im_seg.data = data
im_seg.setFileName('centerline_RPI.nii.gz')
im_seg.changeType('uint8')
im_seg.save()
sct.printv('\nSet to original orientation...', verbose)
# get orientation of the input data
im_seg_original = Image('segmentation.nii.gz')
orientation = im_seg_original.orientation
sct.run('sct_image -i centerline_RPI.nii.gz -setorient '+orientation+' -o centerline.nii.gz')
# create a txt file with the centerline
name_output_txt = 'centerline.txt'
sct.printv('\nWrite text file...', verbose)
file_results = open(name_output_txt, 'w')
for i in range(min_z_index, max_z_index+1):
file_results.write(str(int(i)) + ' ' + str(x_centerline_fit[i-min_z_index]) + ' ' + str(y_centerline_fit[i-min_z_index]) + '\n')
file_results.close()
# come back to parent folder
os.chdir('..')
# Generate output files
sct.printv('\nGenerate output files...', verbose)
sct.generate_output_file(path_tmp+'centerline.nii.gz', file_data+'_centerline.nii.gz')
sct.generate_output_file(path_tmp+'centerline.txt', file_data+'_centerline.txt')
# Remove temporary files
if remove_temp_files:
sct.printv('\nRemove temporary files...', verbose)
sct.run('rm -rf '+path_tmp, verbose)
return file_data+'_centerline.nii.gz'
示例7: open
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import changeType [as 别名]
# Create output text file
if output_file_name != None :
file_name = output_file_name
else: file_name = 'generated_centerline.txt'
sct.printv('\nWrite text file...')
#file_results = open("../"+file_name, 'w')
file_results = open(file_name, 'w')
for i in range(0, z_centerline_fit.shape[0], 1):
file_results.write(str(int(z_centerline_fit[i])) + ' ' + str(x_centerline_fit[i]) + ' ' + str(y_centerline_fit[i]) + '\n')
file_results.close()
#return file_name
# =======================================================================================================================
# Start program
#=======================================================================================================================
if __name__ == "__main__":
parser = Parser(__file__)
parser.usage.set_description('Class to process centerline extraction from.')
parser.add_option()
arguments = parser.parse(sys.argv[1:])
image = Image(arguments["-i"])
image.changeType('minimize')
示例8: Image
# 需要导入模块: from msct_image import Image [as 别名]
# 或者: from msct_image.Image import changeType [as 别名]
#!/usr/bin/env python
from skimage import transform as tf
from skimage import data
from msct_image import Image
from math import pi
im0 = Image('data_by_slice/slice_0_im.nii.gz')
seg0 = Image('data_by_slice/slice_0_seg.nii.gz')
'''
transfo = tf.SimilarityTransform(scale=1, rotation=pi / 2, translation=(0, 1))
print transfo.params
im0.changeType('uint8')
print im0.data
text = data.text()
im_moved = tf.warp(transfo, text) # im0.data)
print im_moved
Image(param=im_moved, absolutepath='moved_slice_0.nii.gz').save()
'''
text = data.text()
seg0.changeType('uint8')
test = seg0.data
Image(param=test, absolutepath='converted_slice_0_seg.nii.gz').save()