import os
import argparse
import numpy as np
import tensorflow as tf
from tensorflow.keras.applications.mobilenet_v2 import (
MobileNetV2, preprocess_input, decode_predictions
)
from PIL import Image
import csv
def load_model():
"""Load pre-trained MobileNetV2 model with ImageNet weights."""
return MobileNetV2(weights='imagenet')
def classify_image(image_path, model):
"""
Classify a single image and return top 3 predictions.
Args:
image_path (str): Path to the image file.
model: Loaded TensorFlow model.
Returns:
list: List of tuples [(class_id, class_name, probability), ...]
"""
try:
# Load and preprocess image
img = Image.open(image_path).convert('RGB').resize((224, 224))
img_array = np.array(img)
img_array = np.expand_dims(img_array, axis=0)
img_array = preprocess_input(img_array)
# Predict
predictions = model.predict(img_array, verbose=0)
return decode_predictions(predictions, top=3)[0]
except Exception as e:
print(f"Error processing {image_path}: {str(e)}")
return []
def main():
parser = argparse.ArgumentParser(
description="Automate image classification using TensorFlow and MobileNetV2."
)
parser.add_argument(
'input_path',
help='Path to a single image file or directory containing images (supports .jpg, .jpeg, .png)'
)
parser.add_argument(
'--output', '-o',
help='Output CSV file path (optional). If not specified, results are printed to console.'
)
args = parser.parse_args()
# Load model once
print("Loading model...")
model = load_model()
results = []
if os.path.isfile(args.input_path):
# Single image
print(f"Classifying single image: {args.input_path}")
preds = classify_image(args.input_path, model)
results.append({'image': args.input_path, 'predictions': preds})
elif os.path.isdir(args.input_path):
# Directory of images
print(f"Classifying images in directory: {args.input_path}")
supported_extensions = ('.jpg', '.jpeg', '.png', '.JPG', '.JPEG', '.PNG')
image_files = [
f for f in os.listdir(args.input_path)
if any(f.lower().endswith(ext) for ext in supported_extensions)
]
if not image_files:
print("No supported image files found in the directory.")
return
print(f"Found {len(image_files)} images.")
for filename in image_files:
img_path = os.path.join(args.input_path, filename)
preds = classify_image(img_path, model)
results.append({'image': img_path, 'predictions': preds})
else:
print(f"Error: {args.input_path} is not a valid file or directory.")
return
# Output results
if args.output:
with open(args.output, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['image', 'class_1', 'prob_1', 'class_2', 'prob_2', 'class_3', 'prob_3'])
for res in results:
row = [res['image']]
preds = res['predictions']
for i in range(3):
if i < len(preds):
row.extend([preds[i][1], f"{preds[i][2]:.4f}"])
else:
row.extend(['', '0.0000'])
writer.writerow(row)
print(f"Results saved to {args.output}")
else:
# Console output
for res in results:
print(f"\nImage: {res['image']}")
if res['predictions']:
for class_id, class_name, prob in res['predictions']:
print(f" {class_name}: {prob:.2%}")
else:
print(" No predictions available.")
if __name__ == '__main__':
main()