Image identification using a pre-trained convolutional neural network (CNN) with TensorFlow and Keras

Below is a simple example of image identification using a pre-trained convolutional neural network (CNN) with TensorFlow and Keras. This example uses the MobileNetV2 model, a lightweight model suitable for mobile applications. You’ll need to have TensorFlow installed:

pip install tensorflow

Now, you can use the following Python code:

import tensorflow as tf
from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input, decode_predictions
from tensorflow.keras.preprocessing import image
import numpy as np
import urllib.request

# Load the MobileNetV2 model pre-trained on ImageNet
model = MobileNetV2(weights='imagenet')

# Load an 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))

# 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
img.show()

In this example:

  1. We use MobileNetV2, a pre-trained model available in Keras applications, for image classification.
  2. An image is loaded from a URL and preprocessed to match the input requirements of the model.
  3. The model makes predictions, and the top-3 predicted classes are printed.

Make sure to replace the image_url variable with the actual URL of the image you want to identify. Additionally, note that MobileNetV2 and similar models are trained on a wide range of classes from the ImageNet dataset, so the predictions will be based on those classes.

You can explore more advanced models and customize the code based on your specific use case and requirements.

Leave a Reply

Your email address will not be published. Required fields are marked *