Image classification with django (deployment) (2024)

Image classification with django (deployment) (1)

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

Image classification with django (deployment) (2)

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).

classify/__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 vgg16

def 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.

Image classification with django (deployment) (3)

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 traceback

def 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.

Image classification with django (deployment) (4)

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

Image classification with django (deployment) (5)

Image classification with django (deployment) (6)

Image classification with django (deployment) (7)

If you like this post, HIT Buy me a coffee! Thanks for reading.😊

Image classification with django (deployment) (8)

Your every small contribution will encourage me to create more content like this.

Image classification with django (deployment) (2024)

FAQs

Can I use TensorFlow with Django? ›

Both of them are possible. We have written the TensorFlow application in Python and export the checkpoint locally. Then start the Django web server to restore the checkpoint and do continuously training or inferencing.

How do you deploy an image to a classification model? ›

Train and deploy on-device image classification model with AutoML Vision in ML Kit
  1. On this page.
  2. Setup.
  3. Download the code and training dataset.
  4. Create Firebase console Project.
  5. Setup the Android app.
  6. Setup the iOS app.
  7. Prepare training dataset.
  8. Explore the dataset.
16 Nov 2021

Which is best for image classification? ›

Pattern recognition and image clustering are two of the most common image classification methods used here. Two popular algorithms used for unsupervised image classification are 'K-mean' and 'ISODATA. ' K-means is an unsupervised classification algorithm that groups objects into k groups based on their characteristics.

Is it worth learning Django in 2022? ›

Yes, it is. it is the most used framework for web development in python, those who develop websites in python either learn django or flask but most of them learn django because its advance.

Can I use Django as a Microservice? ›

However, Django is completely capable of being all microservicy. I usually use Django for microservice stuff because as the project evolves its easier to expand it into a more capable service if needed.

Is decision tree good for image classification? ›

One way to perform image classification is by using decision tree-based algorithms. Decision tree-based algorithms are an important part of the classification methodology. Their main advantage is that there is no assumption about data distribution, and they are usually very fast to compute [11].

Is SVM good for image classification? ›

SVM is a very good algorithm for doing classification. It's a supervised learning algorithm that is mainly used to classify data into different classes. SVM trains on a set of label data.

Is CNN the best for image classification? ›

CNN's are really effective for image classification as the concept of dimensionality reduction suits the huge number of parameters in an image. This write-up barely scratched the surface of CNNs here but provides a basic intuition on the above-stated fact.

Is Django good for machine learning? ›

Django also has a proper folder structure and many libraries, making it unsuitable for small and simple machine learning models. So, Flask is sufficient for almost all the machine learning models.

Which one is better Django or flask? ›

Flask is considered more “Pythonic” than Django is basically since Flask web application code is, in most cases, more unequivocal. Flask is the choice of most tenderfoots due to the need of barricades to getting a basic app up and running.

What is the best way to deploy a Django app to production? ›

You can use Visual Studio Code or your favorite text editor.
  1. Step 1: Creating a Python Virtual Environment for your Project. ...
  2. Step 2: Creating the Django Project. ...
  3. Step 3: Pushing the Site to GitHub. ...
  4. Step 4: Deploying to DigitalOcean with App Platform. ...
  5. Step 5: Deploying Your Static Files.
29 Sept 2021

Why is image classification difficult? ›

The main challenges in image classification are the large number of images, the high dimensionality of the data, and the lack of labeled data. Images can be very large, containing a large number of pixels. The data in each image may be high-dimensional, with many different features.

How many images are enough for image classification? ›

Usually around 100 images are sufficient to train a class. If the images in a class are very similar, fewer images might be sufficient. the training images are representative of the variation typically found within the class.

Which is better for image classification RNN or CNN? ›

While RNNs are suitable for handling temporal or sequential data, CNNs are suitable for handling spatial data (images). Though both models work a bit similarly by introducing sparsity and reusing the same neurons and weights over time (in case of RNN) or over different parts of the image (in case of CNN).

What is the salary of Python Django developer? ›

Django Developer salary in India with less than 1 year of experience to 6 years ranges from ₹ 1.2 Lakhs to ₹ 12.6 Lakhs with an average annual salary of ₹ 3.1 Lakhs based on 90 salaries.

Is there anything better than Django? ›

Similar to Django, Laravel also has wide-ranging features to help developers create products with ease. Some of the features of Laravel are: Free and open source: Laravel is open source and available free to use. The MIT license enables you to manipulate its code in any way developers want for their products.

How long does it take to fully learn Django? ›

How Long Does it Take to Learn Python Django? It will take you about three months to master the basics of Django. But, you could create your first Django application within a day of getting started. To get started with Django, you'll need a solid understanding of the Python programming language.

Which is better for microservices Django or flask? ›

If you're application uses SQLite, PostgreSQL, MySQL, MariaDB, or Oracle, you should take a hard look at Django. On the other hand, if you're using NoSQL or no database at all, then Flask is a solid choice.

Is Django GOOD FOR REST API? ›

Django REST framework (DRF) is a powerful and flexible toolkit for building Web APIs. Its main benefit is that it makes serialization much easier. Django REST framework is based on Django's class-based views, so it's an excellent option if you're familiar with Django.

Is Django good for small projects? ›

Is Django good for small projects? A. Though you can experiment with Django for beginner-level projects for learning purposes, Django isn't suitable for basic apps as it is pretty complex. If your app doesn't need backend development, then Django would be an unnecessary addition to your technology stack.

Can Django be used for Blockchain? ›

Handling Contract's Responses in Django

First, you might have a made a transaction(added something to the Blockchain or made a payment). In this case, you will simple get back a transaction receipt. There is nothing more you would like to do with it since its just a confirmation that your transaction has executed.

Which is best IDE for Python for Django development? ›

PyCharm. PyCharm is a cross-platform Integrated Development Environment that was created by Jet Brains. It's one of the best Django IDE for any project that has to do with Python language.

Can I use NPM with Django? ›

You can also now use npm packages in your django app. For example, if you wanted to use jQuery simply install it. And import it in your script. js file.

What Python works with TensorFlow? ›

TensorFlow is tested and supported on the following 64-bit systems: Python 3.7–3.10. Ubuntu 16.04 or later. Windows 7 or later (with C++ redistributable)

Top Articles
Latest Posts
Article information

Author: Barbera Armstrong

Last Updated:

Views: 6350

Rating: 4.9 / 5 (79 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Barbera Armstrong

Birthday: 1992-09-12

Address: Suite 993 99852 Daugherty Causeway, Ritchiehaven, VT 49630

Phone: +5026838435397

Job: National Engineer

Hobby: Listening to music, Board games, Photography, Ice skating, LARPing, Kite flying, Rugby

Introduction: My name is Barbera Armstrong, I am a lovely, delightful, cooperative, funny, enchanting, vivacious, tender person who loves writing and wants to share my knowledge and understanding with you.