Diff of /xc.py [000000] .. [b018ba]

Switch to unified view

a b/xc.py
1
# c.py
2
from tensorflow import keras
3
from keras.models import load_model
4
from keras.preprocessing.image import load_img, img_to_array
5
import numpy as np
6
7
def predict_image(file_path):
8
    try:
9
        # Load the pre-trained model
10
        model_path = r'model\CNN_model.h5'
11
        print(f"Loading model from: {model_path}")
12
        loaded_model = load_model(model_path)  # Load the model
13
        print("Model loaded successfully!")
14
15
        # Preprocess the image
16
        img = load_img(file_path, target_size=(224, 224))  # Resize to target size
17
        img_array = img_to_array(img)  # Convert to numpy array
18
        img_array = np.expand_dims(img_array, axis=0)  # Add batch dimension
19
        img_array = img_array / 255.0  # Normalize pixel values
20
21
        # Debugging: Check the shape and content of the image array
22
        print(f"Image shape after preprocessing: {img_array.shape}")
23
24
        # Predict the class
25
        predictions = loaded_model.predict(img_array)
26
        print(f"Raw predictions: {predictions}")
27
28
        # Get the predicted class
29
        predicted_class = np.argmax(predictions, axis=1)[0]
30
        print(f"Predicted class: {predicted_class}")
31
32
        return predicted_class  # Return only the predicted class
33
    except Exception as e:
34
        print(f"Error processing image or predicting: {e}")
35
        return None