0% found this document useful (0 votes)
11 views2 pages

Ex 07

This document discusses using a pre-trained VGG16 convolutional neural network model to classify images by loading an image, preprocessing it, making predictions with the model, and decoding the predictions to output the top 3 labels.

Uploaded by

Bhargavi Gangula
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views2 pages

Ex 07

This document discusses using a pre-trained VGG16 convolutional neural network model to classify images by loading an image, preprocessing it, making predictions with the model, and decoding the predictions to output the top 3 labels.

Uploaded by

Bhargavi Gangula
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 2

Ex.

No:7 Use a pre-trained convolution neural


network (VGG16) for image classification.
import numpy as np
import tensorflow as tf
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input, decode_predictions
from keras.applications import VGG16

def classify_image_vgg16(image_path):
# Load the VGG16 model pre-trained on ImageNet data
model = VGG16(weights='imagenet', include_top=True)

try:
# Load an image file
img = image.load_img(image_path, target_size=(224, 224))

# Convert the image to a numpy array


x = image.img_to_array(img)

# Add a dimension to the array to match the input shape of the


model
x = np.expand_dims(x, axis=0)

# Preprocess the input data (normalize pixel values and resize)


x = preprocess_input(x)

# Make predictions
predictions = model.predict(x)

# Decode the predictions


decoded_predictions = decode_predictions(predictions, top=3)[0]

# Print the top 3 predictions


for i, (imagenet_id, label, score) in
enumerate(decoded_predictions):
print("{}. {}: {:.2f}%".format(i + 1, label, score * 100))

except FileNotFoundError:
print("Error: Image file not found.")
except Exception as e:
print("An error occurred:", e)

if __name__ == "__main__":
# Replace 'image_path.jpg' with the path to your image file
image_path = 'car.jpg'
classify_image_vgg16(image_path)

You might also like