import tensorflow as tf
from tensorflow.keras.applications import VGG16
from tensorflow.keras.preprocessing.image import load_img,
img_to_array
from tensorflow.keras.applications.vgg16 import preprocess_input,
decode_predictions
import numpy as np
import matplotlib.pyplot as plt
model = VGG16(weights='imagenet')
Downloading data from https://storage.googleapis.com/tensorflow/keras-
applications/vgg16/vgg16_weights_tf_dim_ordering_tf_kernels.h5
553467096/553467096 ━━━━━━━━━━━━━━━━━━━━ 842s 2us/step
# Function to load and preprocess an image
def load_and_preprocess_image(image_path, target_size=(224, 224)):
img = load_img(image_path, target_size=target_size) # Load the image
img_array = img_to_array(img) # Convert to array
img_array = np.expand_dims(img_array, axis=0) # Expand dimensions to
match
img_array = preprocess_input(img_array) # Preprocess the image
return img_array, img
def predict_image(model, img_array):
predictions = model.predict(img_array) # Get predictions
decoded_predictions = decode_predictions(predictions, top=3)[0] #
Decode t
return decoded_predictions
image_path = r'C:\Users\nagal\OneDrive\Desktop\cat.jpg' # Corrected
file path
img_array, img = load_and_preprocess_image(image_path)
predictions = predict_image(model, img_array)
# Display the input image
plt.imshow(img)
plt.title("Input Image")
plt.axis('off')
plt.show()
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 260ms/step
Downloading data from
https://storage.googleapis.com/download.tensorflow.org/data/imagenet_c
lass_index.json
35363/35363 ━━━━━━━━━━━━━━━━━━━━ 1s 14us/step
for pred in predictions:
print(f"Predicted: {pred[1]} with a probability of {pred[2]*100:.2f}
%")
Predicted: Egyptian_cat with a probability of 49.79%
Predicted: tabby with a probability of 38.66%
Predicted: tiger_cat with a probability of 8.95%