15.02.2018       Выпуск 217 (12.02.2018 - 18.02.2018)       Статьи

Пишем Django API для поиска лица на фото с OpenCV и Haar Cascades opencv Django


Экспериментальная функция:

Ниже вы видите текст статьи по ссылке. По нему можно быстро понять ссылка достойна прочтения или нет

Просим обратить внимание, что текст по ссылке и здесь может не совпадать.

Building a Django POST face-detection API using OpenCV and Haar Cascades

I’ve been wanting to work on face detection for quite some time now. Mainly because it sounds so intriguing. In this blog post, I cover the aspect of face recognition via. Django using the HAAR Cascades framework offered via. OpenCV. This is basically the guide to build an API for the same which can be deployed later as per your convenience. I haven’t deployed it as such and have run it on my local machine itself.

In the blogs that I have covered till now, I have hit the areas ofsentiment analysis(via tensorflow), stock-market forecasting(for Bitcoin)as well as some guides on Prediction using ML and Numpy for stock trends.

Let’s begin the journey, shall we?

This is the list of tools/packages/libs you’re required to possess. Our API will basically read a URL stream that has the image uploaded and accordingly return the JSON response with the detected faces marked.

if you run into installation issues, there’s always stack-overflow.Believe me, it’s the best help you’ll ever have. Oh, and of course, your best friend, Google :)

Once you’re through, we start of with creating a project named facedetection

Migrate to a directory of your choice and execute the following command

This creates the project named facedetectionin the respective directory.

Do a CD in this project directory to get into the newly created project folder.

>cd facedetection

will get you inside the project folder which will have namely 2 files — manage.pyand a sub-folder with the same name as the root folder i.e facedetection

Now, we write a simple Django command to launch the application

As you can see,

python manage.py startapp face_detector

launches a new folder inside your parent folder with the name face_detector.This is your application basically which has a boiler plate in that there are various files contained within this folder — views.py, admin.py, tests.py which come as django imports and are necessary components of any Api wrapper you’d want to build. We’re mainly concerned with the view.pyfile. This view implies your API’s front-end in a sense and all the coding has to be done within this file primarily.

If you were to be interacting with the back-end as well, there are other files you would have been concerned about on top of views.py — namely models.py

Working with Views.py

Migrate to facedetection/face_detector/views.pyand you can open the views.py file that’s basically empty at this point. We start of with initializing necessary imports namely.

note: csrf_exempt is mandatory as its a middle-ware specific import needed for protection against cross site request forgery


from django.views.decorators.csrf import csrf_exempt
to the list

Ok now we have to define the face_detector_path to the .xml file that comes along with Haar cascades as you install it. You can either look for it directly in the folder where you might’ve installed haar cascades inside the open cv folder of if you end up in some trouble trying to locate it just like I did, you need not worry. Just import it externally from this git repo.Go for the frontalface_default.xml and frontalface_default_alt.xml files and save them somewhere where you can later locate them easily.

Next step, store the path to this file in a variable.

Define the path to the .xml file

Up next, we define the function to read the request URL in JSON format — this is the URL where we’re uploading the image to be detected for facial recognition later.

The function is requested_url(request)

I am breaking it down in 3 segments to try my best to simplify the process.

(Segment 1/3)

Make sure you specify the @csrf_exempt import right before when you define the function

  1. The default value for successful import/execution for the URL is set to be false as we begin since we don’t really have the URL stream as of now.
  2. When dealing with incoming http streams, you can either choose to go with get streams or POST streams — the difference between the two being that GET is used to retrieve remote data where as POST is used more commonly to insert/update remote data.

A Quora user was kind enough to break it downmore simplistically.

3. If the method requested is POST just like we wanted, we check if the image exists within the POST stream and if it is not Noneand we then proceed to read the image as a stream using a read_image() function that I will specify later.

4. If there’s no URL provided, a simple message pops up telling the same. Finally, we return the JsonResponse value for the default variable which is basically the stream of data that’s incoming in the form of the image that is being read using a read_image function which would be created later

(Segment 2/3)

  1. We start off by converting the image to gray-scale. This is going to be our input image which we’re now converting to gray-scale
  2. We have originally supplied the path to the .xml file which is our pre-trained face detector as it comes with Haar cascades
  3. Next, we apply the detectMultiScale method which has to be used to detect the faces. You’ll have to dive deeper to figure out the internal parameters and as to how that method works and how effectively can you exploit it.
  4. Parameters returned by the method include coordinates which are essentially boxes that you’ll see as we detect the faces.
  5. Now we package these into our dictionary defaultand this is then returned back

(Segment 3/3) — Defining the read_image() function

Changes to be made in the facedetection/face_detector/urls.py file:

Changes to be made in the Urls.py file

Next, we will create a test_run.pyfile in the same directory as your face detector and mange.py.

This is the file where we would be testing the API.

Create a new file and the following code in it:


Finally, deploying the API can be a bit tedious if you execute if with post services like CURL but in this case, I am just hosting the image on an external URL and referring that in the test_run.py file. Also, you can simply store the image file in your project directory — where you have the test_run.py file stored and that will also work for you.


NOTE: I have covered the entire deployment run via. a video that I have uploaded on Youtube. You can find thathere
However, in case, you find reading the blog more convenient, please feel free to carry on.
  1. Run manage.py inside the project directory

A successful run would look something like this:

Visit your localhost( and it will show a pop up message as {successs: false} since you haven’t really set up the image stream yet.

The image I am using for now is posted here:


Sample image

Running the below Curl Script, you can see that our API detects 6 faces”

This detects four faces as can be seen below and as is pointed out by the Curl script that’s posted above. The curl script outputs the dimensions for each box that is capturing each face.

To run the API, migrate to the repository where you have the test_run.pysaved then simply type:

>>python test_run.py

The pop up will be where you can see the detected faces.

Another run on a different image,

Hosted here -> https://image.ibb.co/iCtoy7/temp.png

Please make sure to update the respective location and the URL in the test_run file.

Specifically, these two variables:

Update with each new run

And this is it! We now have ourselves a simple face recognition API built using HAAR cascades deployed on a django localhost server.

Full link to the github repo:

Please feel free to leave suggestions and claps if this even remotely fascinated you.

I’ll be back with more. Cheers.

Лучшая Python рассылка

Нас поддерживает

Python Software Foundation

Разместим вашу рекламу

Пиши: mail@pythondigest.ru

Нашли опечатку?

Выделите фрагмент и отправьте нажатием Ctrl+Enter.

Система Orphus