import cv2
import numpy as np
from tensorflow.keras.applications.mobilenet import MobileNet, preprocess_input, decode_predictions
# Load pre-trained MobileNet model
model = MobileNet(weights='imagenet')
# Create video capture object
cap = cv2.VideoCapture(0)
while True:
# Read frames from webcam
ret, frame = cap.read()
# Resize frame to (224, 224) for MobileNet model
resized_frame = cv2.resize(frame, (224, 224))
# Preprocess input frame for MobileNet model
preprocessed_frame = preprocess_input(np.expand_dims(resized_frame, axis=0))
# Make predictions using MobileNet model
predictions = model.predict(preprocessed_frame)
# Get top 3 predictions
top_predictions = decode_predictions(predictions, top=3)[0]
# Display labels and probabilities on the frame
for i, (label, description, probability) in enumerate(top_predictions):
text = f"{label}: {probability*100:.2f}%"
cv2.putText(frame, text, (10, (i+1)*30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
# Display the frame
cv2.imshow('Webcam', frame)
# Break the loop if 'q' is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release video capture object and close windows
cap.release()
cv2.destroyAllWindows()
Make sure you have the necessary dependencies installed (OpenCV, TensorFlow, and Keras) before running this code.