Certainly! Below is a Python script that accomplishes the following:
- Scans a specified folder for all image files (JPEG, PNG, etc.).
- Extracts the date and location data from each image's metadata (EXIF data).
- Adds a non-destructive text overlay to each image displaying the date and location information.
- Saves the modified images in a separate folder to preserve the originals.
Requirements
Before running the script, ensure you have the following Python packages installed:
Pillow: For image processing.
piexif: For extracting and handling EXIF data.
geopy: For reverse geocoding latitude and longitude to a human-readable location.
You can install these packages using pip:
pip install Pillow piexif geopy
Script Overview
- Scanning the Folder: The script scans a specified directory for images with supported extensions.
- Extracting EXIF Data: For each image, it extracts the original date and GPS information.
- Reverse Geocoding: Converts GPS coordinates to a human-readable address using
geopy.
- Adding Overlay: Overlays the date and location text onto the image without altering the original image.
- Saving the Image: Saves the modified image to an output directory, maintaining the original image format.
The Python Script
import os
from PIL import Image, ImageDraw, ImageFont
import piexif
from geopy.geocoders import Nominatim
from geopy.exc import GeocoderTimedOut
# Configuration
INPUT_FOLDER = 'path/to/input/folder' # Replace with your input folder path
OUTPUT_FOLDER = 'path/to/output/folder' # Replace with your output folder path
FONT_PATH = 'arial.ttf' # Path to a .ttf font file
FONT_SIZE = 36
TEXT_COLOR = (255, 255, 255) # White text
TEXT_BG_COLOR = (0, 0, 0, 128) # Semi-transparent black background
MAX_WIDTH = 800 # Maximum width for images (optional)
# Supported image extensions
SUPPORTED_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.tiff', '.bmp', '.gif')
# Initialize geolocator
geolocator = Nominatim(user_agent="image_metadata_overlay")
def get_exif_data(image_path):
try:
exif_dict = piexif.load(image_path)
return exif_dict
except Exception as e:
print(f"Error reading EXIF data from {image_path}: {e}")
return None
def get_date(exif_dict):
# Try different EXIF tags for date
for tag in ['DateTimeOriginal', 'DateTime', 'DateTimeDigitized']:
date = exif_dict['Exif'].get(piexif.ExifIFD.__dict__.get(tag, None))
if date:
return date.decode('utf-8')
return "Unknown Date"
def get_gps_coords(exif_dict):
gps_info = exif_dict.get('GPS', {})
if not gps_info:
return None
def _convert_to_degrees(value):
d, m, s = value
return d[0]/d[1] + (m[0]/m[1])/60 + (s[0]/s[1])/3600
try:
lat = _convert_to_degrees(gps_info[piexif.GPSIFD.GPSLatitude])
if gps_info.get(piexif.GPSIFD.GPSLatitudeRef, b'N') != b'N':
lat = -lat
lon = _convert_to_degrees(gps_info[piexif.GPSIFD.GPSLongitude])
if gps_info.get(piexif.GPSIFD.GPSLongitudeRef, b'E') != b'E':
lon = -lon
return (lat, lon)
except KeyError as e:
print(f"Missing GPS key: {e}")
return None
except Exception as e:
print(f"Error converting GPS data: {e}")
return None
def reverse_geocode(coords):
try:
location = geolocator.reverse(coords, timeout=10)
if location:
return location.address
else:
return "Unknown Location"
except GeocoderTimedOut:
print("Geocoder service timed out.")
return "Location Unavailable"
except Exception as e:
print(f"Geocoding error: {e}")
return "Location Unavailable"
def add_overlay(image, text, font_path, font_size, text_color, bg_color):
draw = ImageDraw.Draw(image, "RGBA")
try:
font = ImageFont.truetype(font_path, font_size)
except IOError:
print(f"Font not found at {font_path}. Using default font.")
font = ImageFont.load_default()
text_width, text_height = draw.textsize(text, font=font)
padding = 10
x, y = padding, padding
# Draw background rectangle
draw.rectangle(
[x - padding, y - padding, x + text_width + padding, y + text_height + padding],
fill=bg_color
)
# Draw text
draw.text((x, y), text, font=font, fill=text_color)
def process_image(image_path, output_path):
exif_data = get_exif_data(image_path)
if not exif_data:
print(f"No EXIF data for {image_path}. Skipping.")
return
date = get_date(exif_data)
coords = get_gps_coords(exif_data)
location = "Unknown Location"
if coords:
location = reverse_geocode(coords)
text = f"Date: {date}\nLocation: {location}"
try:
with Image.open(image_path) as img:
# Optionally resize image if it's too large
if img.width > MAX_WIDTH:
ratio = MAX_WIDTH / float(img.width)
new_height = int(float(img.height) * ratio)
img = img.resize((MAX_WIDTH, new_height), Image.ANTIALIAS)
add_overlay(img, text, FONT_PATH, FONT_SIZE, TEXT_COLOR, TEXT_BG_COLOR)
# Ensure output directory exists
os.makedirs(os.path.dirname(output_path), exist_ok=True)
img.save(output_path)
print(f"Processed and saved: {output_path}")
except Exception as e:
print(f"Error processing {image_path}: {e}")
def main():
if not os.path.exists(INPUT_FOLDER):
print(f"Input folder '{INPUT_FOLDER}' does not exist.")
return
os.makedirs(OUTPUT_FOLDER, exist_ok=True)
for root, dirs, files in os.walk(INPUT_FOLDER):
for file in files:
if file.lower().endswith(SUPPORTED_EXTENSIONS):
input_path = os.path.join(root, file)
# Maintain directory structure in output folder
relative_path = os.path.relpath(input_path, INPUT_FOLDER)
output_path = os.path.join(OUTPUT_FOLDER, relative_path)
output_dir = os.path.dirname(output_path)
os.makedirs(output_dir, exist_ok=True)
process_image(input_path, output_path)
if __name__ == "__main__":
main()
Detailed Explanation
-
Imports and Configuration:
- Libraries: The script uses
os for file operations, Pillow (PIL) for image processing, piexif for handling EXIF data, and geopy for reverse geocoding.
- Configuration Variables: Define paths for input and output folders, font settings, text colors, and supported image extensions.
-
EXIF Data Extraction:
get_exif_data: Loads EXIF data from an image using piexif.
get_date: Attempts to extract the original capture date from various EXIF tags.
get_gps_coords: Extracts GPS latitude and longitude, converting them to decimal degrees.
-
Reverse Geocoding:
reverse_geocode: Uses geopy's Nominatim service to convert GPS coordinates into a human-readable address. Note that excessive requests may lead to rate limiting; consider implementing caching or delays for large batches.
-
Adding Text Overlay:
add_overlay: Draws semi-transparent background and text onto the image. It uses a TrueType font (.ttf) specified by FONT_PATH. If the font file isn't found, it defaults to a basic font.
- Text Placement: Currently positions the text at the top-left corner with some padding. You can modify the
x and y coordinates for different placements.
-
Processing Images:
process_image: Handles the entire process for each image—extracting metadata, reverse geocoding, adding overlay, and saving the modified image.
- Resizing: Optionally resizes images that exceed
MAX_WIDTH to ensure overlays remain appropriately sized.
-
Main Execution Flow:
main: Iterates through all supported image files in the input directory, maintaining the directory structure in the output folder, and processes each image accordingly.
Notes and Best Practices
- Non-Destructive Editing: The script saves modified images to an output directory, leaving the original images untouched.
- Font File: Ensure that the
FONT_PATH points to a valid .ttf font file on your system. Common fonts like Arial may require specifying the full path or using a different font if unavailable.
- Geocoding Limits: Free geocoding services like Nominatim have usage policies and rate limits. For large numbers of images, consider implementing request throttling or using a paid service.
- Error Handling: The script includes basic error handling to skip images with missing data or processing errors without terminating the entire process.
- Extensibility: You can enhance the script by adding support for more metadata fields, customizing overlay positions, or integrating with other services.
Running the Script
- Set Configuration Variables: Update the
INPUT_FOLDER, OUTPUT_FOLDER, and FONT_PATH variables with appropriate paths on your system.
- Execute the Script: Run the script using Python 3.
python add_overlay.py
Replace add_overlay.py with the filename you've saved the script as.
Example Directory Structure
/path/to/input/folder/
├── image1.jpg
├── image2.png
└── subfolder/
└── image3.tiff
/path/to/output/folder/
├── image1.jpg
├── image2.png
└── subfolder/
└── image3.tiff
Each image in the output folder will have a text overlay with its respective date and location, while the original images remain unaltered in the input folder.
Feel free to customize and enhance the script to better fit your specific needs!