示例#1
0
def bulk_apply_mask(image_dir,
                    mask_dir,
                    output_dir,
                    output_suffix,
                    skip_existing_images=True):
    """Find corresponding images between dirs and apply the second as a mask
        
        Inputs:
        image_dir -- Directory of images to-be-masked
        mask_dir -- Directory of images that will be used as the mask
        output_dir -- Directory where the masked images will be saved
        ouptut_suffix -- Filename text after the core/sample name of the image file
        """

    (image_path_list,
     mask_path_list) = blk.find_shared_images(image_dir, mask_dir)

    for i in range(np.size(image_path_list)):

        masked_path = blk.create_new_image_path(image_path_list[i], output_dir,
                                                output_suffix)
        if masked_path.exists() and skip_existing_images:
            continue

        image = meta.setup_image(image_path_list[i])
        mask = meta.setup_image(mask_path_list[i]) > 0

        print('Masking ' + os.path.basename(image_path_list[i]) + ' with ' +
              os.path.basename(mask_path_list[i]))

        masked_image = sitk.Mask(image, mask)
        meta.copy_relevant_metadata(masked_image, image)

        meta.write_image(masked_image, masked_path)
示例#2
0
def apply_polarization_transforms(path_image, output_dir, transform_dir, transform_prefix, resolution,
                                  skip_existing_images=True):
        """
        Apply pre-calculated transforms onto a single mueller polarimetry image

        :param path_image: path to the image being processed
        :param output_dir: directory to save the image to
        :param resolution: resolution of the image file
        :return:
        """
        print('Applying transforms to {0}'.format(path_image.stem))
        
        fixed_image = czi_timepoint_to_sitk_image(path_image, 0, resolution)

        for num in range(24):
                output_path = Path(output_dir, path_image.stem + '_' + str(num + 1) + '.tif')
                # if skip_existing_images and output_path.is_file():
                #         continue

                moving_image = czi_timepoint_to_sitk_image(path_image, num, resolution)
                transform_path = Path(transform_dir, transform_prefix + '_' + str(num + 1) + '.tfm')
                
                if num == 0:
                        meta.write_image(fixed_image, output_path)
                else:
                        registered_image = tran.apply_transform_fromfile(fixed_image, moving_image, str(transform_path))
                        meta.write_image(registered_image, output_path)
示例#3
0
def bulk_resize_image(fixed_dir,
                      moving_dir,
                      output_dir,
                      output_suffix,
                      skip_existing_images=False):
    """Resize multiple images to corresponding reference size"""
    (fixed_image_path_list,
     moving_image_path_list) = blk.find_shared_images(fixed_dir, moving_dir)

    for i in range(0, np.size(fixed_image_path_list)):
        resized_path = blk.create_new_image_path(moving_image_path_list[i],
                                                 output_dir, output_suffix)
        if resized_path.exists() and skip_existing_images:
            continue

        current_spacing = meta.get_image_parameters(moving_image_path_list[i],
                                                    return_origin=True,
                                                    return_spacing=True)[0]

        target_spacing = meta.get_image_parameters(fixed_image_path_list[i],
                                                   return_origin=True,
                                                   return_spacing=True)[0]

        moving_image = sitk.ReadImage(str(moving_image_path_list[i]))
        resized_image = resize_image(moving_image_path_list[i],
                                     current_spacing, target_spacing)

        meta.write_image(resized_image, resized_path)
示例#4
0
def bulk_resize_to_target(image_dir,
                          output_dir,
                          output_suffix,
                          target_spacing,
                          skip_existing_images=False):

    image_name_list = [
        Path(f) for f in os.listdir(image_dir) if f.endswith('.tif')
    ]

    for i in range(0, np.size(image_name_list)):
        image_path = Path(image_dir, image_name_list[i])

        resized_path = blk.create_new_image_path(image_path, output_dir,
                                                 output_suffix)
        if resized_path.exists() and skip_existing_images:
            continue

        current_spacing = meta.get_image_parameters(image_path,
                                                    return_origin=False,
                                                    return_spacing=True)[0][0]
        itk_image = meta.setup_image(image_path)
        image_name = os.path.basename(image_path)
        print('\nResizing ' + image_name + ' from ' + str(current_spacing) +
              ' to target spacing ' + str(target_spacing) + ')')

        resized_image = resize_image(itk_image, current_spacing,
                                     target_spacing)

        meta.write_image(resized_image, resized_path)
示例#5
0
def bulk_apply_transform(fixed_dir,
                         moving_dir,
                         transform_dir,
                         output_dir,
                         output_suffix,
                         skip_existing_images=False):

    fixed_paths, moving_paths, transform_paths = blk.find_bulk_shared_images(
        [fixed_dir, moving_dir, transform_dir])

    for i in range(0, np.size(fixed_paths)):
        registered_path = blk.create_new_image_path(moving_paths[i],
                                                    output_dir, output_suffix)

        if registered_path.exists() and skip_existing_images:
            continue

        fixed_image = meta.setup_image(fixed_paths[i])
        moving_image = meta.setup_image(moving_paths[i])

        print('\nApplying transform onto {0} based on transform on {1}'.format(
            str(moving_paths[i].name), str(transform_paths[i].name)))

        transform_path = Path(transform_paths[i].parent,
                              transform_paths[i].stem + '.tfm')
        registered_image = apply_transform_fromfile(fixed_image, moving_image,
                                                    transform_path)

        meta.write_image(registered_image, registered_path)
        write_transform(registered_path,
                        sitk.ReadTransform(str(transform_path)))

    return
示例#6
0
def batch_downsample_retardance(ret_dir, orient_dir, output_dir,
                                scale_factor,
                                simulated_resolution_factor=None):
        output_suffix = 'DownSample-' + str(scale_factor) + 'x'
        
        if (simulated_resolution_factor
                    and simulated_resolution_factor != scale_factor):
                output_suffix = (output_suffix + '_SimRes-'
                                 + str(simulated_resolution_factor) + 'x')
        
        (ret_image_path_list, orient_image_path_list) = blk.find_shared_images(
                ret_dir, orient_dir)
        
        for i in range(0, np.size(ret_image_path_list)):
                (down_ret_image, down_orient_image) = downsample_retardance_image(
                        ret_image_path_list[i], orient_image_path_list[i],
                        scale_factor, simulated_resolution_factor)
                
                down_ret_dir = os.path.join(output_dir, output_suffix, '_ret', )
                down_orient_dir = os.path.join(output_dir, output_suffix, 'SlowAxis', )
                
                down_ret_path = blk.create_new_image_path(ret_image_path_list[i],
                                                          down_ret_dir,
                                                          '__ret_' + output_suffix)
                
                down_orient_path = blk.create_new_image_path(
                        orient_image_path_list[i],
                        down_orient_dir,
                        '_SlowAxis_' + output_suffix)
                
                meta.write_image(down_ret_image, down_ret_path)
                meta.write_image(down_orient_image, down_orient_path)
示例#7
0
def bulk_supervised_register_images(
        fixed_dir: Path,
        moving_dir: Path,
        output_dir: Path,
        output_suffix: str,
        write_output: bool = True,
        write_transform: bool = True,
        transform_type: type = sitk.AffineTransform,
        registration_parameters: dict = None,
        skip_existing_images=True):
    """Register two directories of images, matching based on the core name, the string before the first _
    
        :param fixed_dir: directory holding the images that are being registered to
        :param moving_dir: directory holding the images that will be registered
        :param output_dir: directory to save the output images
        :param output_suffix: base name of the output images
        :param write_output: whether or not to actually write the output image
        :param write_transform: whether or not to write down the transform that produced the output
        :param transform_type: what type of registration, e.g. affine or euler
        :param registration_parameters: dictionary of registration key/value arguments
        :param skip_existing_images: whether to skip images that already have a transform/output image
        :return:
        """

    (fixed_path_list,
     moving_path_list) = blk.find_shared_images(fixed_dir, moving_dir)

    for i in range(0, np.size(fixed_path_list)):
        registered_path = blk.create_new_image_path(moving_path_list[i],
                                                    output_dir, output_suffix)
        if registered_path.exists() and skip_existing_images:
            continue

        fixed_image = meta.setup_image(fixed_path_list[i])
        moving_image = meta.setup_image(moving_path_list[i])
        initial_transform = tran.read_initial_transform(
            moving_path_list[i], transform_type)

        print('\nRegistering ' + os.path.basename(moving_path_list[i]) +
              ' to ' + os.path.basename(fixed_path_list[i]))

        registered_image, transform, metric, stop = \
                supervised_register_images(fixed_image, moving_image, initial_transform,
                                           moving_path_list[i], registration_parameters)

        if write_output:
            meta.write_image(registered_image, registered_path)

        if write_transform:
            tran.write_transform(registered_path, transform)
示例#8
0
def bulk_orientation_to_proper_degrees(input_dir, output_dir, output_suffix,
                                       skip_existing_images=True):
        path_list = util.list_filetype_in_dir(input_dir, '.tif')
        for i in range(len(path_list)):
                output_path = blk.create_new_image_path(
                        path_list[i], output_dir, output_suffix)
                if output_path.exists() and skip_existing_images:
                        continue
                
                print('Converting {} to degrees proper'.format(path_list[i].name))
                orient_img = meta.setup_image(path_list[i])
                deg_img = sitk.Divide(orient_img, 100)
                img = rotate_90_degrees(deg_img)
                
                meta.write_image(img, output_path)
示例#9
0
def bulk_intensity_to_retardance(input_dir, output_dir, output_suffix,
                                 skip_existing_images=True):
        path_list = util.list_filetype_in_dir(input_dir, '.tif')
        
        for i in range(len(path_list)):
                output_path = blk.create_new_image_path(
                        path_list[i], output_dir, output_suffix)
                if output_path.exists() and skip_existing_images:
                        continue
                
                print('Converting {} to degrees linear retardance'.format(path_list[i].name))
                
                int_image = meta.setup_image(path_list[i])
                ret_image = convert_intensity_to_retardance(int_image)

                meta.write_image(ret_image, output_path)
示例#10
0
def bulk_threshold(input_dir,
                   output_dir,
                   output_suffix,
                   threshold=1,
                   skip_existing_images=False):
    """Apply intensity based thresholds to all images in folder"""
    path_list = util.list_filetype_in_dir(input_dir, '.tif')

    for i in range(len(path_list)):
        new_path = blk.create_new_image_path(path_list[i], output_dir,
                                             output_suffix)
        if new_path.exists() and skip_existing_images:
            continue

        original = meta.setup_image(path_list[i])
        new_image = apply_threshold(original,
                                    os.path.basename(path_list[i]),
                                    threshold=threshold)

        meta.copy_relevant_metadata(new_image, original)
        meta.write_image(new_image, new_path)
示例#11
0
def parameters_file_to_metadata(dir_params):
        path_params = Path(dir_params, 'Image Parameters.csv')
        df_params = pd.read_csv(path_params, index_col=0)
        
        for idx in df_params.index:
                image_parameters = df_params.loc[idx]
                path_image= Path(dir_params, idx)
                path_metadata = Path(dir_params, Path(idx).stem + '_metadata.txt')
                
                if path_metadata.is_file():
                        return
                else:
                        image = sitk.ReadImage(str(path_image))
                        print('Adjusting {0}'.format(idx))
                        unit = 'microns'
                        
                        spacing = [float(image_parameters['Spacing']),
                                   float(image_parameters['Spacing'])]
                        image.SetSpacing(spacing)
                        image.SetMetaData('Unit', unit)
                        
                        meta.write_image(image, path_image)
示例#12
0
def bulk_convert_to_eightbit(input_dir, output_dir, output_suffix):
    """Convert all tif images in a directory to 8bit and save in new directory
        
        Inputs:
        input_dir -- Directory of images to convert
        output_dir -- Directory to save converted images
        output_suffix -- Text in output image name after the core/sample name
        
        """

    path_list = util.list_filetype_in_dir(input_dir, '.tif')

    for i in range(len(path_list)):
        original = meta.setup_image(path_list[i])
        new_image = convert_to_eightbit(original,
                                        os.path.basename(path_list[i]))

        new_path = blk.create_new_image_path(path_list[i], output_dir,
                                             output_suffix)

        meta.copy_relevant_metadata(new_image, original)
        meta.write_image(new_image, new_path)