To make the algorithm rotation-independent, you need to consider differences in all directions around the pixel, not just to its left neighbor. One effective way to achieve this is by using the gradient magnitude, which considers differences in both the x and y directions.
To accomplish this, we'll use the Sobel operator, which is a common approach in image processing for edge detection. The Sobel operator computes the gradient of the image intensity at each pixel, giving us a measure of how the intensity changes in both the x and y directions.
Here's the Python script to achieve this:
from PIL import Image
import numpy as np
from scipy.ndimage import sobel
def calculate_gradient_magnitude(image_array):
# Compute the gradient in the X direction
dx = sobel(image_array, axis=0, mode='constant')
# Compute the gradient in the Y direction
dy = sobel(image_array, axis=1, mode='constant')
# Compute the gradient magnitude
gradient_magnitude = np.hypot(dx, dy)
# Normalize to fit within 8-bit range
gradient_magnitude = (gradient_magnitude / gradient_magnitude.max()) * 255
return gradient_magnitude.astype(np.uint8)
# Open the image and convert to grayscale
image_path = 'image.png'
image = Image.open(image_path).convert('L')
image_data = np.array(image)
# Calculate the gradient magnitude
gradient_magnitude = calculate_gradient_magnitude(image_data)
# Convert the result back to an image
diff_image = Image.fromarray(gradient_magnitude, 'L')
# Save the new image
diff_image.save('difference_image.png')
print("Difference image saved as 'difference_image.png'.")
Explanation:
-
Loading and Converting Image:
Image.open(image_path).convert('L') opens the image and converts it to grayscale.
-
Calculating Gradient Magnitude:
dx = sobel(image_array, axis=0, mode='constant') computes the gradient of the image in the x direction.
dy = sobel(image_array, axis=1, mode='constant') computes the gradient of the image in the y direction.
gradient_magnitude = np.hypot(dx, dy) computes the magnitude of the gradient from the x and y gradients using Euclidean distance.
gradient_magnitude = (gradient_magnitude / gradient_magnitude.max()) * 255 normalizes the gradient magnitude to fit within the 8-bit range (0-255).
-
Creating and Saving the New Image:
Image.fromarray(gradient_magnitude, 'L') converts the gradient magnitude matrix back to an image.
diff_image.save('difference_image.png') saves the new image.
This approach ensures that the result is not dependent on the rotation of the image because the gradient magnitude captures the intensity changes in all directions. The Sobel operator is a well-established technique for detecting edges and changes in intensity, which makes it suitable for this task.