目次
Introduction
Hi everyone, this is Mohamed Alomar from GeekFeed.
This blog shows how to access client’s Webcam and how to send live streaming images to Django server using Python and JavaScript.
Prerequisites:
To follow this blog, you should have:
- Remote Linux server (the used one in this blog is Ubuntu Server 20.04 LTS (HVM) provided by AWS).
- Windows Machine for the local development(Windows 10 machine is used in writing this blog).
Starting new Django project
Installing Python on Windows
Django is a python framework, thus Python is required to be installed, to install Python on windows follow the instructions in this link (the recommended version is Python3.7 or later).
Installing Django
After having Python installed on your Windows machine, install Django package by using the following command:
1 |
pip install django |
Verifying Djano version
To confirm the version of Django you have, run the following command in Windows shell prompt:
1 |
python -m django --version |
Starting a new Django project
To start a new Django project run the following command:
1 |
django-admin startproject webcam |
then navigate to webcam directory and create new Django application by running the following command:
1 |
python manage.py startapp webcamapp |
Now, that webcamapp has been created, you have to register this app in the main project, so it will be included when any tools are run, to do so, open project settings file then add new line to INSTALLED_APPS list as below:
1 2 3 4 5 |
INSTALLED_APPS = [ ... 'webapp', ... ] |
Frontend files:
In order to have your static files accessible by other Django functionalities, You need to create templates and static directories inside webapp folder, and inside these two folders your HTML and JavaScript files will reside.
index.html
create new html file (ex:index.html ) inside webapp/templates folder:
1 2 3 4 5 6 |
<body> ..... <video autoplay playsinline id="videoElement"></video> <canvas id="canvas" width="400" height="300"></canvas> ...... </body> |
a video tag is used to embed a simple HTML5 video player to your page.
canvas tag is used to draw graphics using scripts.
Now that you have set the required HTML tags ,it is time to add JavaScript code that will constantly embed your Webcam recordings to the created video player.
app.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
<script src="http://code.jquery.com/jquery-latest.min.js"> var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); const video = document.querySelector("#videoElement"); video.width = 400; video.height = 300; if (navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia({ video: true }) .then(function(stream) { video.srcObject = stream; video.play(); }) .catch(function(err0r) { }); } var timeLeft = 45; var timerId = setInterval(countdown, 1000); function countdown() { if (timeLeft == 0) { clearTimeout(timerId); return '..' } else { timeLeft--; width = video.width; height = video.height; context.drawImage(video, 0, 0, width, height); var dataa = canvas.toDataURL('image/jpeg', 0.5); context.clearRect(0, 0, width, height); $.ajax({ type: 'POST', url: "{% url 'Start_Webcam' %}", data: { 'image': data, csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function(data) { console.log(data) }, error: function(response) { console.log('Error') }, } ); } } </script> |
Back-end functionalities:
URLs
Urls.py file is used to manage and redirect the clients requests by returning back the page that the user is looking for, so urls job to loot at the request URL and then decide which function(view) to fire, and finally return the results back and display it on client’s browser.
Therefore, your urls.py file should contain the following pattern:
1 2 3 4 5 6 7 8 |
from django.urls import path .... urlpatterns = [ .. path('Start_Webcam/', views.Start_Webcam, name='predict'), ... ] |
Views:
View in Django is a function that is triggered from urls.py file, it takes a web request as its input ,then handles that request and returns results as web response.
Your view that will be triggered to handle the coming request should contain the following logic:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import base64 ..... def Start_Webcam(request): if (request.method == 'POST'): try: frame_ = request.POST.get('image') frame_=str(frame_) data=frame_.replace('data:image/jpeg;base64,','') data=data.replace(' ', '+') imgdata = base64.b64decode(data) filename = 'some_image.jpg' with open(filename, 'wb') as f: f.write(imgdata) except: print('Error') return JsonResponse({'Json':data}) |
Issue to solve(After deploying Django app to production)
After deploying Django app to Ubuntu server, the code to detect and run WebCam won’t work correctly (when using Google Chrome and with many other web browsers).
The reason behind that is Google Chrome does not allow accessing user personal data on insecure connection through http protocol, and Django runs its application using http protocol, so in order to overcome this Issue, you need to enable https protocol and run your Django application through that protocol,
in order to do that you need to install django-sslserver module in your Python distribution .
1 |
pip install django-sslserver |
To consider the installed library in your project, you need to specify
django-sslserver name in INSTALLED_APPS list as follows in settings.py:
1 2 3 4 |
INSTALLED_APPS = [ ... 'sslserver' ] |
start up django app with runsslserver
1 |
python manage.py runsslserver 0.0.0.0:port_number |
When you try to access the deployed Django application in remote session , you will be prompted to grant access to the system’s camera , after that the streaming of images will be sent constantly to the server side where you can preform the image processing operations you wish.
Conclusion
Before starting a web project , it is important to choose the right language and the right framework to use, Django is one of the best web frameworks that can be used in web development, due to its ability of having smooth communication between client’s system resources (camera ,microphone, .. etc. ) and backend functionalities, besides being highly secure , scalable and supports cross-platform apps.
- Simple AWS DeepRacer Reward Function Using Waypoints - 2023-12-19
- Restrict S3 Bucket Access from Specified Resource - 2023-12-16
- Expand Amazon EBS Volume on EC2 Instance without Downtime - 2023-09-28
- Monitor OpenSearch Status On EC2 with CloudWatch Alarm - 2023-07-02
- Tokyo’s Coworking Space Hidden Gem: AWS Startup Loft Tokyo - 2023-05-24