Write a python 3.12 scribt that upscales all images with waifu2x. Use spandrel to implement waifu2x. The programm should go through D:\Bilder\Python\1. Input and its subfolders and save all processed images in D:\Bilder\Python\2. Output keeping the same folder structure. Use pillow and numpy
Assistant
python
import os
import numpy as np
from PIL import Image
# Import spandrel or the waifu2x upscaling function
try:
import spandrel
except ImportError:
spandrel = None
print("Please install spandrel to use waifu2x upscaling.")
# Define the upscaling function
def upscale_image(image_array):
if spandrel:
# Assuming spandrel has a function called `upscale` that takes a NumPy array and returns an upscaled NumPy array
upscaled_array = spandrel.upscale(image_array)
return upscaled_array
else:
# Placeholder: using PIL to resize image (this is not waifu2x upscaling)
img = Image.fromarray(image_array)
width, height = img.size
# Simple upscaling by a factor of 2 using bicubic interpolation
upscaled_img = img.resize((width * 2, height * 2), Image.BICUBIC)
return np.array(upscaled_img)
# Input and output directories
input_dir = r'D:\Bilder\Python\1. Input'
output_dir = r'D:\Bilder\Python\2. Output'
# Valid image extensions
image_extensions = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.gif')
# Walk through the input directory
for root, dirs, files in os.walk(input_dir):
# Compute relative path from input directory
rel_path = os.path.relpath(root, input_dir)
# Corresponding output directory
output_root = os.path.join(output_dir, rel_path)
# Ensure output directory exists
os.makedirs(output_root, exist_ok=True)
for file in files:
if file.lower().endswith(image_extensions):
input_file_path = os.path.join(root, file)
output_file_path = os.path.join(output_root, file)
try:
# Open the image
image = Image.open(input_file_path).convert('RGB')
# Convert to numpy array
img_array = np.array(image)
# Process the image with spandrel or placeholder function
upscaled_array = upscale_image(img_array)
# Convert back to image
upscaled_image = Image.fromarray(upscaled_array)
# Save the image
upscaled_image.save(output_file_path)
print(f"Processed and saved {output_file_path}")
except Exception as e:
print(f"Failed to process {input_file_path}: {e}")
This script accomplishes the following:
Imports necessary modules: os for directory traversal, numpy for image array manipulation, and PIL.Image from the Pillow library for image processing.
Attempts to import spandrel: The script tries to import the spandrel module, which is supposed to implement waifu2x upscaling. If it's not installed, a placeholder function is used, and a message prompts the user to install it.
Defines upscale_image function: This function uses spandrel to upscale images if available. If spandrel is not available, it uses a placeholder that simply doubles the image size using bicubic interpolation (note that this does not produce the same quality as waifu2x).
Walks through the input directory: It recursively goes through D:\Bilder\Python\1. Input and its subdirectories.
Processes each image file:
Checks if the file has a valid image extension.
Opens the image and converts it to a NumPy array.
Upscales the image using the upscale_image function.
Converts the upscaled NumPy array back to a PIL Image.
Saves the upscaled image to the corresponding location in D:\Bilder\Python\2. Output, maintaining the directory structure.
Handles errors: If an image fails to process, it catches the exception and prints an error message, allowing the script to continue processing other images.
Instructions for using the script:
Install the required libraries:
Ensure you have Python 3.12 installed.
Install Pillow: pip install Pillow
Install NumPy: pip install numpy
Install spandrel (if available): Since spandrel is not a standard library, you need to install it according to its documentation (e.g., cloning the repository or installing via pip if it's published).
Adjust the directories:
Make sure the input_dir and output_dir variables point to the correct paths on your system.
Run the script:
Execute the script in your Python environment.
Note: The placeholder upscaling function provided (using bicubic interpolation) does not replicate the waifu2x upscaling method. To achieve actual waifu2x upscaling, you need to have spandrel properly installed and ensure it provides an upscale function that accepts and returns a NumPy array representing the image.