Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
@param picklefile the testbed pickle file name
@param original the original image file name
@param label the label image file name
@return a tuple containing:
original: the original image data as ndarray
label: the label image data as ndarray
bounding_boxes: the bounding boxes around the label image regions (Note that the the bounding box of a region with id rid is accessed using bounding_boxes[rid - 1])
model_fg_ids: the region ids of all regions to create the foreground model from
model_bg_ids: the region ids of all regions to create the background model from
eval_ids: the regions to evaluate the regions term on, represented by their ids
truth_fg: subset of regions from the eval_ids that are foreground according to the ground-truth
truth_bg: subset of regions from the eval_ids that are background according to the ground-truth
"""
# load and preprocess images
original_image = load(original)
label_image = load(label)
original_image_d = scipy.squeeze(original_image.get_data())
label_image_d = scipy.squeeze(label_image.get_data())
# relabel the label image to start from 1
label_image_d = medpy.filter.relabel(label_image_d, 1)
# extracting bounding boxes
bounding_boxes = find_objects(label_image_d)
# load testbed
with open(picklefile, 'r') as f:
model_fg_ids = cPickle.load(f)
cPickle.load(f) # model_bg_ids
eval_ids = cPickle.load(f)
truth_fg = cPickle.load(f)
def __load_images(label_image_n, mask_image_n, boundary_image_n, fg_image_n = False, bg_image_n = False):
"""
Load and return all image data in preprocessed ndarrays.
The label image will be relabeled to start from 1.
@return label, ground-truth-mask, boundary-result-mask[, fg-markers, bg-markers]
"""
# load images
label_image = load(label_image_n)
mask_image = load(mask_image_n)
boundary_image = load(boundary_image_n)
if fg_image_n: fg_image = load(fg_image_n)
if bg_image_n: bg_image = load(bg_image_n)
# extract image data
label_image_d = scipy.squeeze(label_image.get_data())
mask_image_d = scipy.squeeze(mask_image.get_data()).astype(scipy.bool_)
boundary_image_d = scipy.squeeze(boundary_image.get_data()).astype(scipy.bool_)
if fg_image_n: fg_image_d = scipy.squeeze(fg_image.get_data()).astype(scipy.bool_)
if bg_image_n: bg_image_d = scipy.squeeze(bg_image.get_data()).astype(scipy.bool_)
# check if images are of same dimensionality
if label_image_d.shape != mask_image_d.shape: raise argparse.ArgumentError('The mask image {} must be of the same dimensionality as the label image {}.'.format(mask_image_d.shape, label_image_d.shape))
if label_image_d.shape != boundary_image_d.shape: raise argparse.ArgumentError('The boundary term image {} must be of the same dimensionality as the label image {}.'.format(boundary_image_d.shape, label_image_d.shape))
if fg_image_n:
if label_image_d.shape != fg_image_d.shape: raise argparse.ArgumentError('The foreground markers image {} must be of the same dimensionality as the label image {}.'.format(fg_image_d.shape, label_image_d.shape))
if bg_image_n:
if label_image_d.shape != bg_image_d.shape: raise argparse.ArgumentError('The background markers image {} must be of the same dimensionality as the label image {}.'.format(bg_image_d.shape, label_image_d.shape))
if os.path.exists(file_csv_name):
logger.warning('The output file {} already exists. Skipping.'.format(file_csv_name))
sys.exit(0)
# open output file
with open(file_csv_name, 'w') as f:
# write header into file
f.write('image;min_x;min_y;min_z;max_x;max_y;max_z\n')
# iterate over input images
for image in args.images:
# get and prepare image data
logger.info('Processing image {}...'.format(image))
image_data = numpy.squeeze(load(image).get_data())
# count number of labels and flag a warning if they reach the ushort border
mask = image_data.nonzero()
# count number of labels and write into file
f.write('{};{};{};{};{};{};{}\n'.format(image.split('/')[-1],
mask[0].min(),
mask[1].min(),
mask[2].min(),
mask[0].max(),
mask[1].max(),
mask[2].max()))
f.flush()
logger.info('Successfully terminated.')
def main():
args = getArguments(getParser())
# test if output image exists
#if not args.force:
# if os.path.exists(args.output):
# print 'The output image {} already exists. Breaking.'.format(args.output)
# sys.exit(-1)
for input in args.input:
# load image
#print 'Loading image {}...'.format(args.input)
input_image = load(input)
input_data = scipy.squeeze(input_image.get_data())
# perform operation
# point out files where image is smaller than X
mask_size = len(input_data.nonzero()[0])
if mask_size < 100:
print '{} has only {} voxels!'.format(input, mask_size)
# save resulting 3D volume
#print 'Saving image as {}...'.format(args.output)
#output_image = image_like(output_data, input_image)
#save(output_image, args.output)
print "Successfully terminated."
image_bg_name += args.mask.split('/')[-1][-4:]
# check if output image exists
if not args.force:
if os.path.exists(image_fg_name):
logger.warning('The output image {} already exists. Breaking.'.format(image_fg_name))
exit(1)
elif os.path.exists(image_bg_name):
logger.warning('The output image {} already exists. Breaking.'.format(image_bg_name))
exit(1)
# load mask
logger.info('Loading mask {}...'.format(args.mask))
try:
mask_image = load(args.mask)
mask_image_data = numpy.squeeze(mask_image.get_data()).astype(scipy.bool_)
except ImageFileError as e:
logger.critical('The mask image does not exist or its file type is unknown.')
raise ArgumentError('The mask image does not exist or its file type is unknown.', e)
# erode mask stepwise
logger.info('Step-wise reducing mask to find center...')
mask_remains = mask_image_data.copy()
while (True):
mask_remains_next = ndimage.binary_erosion(mask_remains, iterations=2)
if 0 == len(mask_remains_next.nonzero()[0]):
break
mask_remains = mask_remains_next
# extract one of the remaining voxels
voxels = mask_remains.nonzero()
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
logger.info('Loading source image {}...'.format(args.input))
try:
input_data = scipy.squeeze(load(args.input).get_data()).astype(scipy.bool_)
except ImageFileError as e:
logger.critical('The region image does not exist or its file type is unknown.')
raise ArgumentError('The region image does not exist or its file type is unknown.', e)
# iterate over designated dimension and create for each such extracted slice a text file
logger.info('Processing per-slice and writing to files...')
idx = [slice(None)] * input_data.ndim
for slice_idx in range(input_data.shape[args.dimension]):
idx[args.dimension] = slice(slice_idx, slice_idx + 1)
# 2009: IM-0001-0027-icontour-manual
file_name = '{}/IM-0001-{:04d}-{}contour-auto.txt'.format(args.target, slice_idx + args.offset, args.ctype)
# 2012: P01-0080-icontour-manual.txt
file_name = '{}/P{}-{:04d}-{}contour-auto.txt'.format(args.target, args.id, slice_idx + args.offset, args.ctype)
# check if output file already exists
if not args.force:
def main():
# prepare logger
logger = Logger.getInstance()
logger.setLevel(logging.DEBUG)
# all rings are at slice z = 98
ring_closed = scipy.squeeze(load('ring_closed.nii').get_data()).astype(scipy.bool_)[:,:,98]
ring_closed_w1hole = scipy.squeeze(load('ring_closed_w1hole.nii').get_data()).astype(scipy.bool_)[:,:,98]
ring_closed_wholes = scipy.squeeze(load('ring_closed_wholes.nii').get_data()).astype(scipy.bool_)[:,:,98]
ring_open = scipy.squeeze(load('ring_open.nii').get_data()).astype(scipy.bool_)[:,:,98]
ring_open_w1hole = scipy.squeeze(load('ring_open_w1hole.nii').get_data()).astype(scipy.bool_)[:,:,98]
ring_open_wholes = scipy.squeeze(load('ring_open_wholes.nii').get_data()).astype(scipy.bool_)[:,:,98]
ring_difficult = scipy.squeeze(load('ring_difficult.nii').get_data()).astype(scipy.bool_)[:,:,98]
ring_difficult_w1hole = scipy.squeeze(load('ring_difficult_w1hole.nii').get_data()).astype(scipy.bool_)[:,:,98]
# algorithm
print 'ring_closed', alg(ring_closed), alg2(ring_closed)
print 'ring_closed_w1hole', alg(ring_closed_w1hole), alg2(ring_closed_w1hole)
print 'ring_closed_wholes', alg(ring_closed_wholes), alg2(ring_closed_wholes)
print 'ring_open', alg(ring_open), alg2(ring_open)
print 'ring_open_w1hole', alg(ring_open_w1hole), alg2(ring_open_w1hole)
print 'ring_open_wholes', alg(ring_open_wholes), alg2(ring_open_wholes)
print 'ring_difficult', alg(ring_difficult), alg2(ring_difficult)
print 'ring_difficult_w1hole', alg(ring_difficult_w1hole), alg2(ring_difficult_w1hole)
def main():
# prepare logger
logger = Logger.getInstance()
logger.setLevel(logging.DEBUG)
# all rings are at slice z = 98
ring_closed = scipy.squeeze(load('ring_closed.nii').get_data()).astype(scipy.bool_)[:,:,98]
ring_closed_w1hole = scipy.squeeze(load('ring_closed_w1hole.nii').get_data()).astype(scipy.bool_)[:,:,98]
ring_closed_wholes = scipy.squeeze(load('ring_closed_wholes.nii').get_data()).astype(scipy.bool_)[:,:,98]
ring_open = scipy.squeeze(load('ring_open.nii').get_data()).astype(scipy.bool_)[:,:,98]
ring_open_w1hole = scipy.squeeze(load('ring_open_w1hole.nii').get_data()).astype(scipy.bool_)[:,:,98]
ring_open_wholes = scipy.squeeze(load('ring_open_wholes.nii').get_data()).astype(scipy.bool_)[:,:,98]
ring_difficult = scipy.squeeze(load('ring_difficult.nii').get_data()).astype(scipy.bool_)[:,:,98]
ring_difficult_w1hole = scipy.squeeze(load('ring_difficult_w1hole.nii').get_data()).astype(scipy.bool_)[:,:,98]
# algorithm
print 'ring_closed', alg(ring_closed), alg2(ring_closed)
print 'ring_closed_w1hole', alg(ring_closed_w1hole), alg2(ring_closed_w1hole)
print 'ring_closed_wholes', alg(ring_closed_wholes), alg2(ring_closed_wholes)
print 'ring_open', alg(ring_open), alg2(ring_open)
print 'ring_open_w1hole', alg(ring_open_w1hole), alg2(ring_open_w1hole)
print 'ring_open_wholes', alg(ring_open_wholes), alg2(ring_open_wholes)
print 'ring_difficult', alg(ring_difficult), alg2(ring_difficult)
print 'ring_difficult_w1hole', alg(ring_difficult_w1hole), alg2(ring_difficult_w1hole)
if len(args.masks) / 2 <= 8:
bit_format = scipy.uint8
elif len(args.masks) / 2 <= 16:
bit_format = scipy.uint16
elif len(args.masks) / 2 <= 32:
bit_format = scipy.uint32
elif len(args.masks) / 2 <= 64:
bit_format = scipy.uint64
else:
raise ArgumentError('It is not possible to combine more than 64 single masks.')
logger.info('Creating a Radiance® segmentation image in {} bit format...'.format(bit_format))
# loading first mask image as reference and template for saving
logger.info('Loading mask {} ({} segmentation) using NiBabel...'.format(args.masks[0], args.masks[1]))
image_mask = load(args.masks[0])
image_mask_data = scipy.squeeze(image_mask.get_data())
# prepare result image
image_radiance_data = scipy.zeros(image_mask_data.shape, dtype=bit_format)
logger.debug('Result image is of dimensions {} and type {}.'.format(image_radiance_data.shape, image_radiance_data.dtype))
# preparing .msk file
f = open(output_msk_name, 'w')
# adding first mask to result image
image_radiance_data[image_mask_data > 0] = 1
# adding first mask segmentation identifier to the .msk file
f.write('{}\t1\t{}\t{}\t{}\n'.format(args.masks[1], *__COLOURS[0%len(__COLOURS)]))