Django is a python web framework that has a big popularity on the python community due to its large amount of functionality that comes with it.This lets you rapidly develop your application.
For Image classification we will use the VGG-16 pre-trained model with ImageNet weights
Requirements:
Keras
django
Creating a project:
To start with the django project, we have to do some initial setups. Django gives some command line tools that help you start your project. Go to your preferred directory where you want to create your project. Open the terminal,for Linux users and cmd for the windows users and type following command
django-admin startproject classify
This command will create a “classify” repository which contains the following files
These files are:
The outer classify/ root directory is a container for your project. Its name doesn’t matter to Django; you can rename it to anything you like.
manage.py: A command-line utility that lets you interact with this Django project in various ways.
The inner classify/ directory is the actual Python package for your project. Its name is the Python package name you’ll need to use to import anything inside it (e.g. classify.urls).
See AlsoReinstalling and patching your Quicken Subscription version after your membership has expired (Quicken for Mac)Quicken Subscription Membership FAQsReinstalling and patching your Quicken Subscription version after your membership has expiredQuicken Review (2023): Features, Pricing & Moreclassify/__init__.py: An empty file that tells Python that this directory should be considered a Python package. If you’re a Python beginner, read more about packages in the official Python docs.
classify/settings.py: Settings/configuration for this Django project. Django settings will tell you all about how settings work.
classify/urls.py: The URL declarations for this Django project; a “table of contents” of your Django-powered site.
classify/asgi.py: An entry-point for ASGI-compatible web servers to serve your project.
classify/wsgi.py: An entry-point for WSGI-compatible web servers to serve your project.
Let Coding begin… Firstly, let’s load our model.
Open the settings.py file from the classify project and insert the code below.
import keras
import numpy as np
from keras import backend as K
import tensorflow as tf
from tensorflow.python.keras.backend import set_session
from keras.applications import vgg16def get_session():
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
return tf.Session(config=config)
K.tensorflow_backend.set_session(get_session())
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
SESS = tf.Session(config=config)
print("model loading")
GRAPH1 = tf.get_default_graph()
set_session(SESS)
# Load the VGG model
VGG_MODEL = vgg16.VGG16(weights="imagenet")
This code will load your model when you run your project so that every time you have to predict you don’t have to load models. Remember that in this code we will use the VGG-16 model, SESS , GRAPH1 variable in views.py file soon.
Insert the code below at the end of your settings.py file
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = 'media/'
This code will create a media file where the uploaded picture will be saved.
Now let’s create a views.py file inside inner classify directory for accessing the model to classify the image. This is how your folder structure should look like at this point.
Let’s edit views.py file. Insert the following code
from django.shortcuts import render
from django.http import JsonResponse
import base64
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.conf import settings
from tensorflow.python.keras.backend import set_session
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.applications.imagenet_utils import decode_predictions
import matplotlib.pyplot as plt
import numpy as np
from keras.applications import vgg16
import datetime
import tracebackdef index(request):
if request.method == "POST":
f=request.FILES['sentFile'] # here you get the files needed
response = {}
file_name = "pic.jpg"
file_name_2 = default_storage.save(file_name, f)
file_url = default_storage.url(file_name_2)
original = load_img(file_url, target_size=(224, 224))
numpy_image = img_to_array(original)
image_batch = np.expand_dims(numpy_image, axis=0)
# prepare the image for the VGG model
processed_image = vgg16.preprocess_input(image_batch.copy())
# get the predicted probabilities for each class
with settings.GRAPH1.as_default():
set_session(settings.SESS)
predictions=settings.VGG_MODEL.predict(processed_image)
label = decode_predictions(predictions)
label = list(label)[0]
response['name'] = str(label)
return render(request,'homepage.html',response)
else:
return render(request,'homepage.html')
Here, the index function helps classify the image and send the prediction to the homepage.html file. The if block validates that a picture has been uploaded and gives a prediction otherwise a simple form is displayed.
Lastly, let’s create the homepage.html in the templates directory. Create a templates directory at the same level of manage.py file.
Let’s make a form into the homepage.html file to get image from the user.
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="sentFile" />
<input type="submit" name="submit" value="Upload" />
</form>
{{name}}
Here, the form helps us get an image from the user where {{name}} is the rendered prediction sent by views.py file.
For routing all this we have to change is the urls.py file to following.
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='homepage'),
path('admin/', admin.site.urls),
]
That’s it.
Now let’s check that you have done all things right or not by running the following command in the terminal or cmd.
python manage.py runserver
You should get the following response.
Starting development server at http://127.0.0.1:8000/Quit the server with CTRL-BREAK.
Open your browser and paste the URL http://127.0.0.1:8000/ then click on the choose file button to upload an image to see the results displayed on the same page in few a seconds.
Results
If you like this post, HIT Buy me a coffee! Thanks for reading.😊
Your every small contribution will encourage me to create more content like this.