Refactor the following code. Use path instead of os. Focus on clean code: import os…
- User
Refactor the following code. Use path instead of os. Focus on clean code: import os import shutil from PIL import Image import numpy as np
Define the input and output folders
input_folder = r'D:\Bilder\Python\1. Input' output_folder = r'D:\Bilder\Python\2. Output'
Thresholds (adjust these as needed)
diff_threshold = 5 # Threshold for color difference between channels fraction_colored_pixels_threshold = 0.05 # Threshold to consider an image as color
Create the output folder if it doesn't exist
if not os.path.exists(output_folder): os.makedirs(output_folder)
Walk through all subdirectories and files in the input_folder
for root, dirs, files in os.walk(input_folder): for filename in files: # Check if the file is an image if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')): # Full path of the image file image_path = os.path.join(root, filename) try: # Open the image and convert it to RGB image = Image.open(image_path).convert('RGB') except Exception as e: print(f"Error opening image {image_path}: {e}") continue # Skip files that cannot be opened as images
# Convert the image to a NumPy array image_np = np.array(image) total_pixels = image_np.shape[0] * image_np.shape[1] # Separate the RGB channels R = image_np[:, :, 0].astype(np.int16) G = image_np[:, :, 1].astype(np.int16) B = image_np[:, :, 2].astype(np.int16) # Compute the absolute differences between each pair of RGB channels diff_RG = np.abs(R - G) diff_RB = np.abs(R - B) diff_GB = np.abs(G - B) # Find the maximum difference among the three pairs for each pixel max_diff = np.maximum(np.maximum(diff_RG, diff_RB), diff_GB) # Count the number of pixels where the maximum difference exceeds the threshold num_colored_pixels = np.sum(max_diff > diff_threshold) fraction_colored_pixels = num_colored_pixels / total_pixels # Check if the image is a color image if fraction_colored_pixels >= fraction_colored_pixels_threshold: # It's a color image - move it to the output folder, maintaining subdirectory structure # Get the relative path of the image file with respect to the input folder relative_path = os.path.relpath(image_path, input_folder) # Compute the destination path destination_path = os.path.join(output_folder, relative_path) # Ensure the destination directory exists destination_dir = os.path.dirname(destination_path) if not os.path.exists(destination_dir): os.makedirs(destination_dir) # Move the image file shutil.move(image_path, destination_path) print(f"Moved color image: {relative_path}") else: # Image is not a color image, do nothing print(f"Skipped non-color image: {os.path.relpath(image_path, input_folder)}") - Assistant