To perform a bitwise XOR operation on a greyscale image using all possible one-byte masks (i.e., values from 0 to 255), we can use Python with the following libraries:
PIL (Pillow) for image loading and conversion to greyscale.
NumPy for efficient array operations.
Matplotlib for visualizing the results.
Below is a well-structured and functional Python script that performs the requested operation:
✅ Python Code: XOR Greyscale Image with All One-Byte Masks
python
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
# Generate a sample greyscale image (256x256 vertical gradient)
# This is used to demonstrate the XOR operation without needing an external image
sample_image = np.zeros((256, 256), dtype=np.uint8)
for i in range(256):
sample_image[i, :] = i
# Alternatively, load an image from file:
# img = Image.open('your_image.png').convert('L')
# sample_image = np.array(img)
# Iterate through all possible one-byte masks (0 to 255)
for mask in range(256):
# Apply XOR operation
xor_image = sample_image ^ mask
# Display the result
plt.figure(figsize=(4, 4))
plt.imshow(xor_image, cmap='gray')
plt.title(f'Mask: {mask}', fontsize=10)
plt.axis('off') # Hide axes for cleaner output
plt.show()
🧠 Explanation
Image Generation:
A 256×256 greyscale image is generated as a vertical gradient. Each row has a constant value (from 0 to 255), which helps visualize how XOR changes the image.
XOR Operation:
For each value of mask (from 0 to 255), the XOR operation is applied to every pixel in the image.
The result is a new greyscale image, where each pixel value is original_pixel ^ mask.
Display:
Using matplotlib.pyplot.imshow, each XORed image is displayed in a separate figure.
The cmap='gray' ensures the image is shown in greyscale.
plt.axis('off') hides the axes for a cleaner visual.
📌 Notes
This script will open 256 separate windows (one for each mask). This can be overwhelming in some environments.
If you're using Jupyter Notebook, consider using plt.close() inside the loop to avoid memory issues.
You can replace the sample image with any real greyscale image by uncommenting the relevant lines and providing a valid file path.
🧪 Example Output
For mask 0, the image remains unchanged.
For mask 255, the image is inverted (since x ^ 255 = 255 - x for 8-bit values).
For other masks, the result is a unique greyscale transformation based on the XOR logic.
This code is a robust and educational approach to understanding how XOR can be used in image processing, particularly for encryption or pattern analysis.