本文整理汇总了Python中medpy.io.save函数的典型用法代码示例。如果您正苦于以下问题:Python save函数的具体用法?Python save怎么用?Python save使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了save函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: main
def main():
# parse cmd arguments
parser = getParser()
parser.parse_args()
args = getArguments(parser)
# prepare logger
logger = Logger.getInstance()
if args.debug:
logger.setLevel(logging.DEBUG)
elif args.verbose:
logger.setLevel(logging.INFO)
# check if output image exists (will also be performed before saving, but as the watershed might be very time intensity, a initial check can save frustration)
if not args.force:
if os.path.exists(args.output):
raise ArgumentError("The output image {} already exists.".format(args.output))
# loading image
data_input, header_input = load(args.input)
# apply the watershed
logger.info("Watershedding with settings: thr={} / level={}...".format(args.threshold, args.level))
data_output = watershed(data_input, get_pixel_spacing(header_input), args.threshold, args.level)
# save file
save(data_output, args.output, header_input, args.force)
logger.info("Successfully terminated.")
开发者ID:tatafarewell,项目名称:medpy,代码行数:29,代码来源:medpy_itk_watershed.py
示例2: main
def main():
# parse cmd arguments
parser = getParser()
parser.parse_args()
args = getArguments(parser)
# prepare logger
logger = Logger.getInstance()
if args.debug: logger.setLevel(logging.DEBUG)
elif args.verbose: logger.setLevel(logging.INFO)
# load input image using nibabel
logger.info('Loading image {}...'.format(args.input))
image_labels_data, _ = load(args.image)
# load mask image
logger.info('Loading mask {}...'.format(args.mask))
image_mask_data, image_mask_data_header = load(args.mask)
# check if output image exists
if not args.force:
if os.path.exists(args.output):
logger.warning('The output image {} already exists. Skipping this image.'.format(args.output))
# create a mask from the label image
logger.info('Reducing the label image...')
image_reduced_data = fit_labels_to_mask(image_labels_data, image_mask_data)
# save resulting mask
logger.info('Saving resulting mask as {} in the same format as input mask, only with data-type int8...'.format(args.output))
image_reduced_data = image_reduced_data.astype(numpy.bool, copy=False) # bool sadly not recognized
save(image_reduced_data, args.output, image_mask_data_header, args.force)
logger.info('Successfully terminated.')
开发者ID:AlexanderRuesch,项目名称:medpy,代码行数:34,代码来源:medpy_reduce.py
示例3: main
def main():
args = getArguments(getParser())
# prepare logger
logger = Logger.getInstance()
if args.debug:
logger.setLevel(logging.DEBUG)
elif args.verbose:
logger.setLevel(logging.INFO)
# check if output image exists
if not args.force:
if os.path.exists(args.output):
logger.warning("The output image {} already exists. Exiting.".format(args.output))
exit(-1)
# load input image
input_data, input_header = load(args.input)
logger.debug("Old number of regions={}.".format(len(scipy.unique(input_data))))
# cut and relabel along the required dimension
logger.info("Cutting and relabeling...")
dimensions = range(input_data.ndim)
del dimensions[args.dimension]
__split_along(input_data, dimensions)
logger.debug("New number of regions={}.".format(len(scipy.unique(input_data))))
# save result contour volume
save(input_data, args.output, input_header, args.force)
logger.info("Successfully terminated.")
开发者ID:tatafarewell,项目名称:medpy,代码行数:33,代码来源:discontinue_dimension.py
示例4: main
def main():
args = getArguments(getParser())
# prepare logger
logger = Logger.getInstance()
if args.debug: logger.setLevel(logging.DEBUG)
elif args.verbose: logger.setLevel(logging.INFO)
# load input image
data_input, header_input = load(args.input)
# transform to uin8
data_input = data_input.astype(scipy.uint8)
# reduce to 3D, if larger dimensionality
if data_input.ndim > 3:
for _ in range(data_input.ndim - 3): data_input = data_input[...,0]
# iter over slices (2D) until first with content is detected
for plane in data_input:
if scipy.any(plane):
# set pixel spacing
spacing = list(header.get_pixel_spacing(header_input))
spacing = spacing[1:3]
__update_header_from_array_nibabel(header_input, plane)
header.set_pixel_spacing(header_input, spacing)
# save image
save(plane, args.output, header_input, args.force)
break
logger.info("Successfully terminated.")
开发者ID:AlexanderRuesch,项目名称:medpy,代码行数:31,代码来源:extract_first_basal_slice.py
示例5: sresamplebyexample
def sresamplebyexample(src, dest, referenceimage, binary = False):
r"""
Secure-re-sample an image located at ``src`` by example ``referenceimage`` and
save it under ``dest``.
Parameters
----------
src : string
Source image file.
dest : string
Destination image file.
referenceimage : string
Reference image displaying the target spacing, origin and size.
binary : bool
Set to ``True`` for binary images.
"""
# get target voxel spacing
refimage, refhdr = load(referenceimage)
spacing = header.get_pixel_spacing(refhdr)
with tmpdir() as t:
# create a temporary copy of the reference image with the source image data-type (imiImageResample requires both images to be of the same dtype)
srcimage, _ = load(src)
save(refimage.astype(srcimage.dtype), os.path.join(t, 'ref.nii.gz'), refhdr)
# prepare and run registration command
cmd = ['imiImageResample', '-I', src, '-O', dest, '-R', os.path.join(t, 'ref.nii.gz'), '-s'] + map(str, spacing)
if binary:
cmd += ['-b']
rtcode, stdout, stderr = call(cmd)
# check if successful
if not os.path.isfile(dest):
raise CommandExecutionError(cmd, rtcode, stdout, stderr, 'Binary re-sampling result image not created.')
开发者ID:loli,项目名称:neuroless,代码行数:34,代码来源:unification.py
示例6: main
def main():
_file = sys.argv[1]
dim = int(sys.argv[2])
i, h = load(_file)
i = flip_axis(i, dim).copy()
save(i, _file, h)
开发者ID:loli,项目名称:nspipeline,代码行数:7,代码来源:flip.py
示例7: test02
def test02(img, idx):
# TEST 02: CAN THEY BE LOADED AGAIN WITHOUT A CHANGE OF DATA TYPE OR DATA CONTENT?
for dt in dtypes:
print '\n:::{}:::'.format(dt).upper()
for t in types_int:
print t.upper(), '\t->',
try:
img1 = img.astype(dt)
name2 = tmp_folder + '.'.join(['tmp', t])
save(img1, name2, hdr, True)
try:
img2, _ = load(name2)
if img2.dtype == img1.dtype and img2[idx] == img1[idx]:
print True
elif img2.dtype == img1.dtype:
print 'dtype: {} / value: {} != {}'.format(True, img2[idx], img1[idx])
elif img2[idx] == img1[idx]:
print 'dtype: {} != {} / value: {}'.format(img2.dtype, img1.dtype, True)
else:
print 'dtype: {} != {} / value: {} != {}'.format(img2.dtype, img1.dtype, img2[idx], img1[idx])
except Exception as e:
print 'loading failed, reason: {}'.format(e)
except Exception as e:
print 'saving unsupported'
开发者ID:ShimonaNiharika,项目名称:MedIA,代码行数:26,代码来源:_test.py
示例8: main
def main():
args = getArguments(getParser())
# prepare logger
logger = Logger.getInstance()
if args.debug: logger.setLevel(logging.DEBUG)
elif args.verbose: logger.setLevel(logging.INFO)
# load input images
input_data, input_header = load(args.input)
original_data, _ = load(args.original)
logger.debug('Old shape={}.'.format(input_data.shape))
# compute position
logger.info('Computing positon and pad volume...')
position = __parse_contour_list(args.contours, input_data)
# pad volume
output_data = scipy.zeros(original_data.shape, input_data.dtype)
output_data[position] = input_data
logger.debug('New shape={}.'.format(input_data.shape))
# save result contour volume
save(output_data, args.output, input_header, args.force)
logger.info("Successfully terminated.")
开发者ID:AlexanderRuesch,项目名称:medpy,代码行数:29,代码来源:pad_cut_by_contourfile.py
示例9: main
def main():
i, h = load(sys.argv[1])
thr = float(sys.argv[2])
o = i >= thr
save(o, sys.argv[3], h)
开发者ID:loli,项目名称:neuropipeline,代码行数:7,代码来源:threshold.py
示例10: main
def main():
i, h = load(sys.argv[1])
thr = float(sys.argv[2])
i = i.copy()
save(i >= thr, sys.argv[1], h)
开发者ID:loli,项目名称:atlasoverlap,代码行数:7,代码来源:threshold.py
示例11: main
def main():
# parse cmd arguments
parser = getParser()
parser.parse_args()
args = getArguments(parser)
# prepare logger
logger = Logger.getInstance()
if args.debug: logger.setLevel(logging.DEBUG)
elif args.verbose: logger.setLevel(logging.INFO)
# check if output image already exists
if not args.force:
if os.path.exists(args.output):
logger.warning('The output image {} already exists. Exiting.'.format(args.output))
exit(-1)
# load input image
image_smoothed_data, image_header = load(args.input)
# apply additional hole closing step
logger.info('Closing holes...')
def fun_holes(arr):
return scipy.ndimage.morphology.binary_fill_holes(arr)
xd_iterator(image_smoothed_data, (1, 2), fun_holes)
# perform opening resp. closing
# in 3D case: size 1 = 6-connectedness, 2 = 12-connectedness, 3 = 18-connectedness, etc.
if 'erosion' == args.type:
logger.info('Applying erosion...')
def fun(arr):
if 0 == args.iterations: return arr
footprint = scipy.ndimage.morphology.generate_binary_structure(arr.ndim, args.size)
return scipy.ndimage.morphology.binary_erosion(arr, footprint, iterations=args.iterations)
elif 'dilation' == args.type:
logger.info('Applying dilation...')
def fun(arr):
if 0 == args.iterations: return arr
footprint = scipy.ndimage.morphology.generate_binary_structure(arr.ndim, args.size)
return scipy.ndimage.morphology.binary_dilation(arr, footprint, iterations=args.iterations)
elif 'opening' == args.type:
logger.info('Applying opening...')
def fun(arr):
if 0 == args.iterations: return arr
footprint = scipy.ndimage.morphology.generate_binary_structure(arr.ndim, args.size)
return scipy.ndimage.morphology.binary_opening(arr, footprint, iterations=args.iterations)
else: # closing
logger.info('Applying closing...')
def fun(arr):
if 0 == args.iterations: return arr
footprint = scipy.ndimage.morphology.generate_binary_structure(arr.ndim, args.size)
return scipy.ndimage.morphology.binary_closing(arr, footprint, iterations=args.iterations)
# iterate over slices and apply selected operation
xd_iterator(image_smoothed_data, (1, 2), fun)
# save resulting mas
save(image_smoothed_data, args.output, image_header, args.force)
logger.info('Successfully terminated.')
开发者ID:AlexanderRuesch,项目名称:medpy,代码行数:60,代码来源:morphology_sliced.py
示例12: main
def main():
args = getArguments(getParser())
# prepare logger
logger = Logger.getInstance()
if args.debug: logger.setLevel(logging.DEBUG)
elif args.verbose: logger.setLevel(logging.INFO)
# load input image
input_data, input_header = load(args.input)
logger.debug('Old shape={}.'.format(input_data.shape))
# compute cut
logger.info('Computing cut and cropping volume...')
cut = __parse_contour_list(args.contours, input_data)
# crop volume
input_data = input_data[cut]
logger.debug('New shape={}.'.format(input_data.shape))
# save result contour volume
save(input_data, args.output, input_header, args.force)
logger.info("Successfully terminated.")
开发者ID:AlexanderRuesch,项目名称:medpy,代码行数:25,代码来源:extract_subvolume_by_contourfile.py
示例13: main
def main():
i1, h1 = load(sys.argv[1])
i2, h2 = load(sys.argv[2])
# shift image to align origins
origin_h1 = numpy.sign(h1.get_qform()[0:3,0:3]).dot(header.get_offset(h1))
origin_h2 = numpy.sign(h2.get_qform()[0:3,0:3]).dot(header.get_offset(h2))
origin_difference_pixel = (origin_h1 - origin_h2) / numpy.asarray(header.get_pixel_spacing(h1))
# negative values: shift image 1 by this upon inserting (which is the smae as cutting the output image)
# positive values: cut image 1 by this at inserting and also cut right side by length of output image plus this value
o = numpy.zeros(i2.shape, i2.dtype)
o_slicer = []
i_slicer = []
for j, p in enumerate(origin_difference_pixel):
if p >= 0:
i_slicer.append(slice(0, min(i1.shape[j], o.shape[j] - abs(p))))
o_slicer.append(slice(abs(p), min(i1.shape[j] + abs(p), o.shape[j])))
else:
i_slicer.append(slice(abs(p), min(i1.shape[j], o.shape[j] + abs(p))))
o_slicer.append(slice(0, min(i1.shape[j] - abs(p), o.shape[j])))
o[o_slicer] = i1[i_slicer]
header.set_offset(h1, header.get_offset(h2))
save(o, sys.argv[3], h1)
开发者ID:loli,项目名称:neuropipeline,代码行数:25,代码来源:align.py
示例14: main
def main():
# parse cmd arguments
parser = getParser()
parser.parse_args()
args = getArguments(parser)
# prepare logger
logger = Logger.getInstance()
if args.debug: logger.setLevel(logging.DEBUG)
elif args.verbose: logger.setLevel(logging.INFO)
# laod input image
data_input, header_input = load(args.input)
# # check if output image exists
# if not args.force:
# if os.path.exists(image_gradient_name):
# logger.warning('The output image {} already exists. Skipping this step.'.format(image_gradient_name))
# continue
# prepare result image
data_output = scipy.zeros(data_input.shape, dtype=scipy.float32)
# apply the gradient magnitude filter
logger.info('Computing the gradient magnitude with Prewitt operator...')
generic_gradient_magnitude(data_input, prewitt, output=data_output) # alternative to prewitt is sobel
# save resulting mask
save(data_output, args.output, header_input, args.force)
logger.info('Successfully terminated.')
开发者ID:AlexanderRuesch,项目名称:medpy,代码行数:31,代码来源:medpy_gradient.py
示例15: main
def main():
# parse cmd arguments
parser = getParser()
parser.parse_args()
args = getArguments(parser)
# prepare logger
logger = Logger.getInstance()
if args.debug: logger.setLevel(logging.DEBUG)
elif args.verbose: logger.setLevel(logging.INFO)
# check if output image exists (will also be performed before saving, but as the gradient might be time intensity, a initial check can save frustration)
if not args.force:
if os.path.exists(args.output):
raise ArgumentError('The output image {} already exists.'.format(args.output))
# loading image
data_input, header_input = load(args.input)
logger.debug('Input array: dtype={}, shape={}'.format(data_input.dtype, data_input.shape))
# execute the gradient map filter
logger.info('Applying gradient map filter...')
data_output = filter.gradient_magnitude(data_input, header.get_pixel_spacing(header_input))
logger.debug('Resulting array: dtype={}, shape={}'.format(data_output.dtype, data_output.shape))
# save image
save(data_output, args.output, header_input, args.force)
logger.info('Successfully terminated.')
开发者ID:AlexanderRuesch,项目名称:medpy,代码行数:31,代码来源:medpy_itk_gradient.py
示例16: main
def main():
# parse cmd arguments
parser = getParser()
parser.parse_args()
args = getArguments(parser)
# prepare logger
logger = Logger.getInstance()
if args.debug: logger.setLevel(logging.DEBUG)
elif args.verbose: logger.setLevel(logging.INFO)
# check if output image exists (will also be performed before saving, but as the smoothing might be very time intensity, a initial check can save frustration)
if not args.force:
if os.path.exists(args.output):
raise parser.error('The output image {} already exists.'.format(args.output))
# loading image
data_input, header_input = load(args.input)
# apply the watershed
logger.info('Applying anisotropic diffusion with settings: niter={} / kappa={} / gamma={}...'.format(args.iterations, args.kappa, args.gamma))
data_output = anisotropic_diffusion(data_input, args.iterations, args.kappa, args.gamma, get_pixel_spacing(header_input))
# save file
save(data_output, args.output, header_input, args.force)
logger.info('Successfully terminated.')
开发者ID:loli,项目名称:medpy,代码行数:27,代码来源:medpy_anisotropic_diffusion.py
示例17: main
def main():
args = getArguments(getParser())
# prepare logger
logger = Logger.getInstance()
if args.debug: logger.setLevel(logging.DEBUG)
elif args.verbose: logger.setLevel(logging.INFO)
# load input image
data_input, header_input = load(args.input)
logger.debug('Original shape = {}.'.format(data_input.shape))
# check if supplied dimension parameters is inside the images dimensions
if args.dimension1 >= data_input.ndim or args.dimension1 < 0:
raise ArgumentError('The first swap-dimension {} exceeds the number of input volume dimensions {}.'.format(args.dimension1, data_input.ndim))
elif args.dimension2 >= data_input.ndim or args.dimension2 < 0:
raise ArgumentError('The second swap-dimension {} exceeds the number of input volume dimensions {}.'.format(args.dimension2, data_input.ndim))
# swap axes
data_output = scipy.swapaxes(data_input, args.dimension1, args.dimension2)
# swap pixel spacing and offset
ps = list(header.get_pixel_spacing(header_input))
ps[args.dimension1], ps[args.dimension2] = ps[args.dimension2], ps[args.dimension1]
header.set_pixel_spacing(header_input, ps)
os = list(header.get_offset(header_input))
os[args.dimension1], os[args.dimension2] = os[args.dimension2], os[args.dimension1]
header.set_offset(header_input, os)
logger.debug('Resulting shape = {}.'.format(data_output.shape))
# save resulting volume
save(data_output, args.output, header_input, args.force)
logger.info("Successfully terminated.")
开发者ID:AlexanderRuesch,项目名称:medpy,代码行数:35,代码来源:medpy_swap_dimensions.py
示例18: main
def main():
# catch parameters
forest_file = sys.argv[1]
case_folder = sys.argv[2]
mask_file = sys.argv[3]
segmentation_file = sys.argv[4]
# loading case features
feature_vector = []
for _file in os.listdir(case_folder):
if _file.endswith('.npy') and _file.startswith('feature.'):
with open(os.path.join(case_folder, _file), 'r') as f:
feature_vector.append(numpy.load(f))
feature_vector = join(*feature_vector)
if 1 == feature_vector.ndim:
feature_vector = numpy.expand_dims(feature_vector, -1)
# load and apply the decision forest
with open(forest_file, 'r') as f:
forest = pickle.load(f)
classification_results = forest.predict(feature_vector)
# preparing image
m, h = load(mask_file)
m = m.astype(numpy.bool)
o = numpy.zeros(m.shape, numpy.uint8)
o[m] = numpy.squeeze(classification_results).ravel()
# applying the post-processing morphology
#o = binary_dilation(o, iterations=2)
#o = keep_largest_connected_component(o)
o = binary_fill_holes(o)
# savin the results
save(o, segmentation_file, h, True)
开发者ID:loli,项目名称:neuropipeline,代码行数:35,代码来源:apply_rdf.py
示例19: test03
def test03(img, hdr, idx, delta):
# TEST 03: DOES ANY META-INFORMATION GET LOST DURING FORMAT CONVERSION? AND IF YES; WHICH?
for tr in types_int: # reference type
print ''
oformat = tr
# create, save and load reference image
try:
name_ref = tmp_folder + '.'.join(['tmp_ref', tr])
save(img, name_ref, hdr, True)
img_ref, hdr_ref = load(name_ref)
except Exception as e:
print '\tERROR: Could not generate reference image for type {}: {}'.format(otype, e)
continue
# extract meta-data from reference image
mdata_ref = {'shape': img_ref.shape,
'dtype': img_ref.dtype,
'point': img_ref[idx],
'spacing': header.get_pixel_spacing(hdr_ref),
'offset': header.get_offset(hdr_ref),}
# print meta-data from reference image
# iterate of test images
for tt in types_int: # test type
print '{} => {}'.format(oformat, tt),
# create, save and load test images
try:
#print type(img_ref), type(hdr_ref)
#print type(img_test), type(hdr_test)
name_test = tmp_folder + '.'.join(['tmp_test', tt])
save(img_ref, name_test, hdr_ref, True)
img_test, hdr_test = load(name_test)
except Exception as e:
print '\tERROR: Could not generate test image. {}'.format(e)
continue
# extract meta-data from test image
mdata_test = {'shape': img_test.shape,
'dtype': img_test.dtype,
'spacing': header.get_pixel_spacing(hdr_test),
'offset': header.get_offset(hdr_test),
'point': img_test[idx]}
# compare reference against meta-image
error = False
for k in mdata_ref.keys():
equal = _compare(mdata_ref[k], mdata_test[k], delta)
#print '\n\t{} ({}) : {} = {}'.format(equal, k, mdata_ref[k], mdata_test[k]),
if not equal:
error = True
print '\n\t{} ({}) : {} = {}'.format(equal, k, mdata_ref[k], mdata_test[k]),
if not error:
print '\t{}'.format(True)
else:
print '\n'
开发者ID:ShimonaNiharika,项目名称:MedIA,代码行数:59,代码来源:_test.py
示例20: main
def main():
args = getArguments(getParser())
# prepare logger
logger = Logger.getInstance()
if args.debug: logger.setLevel(logging.DEBUG)
elif args.verbose: logger.setLevel(logging.INFO)
# loading input images
b0img, b0hdr = load(args.b0image)
bximg, bxhdr = load(args.bximage)
# convert to float
b0img = b0img.astype(numpy.float)
bximg = bximg.astype(numpy.float)
# check if image are compatible
if not b0img.shape == bximg.shape:
raise ArgumentError('The input images shapes differ i.e. {} != {}.'.format(b0img.shape, bximg.shape))
if not header.get_pixel_spacing(b0hdr) == header.get_pixel_spacing(bxhdr):
raise ArgumentError('The input images voxel spacing differs i.e. {} != {}.'.format(header.get_pixel_spacing(b0hdr), header.get_pixel_spacing(bxhdr)))
# check if supplied threshold value as well as the b value is above 0
if args.threshold is not None and not args.threshold >= 0:
raise ArgumentError('The supplied threshold value must be greater than 0, otherwise a division through 0 might occur.')
if not args.b > 0:
raise ArgumentError('The supplied b-value must be greater than 0.')
# compute threshold value if not supplied
if args.threshold is None:
b0thr = otsu(b0img, 32) / 4. # divide by 4 to decrease impact
bxthr = otsu(bximg, 32) / 4.
if 0 >= b0thr:
raise ArgumentError('The supplied b0image seems to contain negative values.')
if 0 >= bxthr:
raise ArgumentError('The supplied bximage seems to contain negative values.')
else:
b0thr = bxthr = args.threshold
logger.debug('thresholds={}/{}, b-value={}'.format(b0thr, bxthr, args.b))
# threshold b0 + bx DW image to obtain a mask
# b0 mask avoid division through 0, bx mask avoids a zero in the ln(x) computation
mask = binary_fill_holes(b0img > b0thr) & binary_fill_holes(bximg > bxthr)
# perform a number of binary morphology steps to select the brain only
mask = binary_erosion(mask, iterations=1)
mask = largest_connected_component(mask)
mask = binary_dilation(mask, iterations=1)
logger.debug('excluding {} of {} voxels from the computation and setting them to zero'.format(numpy.count_nonzero(mask), numpy.prod(mask.shape)))
# compute the ADC
adc = numpy.zeros(b0img.shape, b0img.dtype)
adc[mask] = -1. * args.b * numpy.log(bximg[mask] / b0img[mask])
adc[adc < 0] = 0
# saving the resulting image
save(adc, args.output, b0hdr, args.force)
开发者ID:kleinfeld,项目名称:medpy,代码行数:59,代码来源:medpy_apparent_diffusion_coefficient.py
注:本文中的medpy.io.save函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论