예제 #1
0
파일: align.py 프로젝트: loli/neuropipeline
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)
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.")    
def main():
    args = getArguments(getParser())

    # prepare logger
    logger = Logger.getInstance()
    if args.debug: logger.setLevel(logging.DEBUG)
    elif args.verbose: logger.setLevel(logging.INFO)

    # copy the example image or generate empty image, depending on the modus
    if args.example:
        grid_image = scipy.zeros(args.example_image.shape, scipy.bool_)
        grid_header = args.example_header
    else:
        grid_image = scipy.zeros(args.shape, scipy.bool_)
        # !TODO: Find another solution for this
        # Saving and loading image once to generate a valid header
        tmp_dir = tempfile.mkdtemp()
        tmp_image = '{}/{}'.format(tmp_dir, args.output.split('/')[-1])
        save(grid_image, tmp_image)
        _, grid_header = load(tmp_image)
        try:
            os.remove(tmp_image)
            os.rmdir(tmp_dir)
        except Exception:
            pass

    # set the image attributes if supplied
    if args.pixelspacing:
        header.set_pixel_spacing(grid_header, args.pixelspacing)
    if args.offset:
        header.set_offset(grid_header, args.offset)

    # compute the right grid spacing for each dimension
    if args.real:
        grid_spacing = [
            int(round(sp / float(ps))) for sp, ps in zip(
                args.spacing, header.get_pixel_spacing(grid_header))
        ]
    else:
        grid_spacing = args.spacing

    # paint the grid into the empty image volume
    for dim in range(grid_image.ndim):
        if 0 == grid_spacing[dim]:
            continue  # skip dimension of 0 grid spacing supplied
        for offset in range(0, grid_image.shape[dim], grid_spacing[dim]):
            slicer = [slice(None)] * grid_image.ndim
            slicer[dim] = slice(offset, offset + 1)
            grid_image[slicer] = True

    # saving resulting grid volume
    save(grid_image, args.output, grid_header, args.force)
예제 #4
0
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.output1):
            raise parser.error('The output image {} already exists.'.format(
                args.output1))
        if os.path.exists(args.output2):
            raise parser.error('The output image {} already exists.'.format(
                args.output2))

    # loading images
    data_input1, header_input1 = load(args.input1)
    data_input2, header_input2 = load(args.input2)
    logger.debug('Original image sizes are {} and {}.'.format(
        data_input1.shape, data_input2.shape))

    # compute intersection volumes (punch)
    logger.info('Computing the intersection.')
    inters1, inters2, new_offset = intersection(data_input1, header_input1,
                                                data_input2, header_input2)
    logger.debug(
        'Punched images are of sizes {} and {} with new offset {}.'.format(
            inters1.shape, inters2.shape, new_offset))

    # check if any intersection could be found at all
    if 0 == inters1.size:
        logger.warning(
            'No intersection could be found between the images. Please check their meta-data e.g. with medpy_info'
        )

    # update header informations
    header.set_offset(header_input1, new_offset)
    header.set_offset(header_input2, new_offset)

    # save punched images
    save(inters1, args.output1, header_input1, args.force)
    save(inters2, args.output2, header_input2, args.force)

    logger.info('Successfully terminated.')
예제 #5
0
def main():
    args = getArguments(getParser())

    # prepare logger
    logger = Logger.getInstance()
    if args.debug: logger.setLevel(logging.DEBUG)
    elif args.verbose: logger.setLevel(logging.INFO)
    
    # copy the example image or generate empty image, depending on the modus
    if args.example:
        grid_image = scipy.zeros(args.example_image.shape, scipy.bool_)
        grid_header = args.example_header
    else:
        grid_image = scipy.zeros(args.shape, scipy.bool_)
        # !TODO: Find another solution for this
        # Saving and loading image once to generate a valid header
        tmp_dir = tempfile.mkdtemp()
        tmp_image = '{}/{}'.format(tmp_dir, args.output.split('/')[-1])
        save(grid_image, tmp_image)
        _, grid_header = load(tmp_image)
        try:
            os.remove(tmp_image)
            os.rmdir(tmp_dir)
        except Exception:
            pass
        
    # set the image attributes if supplied
    if args.pixelspacing:
        header.set_pixel_spacing(grid_header, args.pixelspacing)
    if args.offset:
        header.set_offset(grid_header, args.offset)
    
    # compute the right grid spacing for each dimension
    if args.real:
        grid_spacing = [int(round(sp / float(ps))) for sp, ps in zip(args.spacing, header.get_pixel_spacing(grid_header))]
    else:
        grid_spacing = args.spacing
        
    # paint the grid into the empty image volume
    for dim in range(grid_image.ndim):
        if 0 == grid_spacing[dim]: continue # skip dimension of 0 grid spacing supplied
        for offset in range(0, grid_image.shape[dim], grid_spacing[dim]):
            slicer = [slice(None)] * grid_image.ndim
            slicer[dim] = slice(offset, offset + 1)
            grid_image[slicer] = True
            
    # saving resulting grid volume
    save(grid_image, args.output, grid_header, args.force)
예제 #6
0
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.output1):
            raise parser.error("The output image {} already exists.".format(args.output1))
        if os.path.exists(args.output2):
            raise parser.error("The output image {} already exists.".format(args.output2))

    # loading images
    data_input1, header_input1 = load(args.input1)
    data_input2, header_input2 = load(args.input2)
    logger.debug("Original image sizes are {} and {}.".format(data_input1.shape, data_input2.shape))

    # compute intersection volumes (punch)
    logger.info("Computing the intersection.")
    inters1, inters2, new_offset = intersection(data_input1, header_input1, data_input2, header_input2)
    logger.debug(
        "Punched images are of sizes {} and {} with new offset {}.".format(inters1.shape, inters2.shape, new_offset)
    )

    # check if any intersection could be found at all
    if 0 == inters1.size:
        logger.warning(
            "No intersection could be found between the images. Please check their meta-data e.g. with medpy_info"
        )

    # update header informations
    header.set_offset(header_input1, new_offset)
    header.set_offset(header_input2, new_offset)

    # save punched images
    save(inters1, args.output1, header_input1, args.force)
    save(inters2, args.output2, header_input2, args.force)

    logger.info("Successfully terminated.")
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.")
    def test_MetadataConsistency(self):
        """
        This test checks the ability of different image formats to consistently save
        meta-data information. Especially if a conversion between formats is required,
        that involves different 3rd party modules, this is not always guaranteed.
        
        The images are saved in one format, loaded and then saved in another format.
        Subsequently the differences in the meta-data is checked.
        
        Currently this test can only check:
        - voxel spacing
        - image offset
        
        Note that some other test are inherently performed by the
        loadsave.TestIOFacilities class:
        - data type
        - shape
        - content
        
        With the verboose switches, a comprehensive list of the results can be obtianed.
        """
        ####
        # VERBOOSE SETTINGS
        # The following are two variables that can be used to print some nicely
        # formatted additional output. When one of them is set to True, this unittest
        # should be run stand-alone.
        ####
        # Print a list of format to format conversion which preserve meta-data
        consistent = True
        # Print a list of format to format conversion which do not preserve meta-data
        inconsistent = False
        # Print a list of formats that failed conversion in general
        unsupported = False

        ####
        # OTHER SETTINGS
        ####
        # debug settings
        logger = Logger.getInstance()
        #logger.setLevel(logging.DEBUG)

        # run test either for most important formats or for all (see loadsave.TestIOFacilities)
        #__suffixes = self.__important # (choice 1)
        __suffixes = self.__important + self.__itk  # (choice 2)

        # dimensions and dtypes to check
        __suffixes = list(set(__suffixes))
        __ndims = [1, 2, 3, 4, 5]
        __dtypes = [
            scipy.bool_,
            scipy.int8,
            scipy.int16,
            scipy.int32,
            scipy.int64,
            scipy.uint8,
            scipy.uint16,
            scipy.uint32,
            scipy.uint64,
            scipy.float32,
            scipy.
            float64,  #scipy.float128, # last one removed, as not present on every machine
            scipy.complex64,
            scipy.complex128,
        ]  #scipy.complex256 ## removed, as not present on every machine

        # prepare struct to save settings that passed the test
        consistent_types = dict.fromkeys(__suffixes)
        for k0 in consistent_types:
            consistent_types[k0] = dict.fromkeys(__suffixes)
            for k1 in consistent_types[k0]:
                consistent_types[k0][k1] = dict.fromkeys(__ndims)
                for k2 in consistent_types[k0][k1]:
                    consistent_types[k0][k1][k2] = []

        # prepare struct to save settings that did not
        inconsistent_types = dict.fromkeys(__suffixes)
        for k0 in inconsistent_types:
            inconsistent_types[k0] = dict.fromkeys(__suffixes)
            for k1 in inconsistent_types[k0]:
                inconsistent_types[k0][k1] = dict.fromkeys(__ndims)
                for k2 in inconsistent_types[k0][k1]:
                    inconsistent_types[k0][k1][k2] = dict.fromkeys(__dtypes)

        # prepare struct to save settings that did not pass the data integrity test
        unsupported_types = dict.fromkeys(__suffixes)
        for k0 in consistent_types:
            unsupported_types[k0] = dict.fromkeys(__suffixes)
            for k1 in unsupported_types[k0]:
                unsupported_types[k0][k1] = dict.fromkeys(__ndims)
                for k2 in unsupported_types[k0][k1]:
                    unsupported_types[k0][k1][k2] = dict.fromkeys(__dtypes)

        # create artifical images, save them, load them again and compare them
        path = tempfile.mkdtemp()
        try:
            for ndim in __ndims:
                logger.debug('Testing for dimension {}...'.format(ndim))
                arr_base = scipy.random.randint(0, 10,
                                                list(range(10, ndim + 10)))
                for dtype in __dtypes:
                    arr_save = arr_base.astype(dtype)
                    for suffix_from in __suffixes:
                        # do not run test, if in avoid array
                        if ndim in self.__avoid and suffix_from in self.__avoid[
                                ndim]:
                            unsupported_types[suffix_from][suffix_from][ndim][
                                dtype] = "Test skipped, as combination in the tests __avoid array."
                            continue

                        # save array as file, load again to obtain header and set the meta-data
                        image_from = '{}/img{}'.format(path, suffix_from)
                        try:
                            save(arr_save, image_from, None, True)
                            if not os.path.exists(image_from):
                                raise Exception(
                                    'Image of type {} with shape={}/dtype={} has been saved without exception, but the file does not exist.'
                                    .format(suffix_from, arr_save.shape,
                                            dtype))
                        except Exception as e:
                            unsupported_types[suffix_from][suffix_from][
                                ndim][dtype] = e.message if hasattr(
                                    e, 'message') else str(e.args)
                            continue

                        try:
                            img_from, hdr_from = load(image_from)
                            img_from = img_from.astype(
                                dtype
                            )  # change dtype of loaded image again, as sometimes the type is higher (e.g. int64 instead of int32) after loading!
                        except Exception as e:
                            _message = e.message if hasattr(
                                e, 'message') else str(e.args)
                            unsupported_types[suffix_from][suffix_from][ndim][
                                dtype] = 'Saved reference image of type {} with shape={}/dtype={} could not be loaded. Reason: {}'.format(
                                    suffix_from, arr_save.shape, dtype,
                                    _message)
                            continue

                        header.set_pixel_spacing(hdr_from, [
                            scipy.random.rand() * scipy.random.randint(1, 10)
                            for _ in range(img_from.ndim)
                        ])
                        try:
                            header.set_pixel_spacing(hdr_from, [
                                scipy.random.rand() *
                                scipy.random.randint(1, 10)
                                for _ in range(img_from.ndim)
                            ])
                            header.set_offset(hdr_from, [
                                scipy.random.rand() *
                                scipy.random.randint(1, 10)
                                for _ in range(img_from.ndim)
                            ])
                        except Exception as e:
                            logger.error(
                                'Could not set the header meta-data for image of type {} with shape={}/dtype={}. This should not happen and hints to a bug in the code. Signaled reason is: {}'
                                .format(suffix_from, arr_save.shape, dtype, e))
                            unsupported_types[suffix_from][suffix_from][
                                ndim][dtype] = e.message if hasattr(
                                    e, 'message') else str(e.args)
                            continue

                        for suffix_to in __suffixes:
                            # do not run test, if in avoid array
                            if ndim in self.__avoid and suffix_to in self.__avoid[
                                    ndim]:
                                unsupported_types[suffix_from][suffix_to][ndim][
                                    dtype] = "Test skipped, as combination in the tests __avoid array."
                                continue

                            # for each other format, try format to format conversion an check if the meta-data is consistent
                            image_to = '{}/img_to{}'.format(path, suffix_to)
                            try:
                                save(img_from, image_to, hdr_from, True)
                                if not os.path.exists(image_to):
                                    raise Exception(
                                        'Image of type {} with shape={}/dtype={} has been saved without exception, but the file does not exist.'
                                        .format(suffix_to, arr_save.shape,
                                                dtype))
                            except Exception as e:
                                unsupported_types[suffix_from][suffix_from][
                                    ndim][dtype] = e.message if hasattr(
                                        e, 'message') else str(e.args)
                                continue

                            try:
                                _, hdr_to = load(image_to)
                            except Exception as e:
                                _message = e.message if hasattr(
                                    e, 'message') else str(e.args)
                                unsupported_types[suffix_from][suffix_to][ndim][
                                    dtype] = 'Saved testing image of type {} with shape={}/dtype={} could not be loaded. Reason: {}'.format(
                                        suffix_to, arr_save.shape, dtype,
                                        _message)
                                continue

                            msg = self.__diff(hdr_from, hdr_to)
                            if msg:
                                inconsistent_types[suffix_from][suffix_to][
                                    ndim][dtype] = msg
                            else:
                                consistent_types[suffix_from][suffix_to][
                                    ndim].append(dtype)

                            # remove testing image
                            if os.path.exists(image_to): os.remove(image_to)

                        # remove reference image
                        if os.path.exists(image_to): os.remove(image_to)

        except Exception:
            if not os.listdir(path): os.rmdir(path)
            else:
                logger.debug(
                    'Could not delete temporary directory {}. Is not empty.'.
                    format(path))
            raise

        if consistent:
            print(
                '\nthe following format conversions are meta-data consistent:')
            print('from\tto\tndim\tdtypes')
            for suffix_from in consistent_types:
                for suffix_to in consistent_types[suffix_from]:
                    for ndim, dtypes in list(
                            consistent_types[suffix_from][suffix_to].items()):
                        if list == type(dtypes) and not 0 == len(dtypes):
                            print(('{}\t{}\t{}D\t{}'.format(
                                suffix_from, suffix_to, ndim,
                                [str(x).split('.')[-1][:-2] for x in dtypes])))
        if inconsistent:
            print(
                '\nthe following form conversions are not meta-data consistent:'
            )
            print('from\tto\tndim\tdtype\t\terror')
            for suffix_from in inconsistent_types:
                for suffix_to in inconsistent_types[suffix_from]:
                    for ndim in inconsistent_types[suffix_from][suffix_to]:
                        for dtype, msg in list(inconsistent_types[suffix_from]
                                               [suffix_to][ndim].items()):
                            if msg:
                                print(('{}\t{}\t{}D\t{}\t\t{}'.format(
                                    suffix_from, suffix_to, ndim,
                                    str(dtype).split('.')[-1][:-2], msg)))

        if unsupported:
            print(
                '\nthe following form conversions could not be tested due to errors:'
            )
            print('from\tto\tndim\tdtype\t\terror')
            for suffix_from in unsupported_types:
                for suffix_to in unsupported_types[suffix_from]:
                    for ndim in unsupported_types[suffix_from][suffix_to]:
                        for dtype, msg in list(unsupported_types[suffix_from]
                                               [suffix_to][ndim].items()):
                            if msg:
                                print(('{}\t{}\t{}D\t{}\t\t{}'.format(
                                    suffix_from, suffix_to, ndim,
                                    str(dtype).split('.')[-1][:-2], msg)))
예제 #9
0
    def test_MetadataConsistency(self):
        """
        This test checks the ability of different image formats to consistently save
        meta-data information. Especially if a conversion between formats is required,
        that involves different 3rd party modules, this is not always guaranteed.
        
        The images are saved in one format, loaded and then saved in another format.
        Subsequently the differences in the meta-data is checked.
        
        Currently this test can only check:
        - voxel spacing
        - image offset
        
        Note that some other test are inherently performed by the
        loadsave.TestIOFacilities class:
        - data type
        - shape
        - content
        
        With the verboose switches, a comprehensive list of the results can be obtianed.
        """
        ####
        # VERBOOSE SETTINGS
        # The following are two variables that can be used to print some nicely
        # formatted additional output. When one of them is set to True, this unittest
        # should be run stand-alone.
        ####
        # Print a list of format to format conversion which preserve meta-data
        consistent = True
        # Print a list of format to format conversion which do not preserve meta-data
        inconsistent = True
        # Print a list of formats that failed conversion in general
        unsupported = False
        
        ####
        # OTHER SETTINGS
        ####
        # debug settings
        logger = Logger.getInstance()
        #logger.setLevel(logging.DEBUG)
        
        # run test either for most important formats or for all (see loadsave.TestIOFacilities)
        #__suffixes = self.__important # (choice 1)
        __suffixes = self.__pydicom + self.__nifti + self.__itk + self.__itk_more # (choice 2)
        
        # dimensions and dtypes to check
        __suffixes = list(set(__suffixes))
        __ndims = [1, 2, 3, 4, 5]
        __dtypes = [scipy.bool_,
                    scipy.int8, scipy.int16, scipy.int32, scipy.int64,
                    scipy.uint8, scipy.uint16, scipy.uint32, scipy.uint64,
                    scipy.float32, scipy.float64, #scipy.float128, # last one removed, as not present on every machine
                    scipy.complex64, scipy.complex128, ] #scipy.complex256 ## removed, as not present on every machine
        
        # prepare struct to save settings that passed the test
        consistent_types = dict.fromkeys(__suffixes)
        for k0 in consistent_types:
            consistent_types[k0] = dict.fromkeys(__suffixes)
            for k1 in consistent_types[k0]:
                consistent_types[k0][k1] = dict.fromkeys(__ndims)
                for k2 in consistent_types[k0][k1]:
                    consistent_types[k0][k1][k2] = []
        
        # prepare struct to save settings that did not
        inconsistent_types = dict.fromkeys(__suffixes)
        for k0 in inconsistent_types:
            inconsistent_types[k0] = dict.fromkeys(__suffixes)
            for k1 in inconsistent_types[k0]:
                inconsistent_types[k0][k1] = dict.fromkeys(__ndims)
                for k2 in inconsistent_types[k0][k1]:
                    inconsistent_types[k0][k1][k2] = dict.fromkeys(__dtypes)
        
        # prepare struct to save settings that did not pass the data integrity test
        unsupported_types = dict.fromkeys(__suffixes)
        for k0 in consistent_types:
            unsupported_types[k0] = dict.fromkeys(__suffixes)
            for k1 in unsupported_types[k0]:
                unsupported_types[k0][k1] = dict.fromkeys(__ndims)
                for k2 in unsupported_types[k0][k1]:
                    unsupported_types[k0][k1][k2] = dict.fromkeys(__dtypes)
        
        # create artifical images, save them, load them again and compare them
        path = tempfile.mkdtemp()
        try:
            for ndim in __ndims:
                logger.debug('Testing for dimension {}...'.format(ndim))
                arr_base = scipy.random.randint(0, 10, range(10, ndim + 10))
                for dtype in __dtypes:
                    arr_save = arr_base.astype(dtype)
                    for suffix_from in __suffixes:
                        # do not run test, if in avoid array
                        if ndim in self.__avoid and suffix_from in self.__avoid[ndim]:
                            unsupported_types[suffix_from][suffix_from][ndim][dtype] = "Test skipped, as combination in the tests __avoid array."
                            continue
                        
                        # save array as file, load again to obtain header and set the meta-data
                        image_from = '{}/img{}'.format(path, suffix_from)
                        try:
                            save(arr_save, image_from, None, True)
                            if not os.path.exists(image_from):
                                raise Exception('Image of type {} with shape={}/dtype={} has been saved without exception, but the file does not exist.'.format(suffix_from, arr_save.shape, dtype))
                        except Exception as e:
                            unsupported_types[suffix_from][suffix_from][ndim][dtype] = e.message
                            continue
                        
                        try:
                            img_from, hdr_from = load(image_from)
                            img_from = img_from.astype(dtype) # change dtype of loaded image again, as sometimes the type is higher (e.g. int64 instead of int32) after loading!
                        except Exception as e:
                            unsupported_types[suffix_from][suffix_from][ndim][dtype] = 'Saved reference image of type {} with shape={}/dtype={} could not be loaded. Reason: {}'.format(suffix_from, arr_save.shape, dtype, e.message)
                            continue

                        header.set_pixel_spacing(hdr_from, [scipy.random.rand() * scipy.random.randint(1, 10) for _ in range(img_from.ndim)])
                        try:
                            header.set_pixel_spacing(hdr_from, [scipy.random.rand() * scipy.random.randint(1, 10) for _ in range(img_from.ndim)])
                            header.set_offset(hdr_from, [scipy.random.rand() * scipy.random.randint(1, 10) for _ in range(img_from.ndim)])
                        except Exception as e:
                            logger.error('Could not set the header meta-data for image of type {} with shape={}/dtype={}. This should not happen and hints to a bug in the code. Signaled reason is: {}'.format(suffix_from, arr_save.shape, dtype, e))
                            unsupported_types[suffix_from][suffix_from][ndim][dtype] = e.message             
                            continue

                        for suffix_to in __suffixes:
                            # do not run test, if in avoid array
                            if ndim in self.__avoid and suffix_to in self.__avoid[ndim]:
                                unsupported_types[suffix_from][suffix_to][ndim][dtype] = "Test skipped, as combination in the tests __avoid array."
                                continue
                            
                            # for each other format, try format to format conversion an check if the meta-data is consistent
                            image_to = '{}/img_to{}'.format(path, suffix_to)
                            try:
                                save(img_from, image_to, hdr_from, True)
                                if not os.path.exists(image_to):
                                    raise Exception('Image of type {} with shape={}/dtype={} has been saved without exception, but the file does not exist.'.format(suffix_to, arr_save.shape, dtype))
                            except Exception as e:
                                unsupported_types[suffix_from][suffix_from][ndim][dtype] = e.message
                                continue
                            
                            try:
                                _, hdr_to = load(image_to)
                            except Exception as e:
                                unsupported_types[suffix_from][suffix_to][ndim][dtype] = 'Saved testing image of type {} with shape={}/dtype={} could not be loaded. Reason: {}'.format(suffix_to, arr_save.shape, dtype, e.message)
                                continue
                            
                            msg = self.__diff(hdr_from, hdr_to)
                            if msg:
                                inconsistent_types[suffix_from][suffix_to][ndim][dtype] = msg
                            else:
                                consistent_types[suffix_from][suffix_to][ndim].append(dtype)
                                
                            # remove testing image
                            if os.path.exists(image_to): os.remove(image_to)
                        
                        # remove reference image
                        if os.path.exists(image_to): os.remove(image_to)
                        
        except Exception:
            if not os.listdir(path): os.rmdir(path)
            else: logger.debug('Could not delete temporary directory {}. Is not empty.'.format(path))
            raise
        
        if consistent:
            print '\nthe following format conversions are meta-data consistent:'
            print 'from\tto\tndim\tdtypes'
            for suffix_from in consistent_types:
                for suffix_to in consistent_types[suffix_from]:
                    for ndim, dtypes in consistent_types[suffix_from][suffix_to].iteritems():
                        if list == type(dtypes) and not 0 == len(dtypes):
                            print '{}\t{}\t{}D\t{}'.format(suffix_from, suffix_to, ndim, map(lambda x: str(x).split('.')[-1][:-2], dtypes))
        if inconsistent:
            print '\nthe following form conversions are not meta-data consistent:'
            print 'from\tto\tndim\tdtype\t\terror'
            for suffix_from in inconsistent_types:
                for suffix_to in inconsistent_types[suffix_from]:
                    for ndim in inconsistent_types[suffix_from][suffix_to]:
                        for dtype, msg in inconsistent_types[suffix_from][suffix_to][ndim].iteritems():
                            if msg:
                                print '{}\t{}\t{}D\t{}\t\t{}'.format(suffix_from, suffix_to, ndim, str(dtype).split('.')[-1][:-2], msg)
            
        if unsupported:
            print '\nthe following form conversions could not be tested due to errors:'
            print 'from\tto\tndim\tdtype\t\terror'
            for suffix_from in unsupported_types:
                for suffix_to in unsupported_types[suffix_from]:
                    for ndim in unsupported_types[suffix_from][suffix_to]:
                        for dtype, msg in unsupported_types[suffix_from][suffix_to][ndim].iteritems():
                            if msg:
                                print '{}\t{}\t{}D\t{}\t\t{}'.format(suffix_from, suffix_to, ndim, str(dtype).split('.')[-1][:-2], msg)