This code snippet loads an image, applies preprocessing and prediction using a machine learning model, and then extracts and prints the predicted label. The code utilizes various functions, including ef
for image transformation and a model's predict
method for making predictions.
image = 'images/train/sad/42.jpg'
print("original image is of sad")
img = ef(image)
pred = model.predict(img)
pred_label = label[pred.argmax()]
print("model prediction is ",pred_label)
import os
import cv2
import numpy as np
from tensorflow import keras
def load_image(image_path):
"""
Load an image from the given path.
Args:
image_path (str): Path to the image file.
Returns:
np.ndarray: Loaded image.
"""
img = cv2.imread(image_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Convert to RGB
return img
def preprocess_image(image):
"""
Pre-process the image by resizing it.
Args:
image (np.ndarray): Input image.
Returns:
np.ndarray: Pre-processed image.
"""
image = cv2.resize(image, (224, 224)) # Resize to 224x224
image = image / 255.0 # Normalize pixel values
return image
## Main Function
def classify_image(image_path, model, label):
"""
Classify an image using the given model.
Args:
image_path (str): Path to the image file.
model: Image classification model.
label (list): List of labels.
Returns:
str: Predicted label.
"""
image = load_image(image_path)
image = preprocess_image(image)
image = np.expand_dims(image, axis=0) # Add batch dimension
pred = model.predict(image)
pred_label = label[pred.argmax()]
return pred_label
# Example usage
image_path = 'images/train/sad/42.jpg'
model = keras.models.load_model('path_to_your_model.h5') # Load the model
label = ['happy','sad', 'angry'] # List of labels
pred_label = classify_image(image_path, model, label)
print("original image is of", pred_label)
No imports are shown in the code snippet.
image = 'images/train/sad/42.jpg'
Loads an image located at the specified path into a variable named image
.
print("original image is of sad")
Prints a message to the console indicating the expected label of the original image.
img = ef(image)
Applies some form of image transformation or feature extraction to the loaded image using a function named ef
. The result is stored in the img
variable.
pred = model.predict(img)
Uses a machine learning model to make predictions on the preprocessed image. The result is stored in the pred
variable.
pred_label = label[pred.argmax()]
Extracts the label corresponding to the index of the maximum prediction value from a list of labels label
. The result is stored in the pred_label
variable.
print("model prediction is ", pred_label)
Prints the predicted label to the console.