I have a folder containing images (PNG) of brain slices. I want to write a script that rotates the images, so that the brain slice are all aligned in the same direction. I have written the following code that, uses scikit-image’s phase_cross_correlation, and I have chosen three example images that all have the correct alignment. The code saves the new aligned png files in a new folder, but when I looked at the images, they were mostly completely blank or only had a bit of the brain in the image. Here is my code:
import os
import numpy as np
from skimage import io, transform, registration, exposure
example_image_paths = ['/path/to/example_image1.png', '/path/to/example_image2.png', '/path/to/example_image3.png']
print('Reading example images')
example_images = [io.imread(path) for path in example_image_paths]
print('Example images have been read')
def align_images_with_examples(image, example_images):
aligned_image = image.copy()
for i, example_image in enumerate(example_images):
shift, error, phasediff = registration.phase_cross_correlation(example_image, image)
angle_rad = np.arctan2(shift[0], shift[1])
angle_deg = np.degrees(angle_rad)
affine_transform = transform.AffineTransform(rotation=angle_deg)
aligned_image = transform.warp(aligned_image, affine_transform)
print(f"Image shifted by {shift} pixels and rotated by {angle_deg} degrees with respect to example image {i+1}.")
return aligned_image
image_dir = '/path/to/input/images'
# Directory to save aligned images (replace with your actual path)
output_dir = '/path/to/output/aligned_images'
image_files = os.listdir(image_dir)
for file in image_files:
image_path = os.path.join(image_dir, file)
image = io.imread(image_path)
aligned_image = align_images_with_examples(image, example_images)
# Rescale intensity of aligned image
aligned_image = exposure.rescale_intensity(aligned_image, out_range=(0, 255))
output_path = os.path.join(output_dir, file)
# Save aligned image
io.imsave(output_path, aligned_image.astype(np.uint8))
print(f"Image saved to: {output_path}")
Can anyone see what is wrong? Or perhaps suggest an alternative way to do this?