Amazing-Python-Scripts
31 строка · 1001.0 Байт
1import tensorflow as tf2import tensorflow.keras.applications.mobilenet_v2 as mobilenet3from tensorflow.keras.preprocessing import image4from tensorflow.keras.applications.mobilenet_v2 import preprocess_input, decode_predictions5import numpy as np6
7
8def classify_image(image_path):9# Load the pre-trained MobileNetV2 model10model = mobilenet.MobileNetV2(weights='imagenet')11
12# Load and preprocess the image13img = image.load_img(image_path, target_size=(224, 224))14img_array = image.img_to_array(img)15img_array = np.expand_dims(img_array, axis=0)16processed_img = preprocess_input(img_array)17
18# Perform image classification19predictions = model.predict(processed_img)20decoded_predictions = decode_predictions(predictions, top=3)[0]21
22return decoded_predictions23
24
25# Example usage
26image_path = "image.jpg"27predictions = classify_image(image_path)28
29# Print the top 3 predictions
30for prediction in predictions:31print(f"{prediction[1]}: {prediction[2]*100:.2f}%")32