Write a python 3.12 script that upscales all images with waifu2x using ncnn (in python).…
- User
Write a python 3.12 script that upscales all images with waifu2x using ncnn (in python). The program should go through D:\Bilder\Python\1. Input and its sub folders and save all processed images in D:\Bilder\Python\2. Output keeping the same folder structure. Use pillow not opencv
Certainly! Here's a Python 3.12 script that recursively processes all images in D:\Bilder\Python\1. Input and its subfolders using waifu2x-ncnn-vulkan, and saves the upscaled images to D:\Bilder\Python\2. Output, preserving the folder structure. The script uses Pillow for image handling and avoids using OpenCV.
Please make sure to update the path to your waifu2x-ncnn-vulkan.exe executable in the script before running it.
import os import subprocess import sys from PIL import Image
def process_images(input_dir, output_dir, waifu2x_exe): # List of valid image extensions valid_extensions = ('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.tiff', '.webp')
# Number of processed images count = 0 # Walk through the input directory for root, dirs, files in os.walk(input_dir): for file in files: if file.lower().endswith(valid_extensions): input_file_path = os.path.join(root, file) # Compute the relative path from input_dir rel_path = os.path.relpath(input_file_path, input_dir) output_file_path = os.path.join(output_dir, rel_path) # Ensure that the output directory exists os.makedirs(os.path.dirname(output_file_path), exist_ok=True) print(f'Processing {input_file_path} -> {output_file_path}') # Load the image using Pillow try: with Image.open(input_file_path) as img: img_format = img.format # Optional: Any image manipulation using Pillow can be done here except Exception as e: print(f'Error opening image {input_file_path}: {e}', file=sys.stderr) continue # Now process the image with waifu2x-ncnn-vulkan # Build the command cmd = [ waifu2x_exe, '-i', input_file_path, '-o', output_file_path, '-n', '1', # Denoise level (adjust as needed) '-s', '2', # Scale factor (adjust as needed) '-f', img_format.lower(), # Output image format ] # Run the command try: subprocess.run(cmd, check=True) count += 1 except subprocess.CalledProcessError as e: print(f'Error processing image {input_file_path}: {e}', file=sys.stderr) print(f'Processed {count} images.')if name == 'main': input_dir = r'D:\Bilder\Python\1. Input' output_dir = r'D:\Bilder\Python\2. Output' waifu2x_exe = r'path\to\waifu2x-ncnn-vulkan.exe' # Update this path to the actual executable
process_images(input_dir, output_dir, waifu2x_exe) - Assistant