"Trash classification by image!" App creation diary day3 ~ Web application with Django ~

Introduction

"Classify garbage by image!" Today, the third day of the app creation diary, I would like to use Django to make it a web app.


Article list

-"Trash classification by image!" App creation diary day1 ~ Data set creation ~ -"Trash classification by image!" App creation diary day2-Fine-tuning with VGG16- -"Trash classification by image!" App creation diary day3 ~ Web application with Django ~ ← Imakoko -"Trash classification by image!" App creation diary day4 ~ Prepare the front end with Bootstrap ~ -"Trash classification by image!" App creation diary day5-Prepare front end with Bootstrap 2- -"Trash classification by image!" App creation diary day6 ~ Correction of directory structure ~

Synopsis up to the last time

In the previous article, I created a model by fine-tuning with VGG16. This time the goal is to be able to run this model on a local browser.

Rough flow

As a flow, first set the original settings of the application. Then create a form so you can upload the image. After that, I will rub it with the model I made last time. For the time being, I'm planning to make only the minimum form and maintain html and css from the next time onwards.

Creating a Django app

First, run the code that creates your Django app on the console. VSCode will open the entire folder, so if you don't, move it to the current directory first.

console


django-admin startproject garbage_proj
cd garbage_proj
python manage.py startapp garbage

Now that you have the basics, let's start with it.

setting setting

First, rewrite garbage_proj / setting.py. I will write it on the code block including the method.

garbage_proj/setting.py



INSTALLED_To APPS"garbage"add to

#Rewrite the following
LANGUAGE_CODE = 'ja'
TIME_ZONE = 'Asia/Tokyo'

The model is not necessary this time because it does not have a function to save images. Make a form for uploading images. Create a new forms.py and write the following.

garbage/forms.py



from django import forms
class UploadPictureForm(forms.Form):
	img = forms.ImageField(required=True, label="")

Label is a problem when displaying in html, but if you do {{form}}, it will be displayed including label, so it is left blank. (If you list the elements yourself, you don't need to set them.)

Settings around URL

First, set up the routing of the original URL. Add it to urls.py in garbage_proj.

garbage_proj/urls.py



from django.urls import include

urlpatterns = [
    # path('admin/', admin.site.urls),
    path("garbage/", include("garbage.urls")),
    path("", include("garbage.urls"))
]

If you specify include ("garbage.urls "), you can skip the process to refer to urls.py in the garbage folder. I don't use admin, so comment it out. Also, if you set the routing for " ", you can open it directly when you step on the link displayed when you start the server, which is convenient.

Next, create a new garbage / urls.py and write the processing when the processing is skipped to garbage.

garbage/urls.py



from django.urls import path
from . import views
urlpatterns = [
    path("", views.index, name="index"),
    path("result", views.result, name="result"),
]

View settings

In Views, describe the processing to be performed on the server side.

garbage/views.py


from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import TemplateView
from django.core.paginator import Paginator
from django.contrib.auth.decorators import login_required
from .forms import UploadPictureForm
from PIL import Image


def index(request):
    params = {
        "form":UploadPictureForm()
    }
    return render(request, "garbage/index.html", params)


def result(request):
    form = UploadPictureForm(request.POST, request.FILES)
    if form.is_valid():
        img = form.cleaned_data["img"]
        pred = predict(img)
    else:
        params = {
            "form":UploadPictureForm()
        }
        return render(request, "garbage/index.html", params)

    params = {
        "img":img,
        "pred":pred
    }
    return render(request, "garbage/result.html", params)
    #Once here

In the result function, the image is recognized by request.FILES, so we are processing to retrieve it. Also, by setting form.cleaned_data, it will be returned in an easy-to-understand form (it seems that it can be used only after confirming form.is_valid).

garbage/views.py


#Continuation from the code block above
def predict(img):
    #Read
    import numpy as np
    import matplotlib.pyplot as plt
    from keras.preprocessing import image
    from keras.models import model_from_json
    from PIL import Image

    model = model_from_json(open("../model.json").read())
    model.load_weights('../param.hdf5')

    img_width, img_height = 150, 150
    img = Image.open(img)
    img.save("image.png ")
    img = np.array(img.resize((img_width, img_height)))
    classes = ['Non-burnable garbage', 'Packaging container plastics', 'Combustible waste', 'Hazardous waste', 'Resources']

    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = x / 255.0

    #Predict the person in the image
    pred = model.predict(x)[0]
    #View results
    pred_dict = {c:s for (c, s) in zip(classes, pred*100)}
    pred_dict = sorted(pred_dict.items(), key=lambda x:x[1], reverse=True)
    return pred_dict

Basically, the previous model is the same, but the path etc. have been fixed so that it feels good. Also, the image file has a format like 'InMemoryUploadedFile' as it is, so it is read again with Pillow.

Creating a Template file

We will create a Template (like the original HTML file). Make sure to create a templates folder and put the files in it.

garbage/templates/garbage/index.html


{% load static %}
<!DOCTYPE html>
<html lang="ja">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Garbage classification by image!</title>
	<link rel="stylesheet" type="text/css" href="{% static 'garbage/css/style.css' %}" />
</head>
<body>
	<h1>Garbage classification by image!</h1>
	<p>Please enter the image you want to check the classification</p>
	<form action="/garbage/result" method="post" enctype="multipart/form-data">
		{% csrf_token %}
		{{ form }}
		<br>
		<button type="submit">Send</button>
	</form>
</body>
</html>

Excuse me for writing this time, but the screen looks like the one below. image.png

Next, we will create the result screen.

garbage/templates/garbage/result.html


{% load static %}
<!DOCTYPE html>
<html lang="ja">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Garbage classification by image!</title>
	<link rel="stylesheet" type="text/css" href="{% static 'garbage/css/style.css' %}" />
</head>
<body>
	<h1>Garbage classification by image!</h1>
	<p>Result is</p>
	<img src="../image.png " alt="image">
	<table>
		<tr><th>Classification</th><td>probability</td></tr>
		{% for key, value in pred %}
			<tr><th>{{ key }}</th><td>{{ value }}</td></tr>
		{% endfor %}
	</table>
	<a href="{% url "index" %}">Top</a>

</body>
</html>

You can write python code by writing {%%} in the template file. How to write a for statement is a little special, but I write it like this. And when you upload the image and execute it, the following screen will be displayed. image.png I don't know the path setting for the image, so it's not displayed, but the program itself seems to be working nicely!

Speaking of which, I haven't written anything about CSS, but I think that only the files are placed and HTML is also applied.

garbage/static/garbage/css/style.css


/*  */

Next time, I will make a little more front end.


Article list

-"Trash classification by image!" App creation diary day1 ~ Data set creation ~ -"Trash classification by image!" App creation diary day2-Fine-tuning with VGG16- -"Trash classification by image!" App creation diary day3 ~ Web application with Django ~ ← Imakoko -"Trash classification by image!" App creation diary day4 ~ Prepare the front end with Bootstrap ~ -"Trash classification by image!" App creation diary day5-Prepare front end with Bootstrap 2- -"Trash classification by image!" App creation diary day6 ~ Correction of directory structure ~

Recommended Posts

"Trash classification by image!" App creation diary day3 ~ Web application with Django ~
"Trash classification by image!" App creation diary day8 ~ heroku deployment ~
"Trash classification by image!" App creation diary day6 ~ Correction of directory structure ~
"Garbage classification by image!" App creation diary day2-Fine-tuning with VGG16-
"Garbage classification by image!" App creation diary day1 ~ Data set creation ~
Web application creation with Django
"Classify garbage by image!" App creation diary day5 ~ Prepare front end with Bootstrap 2 ~
"Classify garbage by image!" App creation diary day4 ~ Prepare the front end with Bootstrap ~
Build a web application with Django
Web App Development Practice: Create a Shift Creation Page with Django! (Shift creation page)
I made a WEB application with Django
Web App Development Practice: Create a Shift Creation Page with Django! (Introduction)
WEB application development using Django [Admin screen creation]
Until Django application creation by terminal (development environment)
[Day 4] Application creation
Try creating a web application with Vue.js and Django (Mac)-(1) Environment construction, application creation
Web App Development Practice: Create a Shift Creation Page with Django! (Write a base template)
Web application made with Python3.4 + Django (Part.1 Environment construction)
Web App Development Practice: Create a Shift Creation Page with Django! (Design of database model)
Image classification with self-made neural network by Keras and PyTorch
[Deep learning] Image classification with convolutional neural network [DW day 4]
Web application development with Flask
Easy image classification with TensorFlow
Image collection by web scraping
Web application with Python + Flask ② ③
Real-time web with Django Channels
Web application with Python + Flask ④
Challenge image classification by TensorFlow2 + Keras 4 ~ Let's predict with trained model ~
If you know Python, you can make a web application with Django
Launched a web application on AWS with django and changed jobs