Importing libraries

The first thing that we have to do is to import libraries. In this case, we will import the Flask library for implementing our web application. Also, we import the OpenCV library for implementing our computer vision solution.

From Flask, we will import the Flask for generating the web app. Also, we will import the Response object for receiving images from the webcam. Here is the code for doing that:

Initializing objects

After we import the library, the next step is to initialize several objects.

  • The first one is the Flask object.
    As I’ve mentioned before, the Flask object will initialize things that we need for building a web app, so we can focus on building our solution.
  • The second is the VideoCapture object from the OpenCV library.
    This object will catch outputs, where the web camera is the source. We will set a parameter ‘0’ for taking images from the web camera.
  • The last one is the CascadeClassifier from the OpenCV library.
    This object will initialize a face detection model, where the model is based on combinations of AdaBoost and Cascade Classifier. This model is already trained with lots of images that are represented as a feature called Haar. I don’t explain this classifier further, but one day I will explain to you, Insha Allah.

In this article, we will not train our model from scratch. We will use the pre-trained model from OpenCV, which you can download here.

Here is the code for initializing the objects:

Implementing the face detection

After you initialize the object, the next step is to implement a function for our face detection. Here are the steps that our function will do:

  • This function below will take an input, which in this case, from the webcam, that is processed per frame.
  • On each frame, the function will detect the face from it and set a bounding box that is surrounding our face.
  • After the function detects the face, the function generates an image with the .jpeg format and converts it into bytes.
  • These bytes from the image will be attached to an HTTP response.
  • Because we send the image more than once, we will use the yield keyword rather than the return keyword. The reason is that the yield keyword returns a generator that always generates values, as long there is no threshold to it.

Here is the code for the implementation:

After we create our face detection function, the next step is to build a function for displaying our face detection results on the website. In the function below, you can see that there is something called…

Continue reading: https://towardsdatascience.com/how-to-display-video-streaming-from-a-webcam-using-flask-7a15e26fbab8?source=rss—-7f60cf5620c9—4

Source: towardsdatascience.com