def __save_nibabel(arr, hdr, filename): """ Image saver using the third-party module nibabel. @param arr the image data @param hdr the image header with met-information @param filename the target location """ import nibabel from ..utilities import nibabelu logger = Logger.getInstance() logger.debug('Saving image as {} with NiBabel...'.format(filename)) # convert type bool to int8 if scipy.bool_ == arr.dtype: arr = arr.astype(scipy.uint8) # if original image object was provided with hdr, try to use it for creating the image object if hdr and __is_header_nibabel(hdr): __update_header_from_array_nibabel(hdr, arr) image = nibabelu.image_like(arr, hdr) # if not, create new image object and copy meta data as far as possible else: image = nibabelu.image_new(arr, filename) if hdr: copy_meta_data(image, hdr) # save image nibabel.save(image, filename)
def __save_itk(arr, hdr, filename): """ Image saver using the third-party module itk. @param arr the image data @param hdr the image header with met-information @param filename the target location """ import itk from medpy.itkvtk.utilities import itku logger = Logger.getInstance() logger.debug('Saving image as {} with Itk...'.format(filename)) # determine image type from array image_type = itku.getImageTypeFromArray(arr) # convert array to itk image try: img = itku.getImageFromArray(arr) except KeyError: raise DependencyError('The itk python PyBuffer transition object was compiled without support for image of type {}.'.format(image_type)) # if original image object was provided with hdr, try to use it for creating the image object if __is_header_itk(hdr): # save original image shape / largest possible region shape = [] for i in range(img.GetLargestPossibleRegion().GetImageDimension()): shape.append(img.GetLargestPossibleRegion().GetSize().GetElement(i)) # copy meta data try: img.CopyInformation(hdr.GetPointer()) # reset largest possible region / shape to original value for i in range(len(shape)): img.GetLargestPossibleRegion().GetSize().SetElement(i, shape[i]) except RuntimeError as e: # raised when the meta data information could not be copied (e.g. when the two images ndims differ) logger.debug('The meta-information could not be copied form the old header. CopyInformation signaled: {}.'.format(e)) pass elif hdr: # otherwise copy meta-data information as far as possible copy_meta_data(img, hdr) # save the image writer = itk.ImageFileWriter[image_type].New() writer.SetFileName(filename) writer.SetInput(img.GetPointer()) writer.Update()