Before we start i would like to show you my work:
Here are some examples of what my code do:
I encountered a challenge with my collection of colored images — they simply weren’t meeting my preference. In pursuit of a solution, I decided to automate the process of converting these colored images to black and white. This not only addressed my aesthetic preferences but also offered a more cohesive visual style for my image repository. Below is the script I devised to seamlessly transition from colored to black and white images.
Let me explain the code step by step:
from PIL import Image
import os
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
PIL
: This is the Python Imaging Library that provides the Image
class for handling images.os
: This module provides a way to interact with the operating system, like working with file paths and directories.time
: This module is used for adding a short delay to the script.watchdog
: This library is used for monitoring file system events. class ImageHandler(FileSystemEventHandler):
def on_created(self, event):
if event.is_directory:
return
input_path = event.src_path
filename = os.path.basename(input_path)
if filename.lower().endswith(('.jpg', '.jpeg', '.png')):
output_directory = 'Gray_Images'
output_path = os.path.join(output_directory, f"bw_{filename}")
convert_to_black_and_white(input_path, output_path)
FileSystemEventHandler
, which provides methods for handling file system events.on_created
method is called when a new file is created.convert_to_black_and_white
. def convert_to_black_and_white(input_path, output_path):
try:
img = Image.open(input_path)
bw_img = img.convert("L")
bw_img.save(output_path)
print(f"Image converted to black and white: {output_path}")
except Exception as e:
print(f"Error processing {input_path}: {e}")
"L"
mode, and saves the result. if __name__ == "__main__":
input_directory = 'Colored_Images'
output_directory = 'Gray_Images'
os.makedirs(output_directory, exist_ok=True)
event_handler = ImageHandler()
observer = Observer()
observer.schedule(event_handler, path=input_directory, recursive=False)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
ImageHandler
and Observer
instances.input_directory
for file creation events (recursive=False means it won’t look into subdirectories).In summary, this script continuously monitors the Colored_Images
directory for new image files and converts them to black and white, saving the results in the Gray_Images
directory. The monitoring is done using the watchdog
library, and the script runs until manually interrupted.