Organizing Photos with Python: A Year in Review

Ah, it’s that time of year again for a big cleanup! Opening my phone’s photo album, oh my, did I really take this many photos in a year? Looking at my nearly full storage space, I suddenly had a brilliant idea: why not let Python help me organize these precious memories?

Photo Classification Challenge

We need to categorize the photos by date. It sounds simple, but doing it manually? No way! Let’s see how Python can help us take a shortcut:

import os
from datetime import datetime
from PIL import Image
import shutil

def organize_photos(source_folder, destination_folder):
    for filename in os.listdir(source_folder):
        if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
            file_path = os.path.join(source_folder, filename)
            try:
                with Image.open(file_path) as img:
                    date_taken = img._getexif()[36867]
                    date_obj = datetime.strptime(date_taken, '%Y:%m:%d %H:%M:%S')
                    year_month = date_obj.strftime('%Y-%m')
                    
                    new_folder = os.path.join(destination_folder, year_month)
                    if not os.path.exists(new_folder):
                        os.makedirs(new_folder)
                    
                    shutil.copy2(file_path, new_folder)
                    print(f"Copied {filename} to {year_month} folder")
            except:
                print(f"Cannot process {filename}")

organize_photos('/path/to/source', '/path/to/destination')

With just a few lines of code, my photos are neatly lined up and archived by year and month! No more worrying about where last year’s family photo from Spring Festival is.

Friendly reminder: Don’t forget to replace ‘/path/to/source’ and ‘/path/to/destination’ with your own folder paths! Otherwise, Python will be confused and won’t know where to organize the photos.

Memory Generator

After organizing the photos, I suddenly thought: wouldn’t it be cool to automatically generate a little video to review the highlights of the year? Let’s do it:

import cv2
import os
import random

def create_slideshow(photo_folder, output_video):
    photos = [img for img in os.listdir(photo_folder) if img.endswith(('.jpg', '.png'))]
    random.shuffle(photos)  # Randomly shuffle for fun
    
    frame = cv2.imread(os.path.join(photo_folder, photos[0]))
    height, width, layers = frame.shape

    video = cv2.VideoWriter(output_video, cv2.VideoWriter_fourcc(*'mp4v'), 1, (width, height))

    for photo in photos:
        img = cv2.imread(os.path.join(photo_folder, photo))
        resized_img = cv2.resize(img, (width, height))
        video.write(resized_img)
        for _ in range(2):  # Each photo stays for 2 seconds
            video.write(resized_img)

    cv2.destroyAllWindows()
    video.release()

create_slideshow('/path/to/photos', 'my_year_in_review.mp4')

This piece of code is like a magician! It randomly selects photos and creates a surprise-filled memory video. There might be unexpected combinations, like a summer beach photo followed by a winter snowman, but isn’t that the charm of life?

Photo Deduplication Magic

Wait, I think I see some duplicate photos? No worries, Python comes to the rescue again:

import os
import hashlib

def find_duplicates(folder):
    hash_dict = {}
    for filename in os.listdir(folder):
        if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
            filepath = os.path.join(folder, filename)
            with open(filepath, 'rb') as f:
                file_hash = hashlib.md5(f.read()).hexdigest()
            if file_hash in hash_dict:
                print(f"Found duplicate: {filename} and {hash_dict[file_hash]}")
            else:
                hash_dict[file_hash] = filename

find_duplicates('/path/to/photos')

This little program calculates the MD5 value of each photo, and if it finds duplicates, it will let you know. But be careful, sometimes photos taken in quick succession might look the same but are actually different beautiful moments!

Looking at the organized photos, I can’t help but marvel: who says programmers only know how to type code? We can also use Python to capture every wonderful moment in life. These little code snippets not only helped me organize my photos but also allowed me to relive those beautiful times. Maybe next year at this time, I’ll write an AI to help me pick the best annual photos? Hmm, sounds like a good idea!

Leave a Comment