Simple Python program that uses TensorFlow and Keras to load the MobileNetV2 model pre-trained on the ImageNet dataset and makes predictions on an example image.
import tensorflow as tf
from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2, preprocess_input, decode_predictions
from tensorflow.keras.preprocessing import image
import numpy as np
import urllib.request
import matplotlib.pyplot as plt
# Load the MobileNetV2 model pre-trained on ImageNet
model = MobileNetV2(weights='imagenet')
# Load an example image from a URL
image_url = "https://example.com/your_image.jpg"
image_path, headers = urllib.request.urlretrieve(image_url)
img = image.load_img(image_path, target_size=(224, 224))
# Display the original image
plt.imshow(img)
plt.title("Original Image")
plt.show()
# Preprocess the image
img_array = image.img_to_array(img)
img_array = np.expand_dims(img_array, axis=0)
img_array = preprocess_input(img_array)
# Make predictions
predictions = model.predict(img_array)
# Decode and print the top-3 predicted classes
decoded_predictions = decode_predictions(predictions, top=3)[0]
print("Predictions:")
for i, (imagenet_id, label, score) in enumerate(decoded_predictions):
print(f"{i + 1}: {label} ({score:.2f})")
# Display the image with predictions
plt.imshow(img)
plt.title(f"Predictions: {decoded_predictions[0][1]}, {decoded_predictions[1][1]}, {decoded_predictions[2][1]}")
plt.show()
In this example:
- We use MobileNetV2, a lightweight convolutional neural network architecture.
- An example image is loaded from a URL using
urllib.request.urlretrieve
. - The image is preprocessed to match the input requirements of the model.
- Predictions are made using the MobileNetV2 model, and the top-3 predicted classes are printed.
- The original image and the image with predictions are displayed using Matplotlib.
Make sure to replace the image_url
variable with the actual URL of the image you want to use for predictions. Additionally, note that MobileNetV2 and similar models are trained on a wide range of classes from the ImageNet dataset.