Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Django Framework
Open CV
Image Processing
Machine Learning
LINUX (Cent OS 7)
Prequisites :
CENTOS / RHEL, Python 3.6, OpenCV, opencv-python,
refer to centos.txt that I asked you to download
a django folder will be created in the folder from where you executed the above
now while staying in the folder that contains the django folder, type
source django/bin/activate
The prompt will now be prefixed with (django) which means we are now in a virtual environment for
this particular session and whatever we will be installing will be for this session / project only
now move to django folder and type the following to create a new folder structure as discussed in the
classroom session
Note : my centos7.txt contains information about how to open port in firewall settings, you will have to
openport 8000, if you need to access the webapplication from other machine.
Now in the browser type the following in the address bar
http://192.168.1.175:8000 and you should see the following
Now let us create our first application. We have already discussed it in the classroom session that a
project is a collection of application (apps)
and against import add import for include module, for that change the following line
from django.urls import path
to
now below must be a list definition for urlpatterns, insert one element at the beginning as follows
path('iprocone/',include('iprocone.urls')),
Now move to django/projiproc/iprocone folder and create a file named as urls.py
The contents of the file should be as shown below
Now in the same folder resides a file by the name of views.py, edit it and add the following to it
now move to django/projiproc folder and run the server as done earlier
http://192.168.1.175:8000/iprocone
and you should see the message ( django app1 iproc one home page )
Thats it. We have just now learned how to setup and django project + app. Now lets start building our
project.
Exit from the virtual environment, now let us install postgre on cent os
now lets move into the postgres shell, for that type
psql
Now let us change the postgre sql peer authentication system, so that the linux user account need not
match the postgre account as it will be quite irritating for us
replace peer with md5 and on the next two lines replace ident with md5
when prompted for passport, provide the password that we have set (projiproc)
and you should see the psql shell prompt as
projiprocdb=#
Now activate the django virtual environment by typing this from the parent folder of django
source django/bin/activate
now let us install a module required for postgre while staying in the enabled virtual environment
Now let us configure the (projiproc) project settings to use the database we created
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'projiprocdb',
'USER': 'projiprocuser',
'PASSWORD': 'projiproc',
'HOST': 'localhost',
'PORT': ''
}
}
make one more change to settings.py
insert this string as the first elements againts the list (INSTALLED_APPS)
INSTALLED_APPS = [
'iprocone.apps.IproconeConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
now we will create our model, our object is that we want a table by the name of member with fields as
follows
some id as primary key and it should be automatically assigned by postgre
email_id char(100) not null unique
name char(100) not null
requested_at datetime not null
uploaded_file char(100) not null
processing_time integer not null
Now instead of creating a table and then mapping a model with it, we will create model and will ask
django to migrate the model to relevant table, which means that the framework will login into the
postgre sql and will issue necessary sql statement to create the tables to represent the models in our
application.
Now let us activate this model, which means that create a table that would correspond to this model
(Member)
now move to the folders that contains manage.py (django\projiproc) and type
if there are no typing mistakes then you should get to see -Create Model Member as the lart part of the
output.
Now see the contents of iprocone/migrations folder, you should see a file by the name of
0001_initial.py
now type
you should see the create table statement. Don't worry about the field type varchar(35) instead of
char(35) and output may vary according to RDBMS.
Now type the following to generate the necesssary table.
Now login to the postgres sql using projiprocuser (account name), password (projiprocuer) and
database a (projiproc)
provide password and at the psql shell type \d and in the list you should see iprocone_member table.
Type \d iprocone_member and you will get to see the field details.
Type \q to quite from psql shell
Now let us create an admin account for this project, for that type
Now start server as we did earlier and in the browser's address bar type
http://192.168.1.175:8000/admin
Provide username and password and you can see the admin home page
Now shutdown the server and login into postgresql psql shell as done earlier and see the list of tables,
and you will see that django has created many tables related to user and groups
Now let us move ahead with our project.
unzip iproconeresources.zip
@import "https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700";
body {
background: #fafafa;
p{
font-size: 1.1em;
font-weight: 300;
line-height: 1.7em;
color: #999;
a, a:hover, a:focus {
color: inherit;
text-decoration: none;
.navbar {
background: #fff;
border: none;
border-radius: 0;
margin-bottom: 40px;
.navbar-btn {
box-shadow: none;
border: none;
.line {
width: 100%;
height: 1px;
margin: 40px 0;
/* ---------------------------------------------------
* SIDEBAR STYLE
* ----------------------------------------------------- */
.wrapper {
display: flex;
width: 100%;
align-items: stretch;
perspective: 1500px;
#sidebar {
min-width: 250px;
max-width: 250px;
background: #000;
color: #fff;
#sidebar.active {
margin-left: -250px;
transform: rotateY(100deg);
#sidebar .sidebar-header {
padding: 20px;
background: #003366;
#sidebar ul.components {
padding: 20px 0;
#sidebar ul p {
color: #fff;
padding: 10px;
#sidebar ul li a {
padding: 10px;
font-size: 1.1em;
display: block;
#sidebar ul li a:hover {
color: #7386D5;
background: #fff;
color: #000;
background: #97CBFF;
}
a[data-toggle="collapse"] {
position: relative;
.dropdown-toggle::after {
display: block;
position: absolute;
top: 50%;
right: 20px;
transform: translateY(-50%);
ul ul a {
background: #6d7fcc;
ul.CTAs {
padding: 20px;
ul.CTAs a {
text-align: center;
border-radius: 5px;
margin-bottom: 5px;
a.download {
background: #fff;
color: #7386D5;
a.article, a.article:hover {
/* ---------------------------------------------------
* CONTENT STYLE
* ----------------------------------------------------- */
#content {
width: 100%;
padding: 20px;
min-height: 100vh;
}
#sidebarCollapse {
width: 40px;
height: 40px;
background: #f5f5f5;
cursor: pointer;
#sidebarCollapse span {
width: 80%;
height: 2px;
margin: 0 auto;
display: block;
background: #555;
transition-delay: 0.2s;
#sidebarCollapse span:first-of-type {
#sidebarCollapse span:nth-of-type(2) {
opacity: 0;
#sidebarCollapse span:last-of-type {
}
#sidebarCollapse.active span {
transform: none;
opacity: 1;
/* ---------------------------------------------------
* MEDIAQUERIES
* ----------------------------------------------------- */
#sidebar {
margin-left: -250px;
transform: rotateY(90deg);
#sidebar.active {
margin-left: 0;
transform: none;
#sidebarCollapse span:first-of-type,
#sidebarCollapse span:nth-of-type(2),
#sidebarCollapse span:last-of-type {
transform: none;
opacity: 1;
}
#sidebarCollapse.active span {
margin: 0 auto;
#sidebarCollapse.active span:first-of-type {
#sidebarCollapse.active span:nth-of-type(2) {
opacity: 0;
#sidebarCollapse.active span:last-of-type {
.centered {
position: fixed;
z-index: 999;
height: 2em;
width: 2em;
overflow: show;
margin: auto;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
.imageEditor {
margin: auto;
top: 0;
left: 0;
bottom: 0;
right: 0;
padding: 20px;
max-height:800px;
max-width:800px;
.currentDate {
float:right;
padding-top:5px;
padding-right:5px;
font-size: 16pt;
.topBar{
height:40px;
background: #43464B;
color: white;
margin-bottom:10px;
.nav-company{
font-size:20pt;
position: fixed;
margin-left:40px;
.page-footer{
color: #003336;
#spinnerWrap {
position: fixed;
width: 100%;
height:100%;
display: flex;
top: 0;
.spinnerIcon {
margin: auto;
color: #fff;
text-align: center;
font-size:40pt;
.imageFileName {
float: left;
padding-top:5px;
padding-left:5px;
font-size: 16pt;
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function ViewState()
this.name='';
this.email='';
var openFileDivision=null;
var clientArea=null;
function initializeState()
$.ajax({
url: "getState",
type: "GET",
cache: false,
viewState=res;
updateView();
});
function updateView()
if(clientArea==null) clientArea=$('#clientArea');
if(openFileDivision==null) openFileDivision=$('#openFileDivision');
if(viewState.state=='none')
$('#sidebar').css('visibility','hidden');
$('#sidebarCollapse').css('visibility','hidden');
$('#sidebar').hide();
$('#sidebarCollapse').hide();
$('#sidebar').css('display','none');
$('#sidebarCollapse').css('display','none');
clientArea.html(openFileDivision);
$('#fileOptions').css('visibility','hidden');
$('#topBar').css('visibility','hidden');
if(viewState.state=='opening')
if(viewState.state=='open')
$('#sidebar').css('visibility','visible');
$('#sidebarCollapse').css('visibility','visible');
$('#sidebar').css('display','');
$('#sidebarCollapse').css('display','');
$('#sidebar').show();
$('#sidebarCollapse').show();
$('#fileOptions').css('visibility','visible');
$('#topBar').css('visibility','visible');
function closeFile()
{
viewState.state='none';
updateView();
$.ajax({
url: "closeFile",
type: "GET",
cache: false,
// do nothing
});
function openFile()
var openFileForm=document.getElementById('openFileForm');
viewState.state='opening';
updateView();
$('#spinnerWrap').css('display','');
$('#spinnerWrap').css('visibility','visible');
$('#spinnerWrap').show();
$.ajax({
url: "openFile",
type: "POST",
data: formData,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
viewState.state='open';
viewState.fileName=res.fileName;
viewState.email=res.email;
viewState.name=res.name;
openFileForm.reset();
updateView();
$('#spinnerWrap').css('display','none');
$('#spinnerWrap').css('visibility','hidden');
$('#spinnerWrap').hide();
$('#imageFileName').html('Image : '+viewState.fileName);
});
function toGrayscale()
$('#spinnerWrap').css('display','');
$('#spinnerWrap').css('visibility','visible');
$('#spinnerWrap').show();
$.ajax({
url: "toGrayscale",
type: "GET",
cache: false,
updateView();
$('#spinnerWrap').css('display','none');
$('#spinnerWrap').css('visibility','hidden');
$('#spinnerWrap').hide();
});
</script>
</head>
<body>
<div class="wrapper">
<div class="sidebar-header">
<h3>iMagic</h3>
</div>
<p>Image Processing</p>
<li>
</li>
<li>
</li>
<li>
</li>
<li><a href='#'>Many more .........</a>></li>
</ul>
</nav>
<div id="content">
<div class="container-fluid">
<span></span>
<span></span>
<span></span>
</button>
</button>
</ul>
</div>
</span>
</div>
</nav>
</div>
<div id='clientArea'>
<div id='openFileDivision'>
<div class='form-group'>
{% csrf_token %}
</div>
<div class='form-group'>
<label for='name'>Name</label>
</div>
<div class='form-group'>
</div>
<div class="line"></div>
<footer class="page-footer">
</div>
</footer>
</div>
</div>
<div class="spinnerIcon">
Loading<br/>
</div>
</div>
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
</div>
<div class="modal-body">
<div class='form-group'>
{% csrf_token %}
</div>
<div class='form-group'>
</div>
<div class='form-group'>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#sidebarCollapse').on('click', function () {
$('#sidebar').toggleClass('active');
$(this).toggleClass('active');
});
});
$.ajaxSetup({
function getCookie(name) {
var cookieValue = null;
break;
return cookieValue;
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
});
window.addEventListener('load',initializeState);
</script>
</body>
</html>
urlpatterns=[ path('',views.index,name='index'),
path('openFile',views.openFile,name='openFile'),
path('getImage',views.getImage,name='getImage'),
path('toGrayscale',views.toGrayscale,name='toGrayscale'),
path('getState',views.getState,name='getState'),
path('closeFile',views.closeFile,name='closeFile'),
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('iprocone/',include('iprocone.urls')),
path('admin/', admin.site.urls),
]
import os
ALLOWED_HOSTS = ['192.168.1.175']
# Application definition
INSTALLED_APPS = [
'iprocone.apps.IproconeConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'projiproc.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'projiproc.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'projiprocdb',
'USER': 'projiprocuser',
'PASSWORD': 'projiproc',
'HOST': 'localhost',
'PORT': ''
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'filestore')
Now the last part, edit the views.py in iprocone folder, I am providing the functions (without code) but
with what to do)
Complete it
views.py
from django.shortcuts import render
import datetime
from django.http import *
from django.core.files.storage import FileSystemStorage
import uuid
import os
import cv2
from pathlib import Path
def index(request):
today=datetime.datetime.now()
return render(request,'index.html',{
"today": today.strftime("%d-%m-%Y")
})
def isFileOpen(request):
Check that stack name email and fileName exists in session, if all exists return True
else remove the ones that exists and return False
def getState(request):
Call isFileOpen, if it sends back true then extract name,email,fileName return the response as follows
return JsonResponse({'state': 'open','name': name,'email': email,'fileName':fileName})
else return the following response
return JsonResponse({'state':'none','name':'','email':'','fileName':''})
def openFile(request):
check if the request is of type POST and file 'fileName' has been uploaded or not. Check the
request.FILES part
If not then do nothing, we don't care that nothing happens on the client side
if yes then extract data against 'fileName' from request.FILES[]
use FileSystemStorage to store the file, it will give back the actual new name
extract email,name from request.POST[]
ask save method FileStorage class to save the contents of the imageFile by the name of the file being
uploaded (use imageFile.name), the save method will return the actual name of the uploaded file.
Trap it as imageFileName
set the session expiry time (10 hours)
ceate a list() as stack and insert the imageFileName at top
keep (stack as 'stack',name as 'name',email as 'email' and imageFile.name as 'fileName') in session
then return JsonResponse({'fileName':imageFile.name})
def getImage(request):
if request.method=="GET" and request.session.has_key('stack'):
stack=request.session['stack']
if len(stack)>0:
fileToServe=os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'filestore/%s'%stack[0]))
return FileResponse(open(fileToServe,'rb'))
return HttpResponse('')
def closeFile(request):
check if session has a key named as stack
if yes then extract the list, traverse it
create absolute path (/home/django/projiproc/filestore/name_of_file_to_delete) on every iteration and
delete the file from file system
then delete the stack/name/email/fileName and whatever you must have kept, from the session
def toGrayscale(request):
check if stack exists in session, if yes extract the zeroth element from the stack, create a string that
would contain the absolute path of the zeroth index element
extract its extension
generate a new unique string (use uuid module)
attach the extension
ask opencv function to open the original file
convert it to grayscale and save it by newly generated namee
insert the new name on stack
keep the stack in session
then return JsonResponse({'response':'convertedToGrayscale'})
if stack doesn't exist in session then return HttpResponse('')
http://192.168.1.175:8000/iprocone and you should see whatever you saw in the classroom session