Here is a Python script that traverses through the input directory D:\Bilder\Python\1. Input and its subfolders, applies frequency domain filtering to remove moiré patterns from each image, and saves the processed images to D:\Bilder\Python\2. Output, keeping the same folder structure. The script uses the Pillow and NumPy libraries.
import os
import numpy as np
from PIL import Image
# Define input and output directories
input_dir = r'D:\Bilder\Python\1. Input'
output_dir = r'D:\Bilder\Python\2. Output'
def remove_moire(image):
"""
Apply frequency domain filtering to remove moiré patterns from an image.
"""
# Convert image to grayscale
img_gray = image.convert('L')
img_array = np.array(img_gray, dtype=np.float32)
# Perform 2D FFT
f = np.fft.fft2(img_array)
fshift = np.fft.fftshift(f)
# Create a mask to suppress frequencies corresponding to moiré patterns
rows, cols = img_array.shape
crow, ccol = rows // 2, cols // 2 # Center coordinates
# Create a band-stop filter mask
# Adjust the radius values based on the specific characteristics of the moiré patterns
radius_inner = 10 # Inner radius of the band to suppress
radius_outer = 50 # Outer radius of the band to suppress
mask = np.ones((rows, cols), dtype=np.uint8)
Y, X = np.ogrid[:rows, :cols]
distance = np.sqrt((X - ccol)**2 + (Y - crow)**2)
mask[np.logical_and(distance >= radius_inner, distance <= radius_outer)] = 0
# Apply the mask to the shifted FFT
fshift_filtered = fshift * mask
# Inverse FFT to reconstruct the image
f_ishift = np.fft.ifftshift(fshift_filtered)
img_back = np.fft.ifft2(f_ishift)
img_back = np.abs(img_back)
# Normalize the pixel values to the 0-255 range
img_back_norm = 255 * (img_back - np.min(img_back)) / (np.ptp(img_back))
img_back_uint8 = img_back_norm.astype(np.uint8)
# Convert back to PIL Image
img_filtered = Image.fromarray(img_back_uint8)
return img_filtered
# Traverse the input directory and process images
for root, dirs, files in os.walk(input_dir):
for filename in files:
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.tif', '.tiff', '.bmp', '.gif')):
input_file_path = os.path.join(root, filename)
# Calculate the relative path to maintain folder structure
rel_path = os.path.relpath(root, input_dir)
output_dir_path = os.path.join(output_dir, rel_path)
os.makedirs(output_dir_path, exist_ok=True)
output_file_path = os.path.join(output_dir_path, filename)
try:
# Open the image
image = Image.open(input_file_path)
# Apply moiré pattern removal
image_filtered = remove_moire(image)
# Save the processed image
image_filtered.save(output_file_path)
print(f"Processed {input_file_path} and saved to {output_file_path}")
except Exception as e:
print(f"Failed to process {input_file_path}: {e}")
Explanation of the Script:
Adjusting the Filter Parameters:
- The
radius_inner and radius_outer parameters define the range of frequencies to suppress. These values may need to be adjusted based on the specific characteristics of the moiré patterns in your images.
- Recommendation: You may experiment with different values for
radius_inner and radius_outer to achieve optimal results for your dataset.
Requirements:
- Pillow: Ensure you have the Pillow library installed (
pip install Pillow).
- NumPy: Ensure you have NumPy installed (
pip install numpy).
Running the Script:
- Save the Script: Save the script to a file named
remove_moire.py.
- Install Dependencies:
pip install Pillow numpy
- Run the Script:
python remove_moire.py
Make sure to run the script in an environment where you have the necessary permissions to read from the input directory and write to the output directory.
Note:
- The script processes all images in the input directory and its subfolders. It preserves the subfolder structure in the output directory.
- The processing might take some time depending on the number and size of the images.
- The script prints the status of each processed image. If any image fails to process, it will print an error message but continue processing the remaining images.
Example Output:
Processed D:\Bilder\Python\1. Input\image1.jpg and saved to D:\Bilder\Python\2. Output\image1.jpg
Processed D:\Bilder\Python\1. Input\Subfolder\image2.png and saved to D:\Bilder\Python\2. Output\Subfolder\image2.png
...
Troubleshooting:
- Unexpected Results: If the moiré patterns are not adequately removed, consider adjusting the
radius_inner and radius_outer parameters.
- Performance Issues: Processing large images or a large number of images might consume significant memory and processing power. Consider resizing images before processing if appropriate.
Feel free to modify the script to suit your specific needs, such as processing only certain types of images or integrating additional image processing techniques.