import cv2
from keras_vggface.vggface import VGGFace
from keras_vggface.utils import preprocess_input
from keras_vggface.utils import decode_predictions
import numpy as np
# Load pre-trained VGGFace model
model = VGGFace(model='resnet50', include_top=False, input_shape=(224, 224, 3), pooling='avg')
# Load image
image_path = 'image.jpg'
image = cv2.imread(image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Resize image to match input shape of VGGFace model
resized_image = cv2.resize(image, (224, 224))
# Preprocess input image
resized_image = preprocess_input(resized_image)
# Expand dimensions to match input shape of VGGFace model
input_image = np.expand_dims(resized_image, axis=0)
# Make predictions
predictions = model.predict(input_image)
# Decode predictions
decoded_predictions = decode_predictions(predictions)
# Print top 5 predictions
for i, (class_id, class_name, confidence) in enumerate(decoded_predictions[0][:5]):
print(f'{i + 1}: {class_name} ({confidence * 100:.2f}%)')
This code snippet loads a pre-trained VGGFace model, loads an image file, preprocesses the image, makes predictions using the model, and then prints the top 5 predictions with their corresponding confidence scores.
Note that you will need to install the required libraries (Keras, keras-vggface, and OpenCV) to run this code. Additionally, you may need to fine-tune the algorithm and parameters based on your specific requirements and dataset.