Yesterday, I dug out a pile of old photos, full of memories! But with so many photos, sorting them one by one would be exhausting. Suddenly, I had a bright idea: why not let Python be my helper? Since it can help me process data at work, why can’t it help me organize photos?
Automating Photo Organization for Orderly Memories
We need to make Python able to “understand” the photos. Here we will use the PIL library (Python Imaging Library). It acts like Python’s eyes, helping us read and process images.
from PIL import Image
import os
from datetime import datetime
def get_photo_date(file_path):
try:
img = Image.open(file_path)
exif_data = img._getexif()
if exif_data:
date_taken = exif_data.get(36867) # EXIF tag for date taken
if date_taken:
return datetime.strptime(date_taken, "%Y:%m:%d %H:%M:%S")
except Exception as e:
print(f"Unable to get date taken for {file_path}: {e}")
return None
This piece of code is like a health check for the photos, checking if we can find the date taken from them. If we can’t find it, we will think of another way later.
Next, we need to give the photos a new home:
def organize_photos(source_folder, destination_folder):
for filename in os.listdir(source_folder):
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
file_path = os.path.join(source_folder, filename)
date_taken = get_photo_date(file_path)
if date_taken:
year_folder = os.path.join(destination_folder, str(date_taken.year))
month_folder = os.path.join(year_folder, f"{date_taken.month:02d}")
os.makedirs(month_folder, exist_ok=True)
new_path = os.path.join(month_folder, filename)
os.rename(file_path, new_path)
else:
print(f"Unable to determine date taken for {filename}, skipping processing")
source_folder = "C:/Users/YourName/Pictures/OldPhotos"
destination_folder = "C:/Users/YourName/Pictures/OrganizedPhotos"
organize_photos(source_folder, destination_folder)
This piece of code is like a diligent little elf, sorting the photos by year and month and placing them in the corresponding folders. Those without a date taken will just be left aside for now.
Friendly reminder: Before running this code, remember to back up your photos! In case something goes wrong, we can still recover them.
Identifying Blurry Photos to Say Goodbye to “Blurriness”
After organizing the photos, I suddenly noticed that some of them were blurry, which is unacceptable! So, I wrote another piece of code to identify these “blurry ones”:
import cv2
import numpy as np
def is_blurry(image_path, threshold=100):
image = cv2.imread(image_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
laplacian_var = cv2.Laplacian(gray, cv2.CV_64F).var()
return laplacian_var < threshold
def find_blurry_photos(folder_path):
blurry_photos = []
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.lower().endswith(('.png', '.jpg', '.jpeg')):
file_path = os.path.join(root, file)
if is_blurry(file_path):
blurry_photos.append(file_path)
return blurry_photos
blurry_ones = find_blurry_photos(destination_folder)
print(f"Found {len(blurry_ones)} blurry photos")
This piece of code acts like a strict photography judge, picking out the blurry photos. However, sometimes blurry photos can be more expressive, like those full of motion. So in the end, it still relies on our own eyes to decide whether to keep them.
Labeling Photos for Clearer Memories
After organizing the photos, I thought of another idea: labeling the photos! This way, it will be much easier to find them later. I used Google Vision API to help identify the content of the photos:
from google.cloud import vision
import io
def label_image(file_path):
client = vision.ImageAnnotatorClient()
with io.open(file_path, 'rb') as image_file:
content = image_file.read()
image = vision.Image(content=content)
response = client.label_detection(image=image)
labels = response.label_annotations
return [label.description for label in labels]
# Example usage
file_path = "path/to/your/photo.jpg"
labels = label_image(file_path)
print(f"This photo may contain: {' , '.join(labels)}")
This piece of code acts like a super image recognizer, telling you what is in the photo. However, to use this feature, you need to register an account with Google Cloud and set up the API key. It may be a bit troublesome, but the effect is really great!
I integrated all these functions into a simple interface program. Now I just need to click a few times to easily organize all the photos and quickly find the one I want. This not only saves me a lot of time but also helps me rediscover those precious memories forgotten in the corners of my hard drive.
Looking at these photos from my younger days, I can’t help but sigh: time flies, but at least we still have photos. And Python, like a caring housekeeper, helps us keep these precious memories safe. Perhaps one day you will also need such a little helper, and when that time comes, don’t forget about Python!