Here's a Python script that walks through D:\Bilder\Python\1. Input and its subfolders, processes each image using frequency domain filtering to remove moiré patterns, and saves the processed images to D:\Bilder\Python\2. Output while keeping the same folder structure.
import os
import cv2
import numpy as np
def remove_moire_pattern(img):
"""
Remove moiré patterns from an image using frequency domain filtering.
Parameters:
img (numpy.ndarray): Input image in BGR format.
Returns:
numpy.ndarray: Processed image with moiré patterns reduced.
"""
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Perform FFT on the image
f = np.fft.fft2(gray)
fshift = np.fft.fftshift(f)
# Compute the magnitude spectrum
magnitude_spectrum = 20 * np.log(np.abs(fshift) + 1)
# Normalize the magnitude spectrum for thresholding
mag_spec_norm = cv2.normalize(magnitude_spectrum, None, 0, 255, cv2.NORM_MINMAX)
mag_spec_norm = mag_spec_norm.astype(np.uint8)
# Threshold to find peaks in the magnitude spectrum (possible moiré frequencies)
threshold_value = np.percentile(mag_spec_norm, 99)
_, mag_spec_thresh = cv2.threshold(mag_spec_norm, threshold_value, 255, cv2.THRESH_BINARY)
# Remove small noise in the thresholded image
kernel = np.ones((3, 3), np.uint8)
mag_spec_thresh = cv2.morphologyEx(mag_spec_thresh, cv2.MORPH_OPEN, kernel)
# Create a mask by inverting the thresholded magnitude spectrum
mask = np.ones(fshift.shape, np.uint8)
mask[mag_spec_thresh > 0] = 0
# Exclude the DC component (center of the spectrum)
rows, cols = gray.shape
crow, ccol = rows // 2, cols // 2 # Center coordinates
cv2.circle(mask, (ccol, crow), 10, 1, -1)
# Apply mask to the shifted FFT
fshift_masked = fshift * mask
# Perform inverse FFT to get the filtered image
f_ishift = np.fft.ifftshift(fshift_masked)
img_back = np.fft.ifft2(f_ishift)
img_back = np.abs(img_back)
# Normalize to uint8
img_filtered = cv2.normalize(img_back, None, 0, 255, cv2.NORM_MINMAX)
img_filtered = img_filtered.astype(np.uint8)
# Convert back to BGR to save as a color image
img_filtered_color = cv2.cvtColor(img_filtered, cv2.COLOR_GRAY2BGR)
return img_filtered_color
def process_images(input_dir, output_dir):
"""
Process images in the input directory to remove moiré patterns and save them to the output directory.
Parameters:
input_dir (str): Path to the input directory containing images.
output_dir (str): Path to the output directory where processed images will be saved.
"""
# Walk through the input directory and its subdirectories
for root, dirs, files in os.walk(input_dir):
for file in files:
# Process only image files with common extensions
if file.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.tiff')):
input_file_path = os.path.join(root, file)
# Compute relative path to the input directory
rel_path = os.path.relpath(root, input_dir)
# Build output directory path
output_root = os.path.join(output_dir, rel_path)
if not os.path.exists(output_root):
os.makedirs(output_root)
output_file_path = os.path.join(output_root, file)
print(f"Processing {input_file_path}")
# Read the image
img = cv2.imread(input_file_path)
# Check if the image was loaded successfully
if img is None:
print(f"Failed to load image {input_file_path}")
continue
# Remove moiré pattern from the image
processed_img = remove_moire_pattern(img)
# Save the processed image
cv2.imwrite(output_file_path, processed_img)
print(f"Saved processed image to {output_file_path}")
if __name__ == "__main__":
input_dir = r"D:\Bilder\Python\1. Input"
output_dir = r"D:\Bilder\Python\2. Output"
process_images(input_dir, output_dir)
Explanation:
Usage:
- Ensure you have OpenCV installed:
pip install opencv-python
- Place your images in
D:\Bilder\Python\1. Input directory (with subfolders if any).
- Run the script. Processed images will be saved in
D:\Bilder\Python\2. Output, mirroring the folder structure of the input directory.
Notes:
- The script processes common image formats like PNG, JPG, JPEG, BMP, and TIFF.
- Moiré patterns can vary greatly depending on the image, so the effectiveness of the frequency domain filtering might vary.
- This script uses an adaptive method by thresholding the magnitude spectrum to identify and suppress moiré frequencies.
- The processing might take some time depending on the number and size of images.
Feel free to adjust the parameters in the remove_moire_pattern function (like the threshold percentile or the size of the mask) to better suit your specific images and achieve better results in moiré pattern removal.