本文整理汇总了Python中medpy.io.save函数的典型用法代码示例。如果您正苦于以下问题:Python save函数的具体用法?Python save怎么用?Python save使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了save函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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.")
示例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.')
示例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.")
示例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.")
示例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.')
示例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)
示例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'
示例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.")
示例9: main
def main():
i, h = load(sys.argv[1])
thr = float(sys.argv[2])
o = i >= thr
save(o, sys.argv[3], h)
示例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)
示例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.')
示例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.")
示例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)
示例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.')
示例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.')