Streamline Your Photo Library with AI-Driven Automated Image Naming
Imagine you’ve just returned from a trip with hundreds of photos, but all your images have generic names like IMG_001.jpg
or worse — duplicates with no way to tell them apart. Searching for that perfect sunset or your new puppy becomes a time-consuming hunt. What if artificial intelligence could do the heavy lifting and rename your photos for you, based on what’s actually inside each image?
This article introduces a Python script that leverages EfficientNetB7, a powerful deep learning model, to analyze and rename your images automatically. Whether you’re a photographer, a developer, or a tech-savvy hobbyist, this tool can streamline your workflow, save you hours, and bring order to your photo chaos.
Who Is This For?
This guide is tailored for users comfortable with basic Python scripting and command-line usage. Familiarity with installing Python packages (like TensorFlow) is helpful, but no deep machine learning knowledge is required. If you want a practical, hands-on AI project that delivers real-world benefits, you’re in the right place.
What Does the Script Do?
- Scans a specified folder for common image formats (
.jpg
,.jpeg
,.png
). - Uses EfficientNetB7 — a state-of-the-art image classification model pretrained on ImageNet — to identify the main object or subject in each photo.
- Renames the image file based on the predicted label, keeping filenames concise by limiting the number of words.
- Ensures new filenames don’t overwrite existing files by appending numeric suffixes when necessary.
- Skips files that aren’t images or can’t be processed, preventing errors.
Why EfficientNetB7? Are There Alternatives?
EfficientNetB7 provides some of the best accuracy available for image classification in TensorFlow. This means the labels it predicts are more likely to be correct and meaningful, leading to better filenames.
However, it’s a large model — expect longer processing times and higher memory use. If you want faster results and can accept slightly less accuracy, the script also includes MobileNetV2 as a fallback option. Choose based on your hardware and project needs.
What You’ll Need Before Running the Script
- Python 3.7+ installed on your machine.
- TensorFlow and NumPy libraries installed (
pip install tensorflow numpy
). - A folder containing your images ready for renaming.
- A machine with enough memory to load EfficientNetB7 (preferably with GPU support for faster inference, but CPU works too).
Step-By-Step: Running the Script
- Install dependencies:
pip install tensorflow numpy
- Prepare your images in a folder.
- Run the script: It will prompt you to enter the folder path and the maximum number of words for the filename. The script then processes each image and renames it.
- Check your folder: You’ll find your images renamed to descriptive, AI-generated names like
golden-retriever.png
orsports-car-2.jpg
.
Handling Limitations and Customizations
- The script currently supports only
.jpg
,.jpeg
, and.png
files but can be extended to other formats. - If the model’s prediction doesn’t match your expectations, you can customize the script to manually edit labels or integrate different models.
- For very large image collections, consider batching or running the script during idle times due to model size and inference time.
- The script operates offline — your images stay on your machine, ensuring privacy.
A Real-World Use Case
Meet Sarah, an avid dog photographer with thousands of pictures from various shoots. Before using this script, she spent hours renaming files to reflect the breed or location. Now, she runs the AI renamer, and her images are automatically named golden-retriever.jpg
, border-collie-2.jpg
, and park-scene.jpg
, making it effortless to find the right photo when needed.
Code Highlights
The script’s key components are:
- Image filtering: Detects valid image files.
- Preprocessing: Resizes and formats images for the model.
- Labeling: Extracts and limits the predicted label length.
- Renaming: Ensures new filenames are unique.
Full Python Script
import os
import tensorflow as tf
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.applications import EfficientNetB7
from tensorflow.keras.applications.efficientnet import (
preprocess_input,
decode_predictions,
)
from tensorflow.keras.preprocessing import image
import numpy as np
def is_image_file(filename):
ext = os.path.splitext(filename)[1].lower()
return ext in [".jpg", ".jpeg", ".png"]
def preprocess_img(img_path, target_size=(600, 600)):
img = image.load_img(img_path, target_size=target_size)
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
return x
def get_limited_label(label, max_words):
label = label.replace("_", "-")
words = label.split("-")
limited = "-".join(words[:max_words])
return limited
def get_unique_filename(folder, base, ext):
candidate = f"{base}{ext}"
i = 1
while os.path.exists(os.path.join(folder, candidate)):
candidate = f"{base}-{i}{ext}"
i += 1
return candidate
def main(folder, max_words):
if not os.path.isdir(folder):
print(f"Error: '{folder}' is not a valid directory.")
return
# Simpler model with lesser label accuracy (fallback)
# model = MobileNetV2(weights="imagenet")
# Using EfficientNetB7 for improved accuracy
model = EfficientNetB7(weights="imagenet")
for fname in os.listdir(folder):
if not is_image_file(fname):
continue
old_path = os.path.join(folder, fname)
try:
img_array = preprocess_img(old_path)
preds = model.predict(img_array)
decoded = decode_predictions(preds, top=1)[0][0]
label = decoded[1]
limited_label = get_limited_label(label, max_words)
ext = os.path.splitext(fname)[1].lower()
new_fname = get_unique_filename(folder, limited_label, ext)
new_path = os.path.join(folder, new_fname)
os.rename(old_path, new_path)
print(f"{fname} -> {new_fname}")
except Exception as e:
print(f"Skipping '{fname}': {e}")
if __name__ == "__main__":
folder = input("Enter the path to the image folder: ").strip()
try:
max_words = int(input("Enter the maximum number of words for the new filename: ").strip())
except ValueError:
print("Invalid number for max_words. Using default value 2.")
max_words = 3
main(folder, max_words)
Project Repository
You can find the full source code and related files on GitHub:
GitHub - AI-Powered Image Renamer
Final Thoughts
This project demonstrates how AI can make everyday digital tasks smarter and easier. With just a few lines of Python and a pretrained model, you can bring intelligent organization to your photo library — no manual renaming necessary.
Try the script yourself and see how effortless managing images can become.
If you want help customizing the script, extending it to other file types, or integrating it into larger workflows, just ask!