0

I've build an image classification model that classifies images as one of three classes: cucumber, zucchini, or neither.

Now I want to deploy this model to a Django website but I am currently experiencing some problems. When I run the python manage.py runserver command I get the following printed in the terminal:

Watching for file changes with StatReloader
Performing system checks...

2024-07-10 01:26:11.875397: I tensorflow/core/util/port.cc:113] oneDNN custom operations are 
on. You may see slightly different numerical results due to floating-point round-off errors 
from different computation orders. To turn them off, set the environment variable 
`TF_ENABLE_ONEDNN_OPTS=0`.
2024-07-10 01:26:12.947630: I tensorflow/core/util/port.cc:113] oneDNN custom operations are 
on. You may see slightly different numerical results due to floating-point round-off errors 
from different computation orders. To turn them off, set the environment variable 
`TF_ENABLE_ONEDNN_OPTS=0`.
C:\path\to\virtual\environment\virtual_environment_name\Lib\site-
packages\keras\src\layers\preprocessing\tf_data_layer.py:19: UserWarning: Do not pass an 
`input_shape`/`input_dim` argument to a layer. When using Sequential models, prefer using an 
`Input(shape)` object as the first layer in the model instead.
super().__init__(**kwargs)
2024-07-10 01:26:14.748468: I tensorflow/core/platform/cpu_feature_guard.cc:210] This 
TensorFlow binary is optimized to use available CPU instructions in performance-critical 
operations.
To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with 
the appropriate compiler flags.

Now, to me this does not appear to be error messages, but the local hosting of the website is not up so something does seem to be wrong.

The views.py file where I try to load the model looks like this:

from django.shortcuts import render
from django.conf import settings
from .forms import ImageUploadForm
import tensorflow as tf
from tensorflow.keras.preprocessing import image as keras_image
import numpy as np
import os

# Create your views here.

# cucumber_zucchini_classifier/views.py

# Load the trained model
model_path = 'C:\path\to\model_directory\image_classifier_model.h5'

# Load the trained model
model = tf.keras.models.load_model(model_path)

# Define the labels
LABELS = ['cucumber', 'zucchini', 'neither']

def preprocess_image(img):
    img = keras_image.img_to_array(img)
    img = np.expand_dims(img, axis=0)
    img = img / 255.0  # Normalize the image
    return img

def classify_image(img):
    img = preprocess_image(img)
    predictions = model.predict(img)
    predicted_class = LABELS[np.argmax(predictions)]
    return predicted_class

def image_upload_view(request):
    classification = None
    if request.method == 'POST':
        form = ImageUploadForm(request.POST, request.FILES)
        if form.is_valid():
            img = form.cleaned_data['image']
            img = keras_image.load_img(img, target_size=(180, 180))  # Resize to the input size of model
            classification = classify_image(img)
    else:
        form = ImageUploadForm()
    return render(request, 'cucumber_zucchini_classifier/upload.html', {'form': form, 'classification': classification})

There are (at least) two things that I don't understand and don't know if could be related to this. These are:

  1. if I provide the exact file path for the model in the model_path variable, I get the situation is as described above, but if, however, I only provide the model name, i.e.:

    model_path = 'image_classifier_model.h5'

I get an error telling me that there is no such file or directory:

FileNotFoundError: [Errno 2] Unable to synchronously open file (unable
to open file: name = 'image_classifier_model.h5', errno = 2, error
message = 'No such file or directory', flags = 0, o_flags = 0)

And that is even though the model file is in the same directory as the views.py file.

  1. There seem to be an issue with the import from tensorflow.keras.preprocessing (line 5 in the views.py file however there is no issue with the import of tensorflow (line 4 in the views.py file): highlighting import issue with tensorflow.keras.preprocessing

For context, when I load the model in a jupyter notebook it works fine and I can use it to classify images as expected:

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.preprocessing import image
from tensorflow.keras.preprocessing import image

# Load the saved model
loaded_model = tf.keras.models.load_model('image_classifier_model.h5')


# Function to preprocess the image
def preprocess_image(img_path, img_height, img_width):
    img = image.load_img(img_path, target_size=(img_height, img_width))
    img_array = image.img_to_array(img)
    img_array = np.expand_dims(img_array, axis=0)  # Create batch axis
    #img_array = img_array / 255.0  # Normalize the image to [0, 1] range
    return img_array

def preprocess_image(img_path, img_height, img_width):
    # Load the image from the file path
    img = image.load_img(img_path, target_size=(img_height, img_width))

    # Convert the image to a NumPy array
    img_array = image.img_to_array(img)

    # Expand the dimensions to match the input shape for the model (batch_size, height, width, channels)
    img_array = np.expand_dims(img_array, axis=0)

    return img_array

def predict_and_display(images_paths, model, img_height, img_width, class_names):
    fig, axes = plt.subplots(3, 3, figsize=(12, 12))

    for i, img_path in enumerate(images_paths):
        img_array = preprocess_image(img_path, img_height, img_width)
        predictions = model.predict(img_array)
        predicted_class = np.argmax(predictions, axis=1)[0]
        predicted_class_name = class_names[predicted_class]
    
        img = image.load_img(img_path, target_size=(img_height, img_width))
    
        ax = axes[i//3, i%3]
        ax.imshow(img)
        ax.set_title(f'Predicted: {predicted_class_name}')
        ax.axis('off')

    plt.tight_layout()
    plt.show()

# Examples
img_paths = [
    r'path\to\image1.jpg',
    r'path\to\image2.jpg',
    r'path\to\image3.PNG',
    r'path\to\image4.png',
    r'path\to\image5.jpg',
    r'path\to\image6.png',
    r'path\to\image7.jpg',
    r'path\to\image8.jpg',
    r'path\to\image9.jpg'
]

img_height = 180
img_width = 180
class_names = ['cucumber', 'zucchini', 'neither']

predict_and_display(img_paths, final_model, img_height, img_width, class_names)

Running this, gives me the following (with the test images I used of course) so in this environment there seem to be no problems:

outpu of running the shown code in a jupyter notebook

Does anyone know why the I get stuck after this series of messages and the website is never launched (locally) when I run the python manage.py runserver command?

Any help is appreciated. Thanks :)

0

Browse other questions tagged or ask your own question.