Problem Statement: Coding - Batch Image Processor
You are given a set of images in a directory. Your task is to create a batch image processor that can process these images in parallel. The processor should resize each image to a specified size and then save the resized images to a new directory.
Examples:
Input:
Output:
Input:
Output:
Constraints:
Hints:
PIL library to handle image processing tasks.concurrent.futures module to process images in parallel.Solution: `python from PIL import Image import os from concurrent.futures import ThreadPoolExecutor
def resize_image(image_path, output_path, size): try: with Image.open(image_path) as img: img = img.resize(size) img.save(os.path.join(output_path, os.path.basename(image_path))) except Exception as e: print(f"Error processing {image_path}: {e}")
def batch_image_processor(input_dir, output_dir, size): if not os.path.exists(output_dir): os.makedirs(output_dir)
image_paths = [os.path.join(input_dir, file) for file in os.listdir(input_dir) if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif'))]
with ThreadPoolExecutor() as executor:
executor.map(lambda path: resize_image(path, output_dir, size), image_paths)
input_dir = "/path/to/images" output_dir = "/path/to/resized_images" image_size = (100, 100) batch_image_processor(input_dir, output_dir, image_size) `
Explanation:
resize_image to resize a single image and save it to the output directory.batch_image_processor to process all images in parallel.ThreadPoolExecutor to process images concurrently.This solution processes images in parallel, resizing them to the specified size and saving them to the output directory. It handles errors and creates the output directory if it does not exist.