{"id":17581,"date":"2023-06-09T18:31:00","date_gmt":"2023-06-09T13:01:00","guid":{"rendered":"https:\/\/www.mygreatlearning.com\/blog\/real-time-face-detection\/"},"modified":"2024-11-11T13:37:15","modified_gmt":"2024-11-11T08:07:15","slug":"real-time-face-detection","status":"publish","type":"post","link":"https:\/\/www.mygreatlearning.com\/blog\/real-time-face-detection\/","title":{"rendered":"Real-time Face detection | Face Mask Detection using OpenCV"},"content":{"rendered":"\n<p>In this article, we are going to find out how to <a href=\"https:\/\/www.mygreatlearning.com\/academy\/learn-for-free\/courses\/face-detection-with-opencv-in-python\" target=\"_blank\" rel=\"noreferrer noopener\">detect faces in real-time using OpenCV<\/a>. After detecting the face from the webcam stream, we are going to save the frames containing the face. Later we will pass these frames (images) to our mask detector classifier to find out if the person is wearing a mask or not. <\/p>\n\n\n\n<p>We are also going to see how to make a custom mask detector using <a href=\"https:\/\/www.mygreatlearning.com\/academy\/learn-for-free\/courses\/introduction-to-tensorflow-and-keras\" target=\"_blank\" rel=\"noreferrer noopener\">Tensorflow and Keras<\/a> but you can skip that as I will be attaching the trained model file below which you can download and use. Here is the list of subtopics we are going to cover:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><a href=\"#ad1\">What is Face Detection?<\/a><\/li>\n\n\n\n<li><a href=\"#ad2\">Face Detection Methods<\/a><\/li>\n\n\n\n<li><a href=\"#ad3\">Face detection algorithm <\/a><\/li>\n\n\n\n<li><a href=\"#ad4\">Face recognition<\/a> <\/li>\n\n\n\n<li><a href=\"#ad5\">Face Detection using Python<\/a><\/li>\n\n\n\n<li><a href=\"#sh1\">Face Detection using OpenCV<\/a> <\/li>\n\n\n\n<li><a href=\"#sh2\">Create a model to recognise faces wearing a mask (Optional)<\/a><\/li>\n\n\n\n<li><a href=\"#sh3\">How to do Real-time Mask detection<\/a>&nbsp;<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"what-is-face-detection\"><strong>What<\/strong> <strong>is Face Detection?<\/strong><\/h2>\n\n\n\n<p>The goal of face detection is to determine if there are any faces in the image or video. If multiple faces are present, each face is enclosed by a bounding box and thus we know the location of the faces<\/p>\n\n\n\n<p>The primary objective of face detection algorithms is to accurately and efficiently determine the presence and position of faces in an image or video. The algorithms analyze the visual content of the data, searching for patterns and features that correspond to facial characteristics. By employing various techniques, such as machine learning, image processing, and pattern recognition, face detection algorithms aim to distinguish faces from other objects or background elements within the visual data, helping companies to enhance the <a href=\"https:\/\/cyberpandit.org\/\">cybersecurity<\/a> of their business<\/p>\n\n\n\n<p>Human faces are difficult to model as there are many variables that can change for example facial expression, orientation, lighting conditions, and partial occlusions such as sunglasses, scarfs, masks, etc. The result of the detection gives the face location parameters and it could be required in various forms, for instance, a rectangle covering the central part of the face, eye centers or landmarks including eyes, nose and mouth corners, eyebrows, nostrils, etc.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"face-detection-methods\"><strong>Face Detection Methods<\/strong><\/h2>\n\n\n\n<p>There are two main approaches for Face Detection:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Feature Base Approach<\/li>\n\n\n\n<li>Image Base Approach<\/li>\n<\/ol>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"feature-base-approach\"><strong>Feature Base Approach<\/strong><\/h4>\n\n\n\n<p>Objects are usually recognized by their unique features. There are many features in a human face, which can be recognized between a face and many other objects. It locates faces by extracting structural features like eyes, nose, mouth etc. and then uses them to detect a face. Typically, some sort of statistical classifier qualified then helpful to separate between facial and non-facial regions. In addition, human faces have particular textures which can be used to differentiate between a face and other objects. Moreover, the edge of features can help to detect the objects from the face. In the coming section, we will implement a feature-based approach by using the <a href=\"https:\/\/www.mygreatlearning.com\/academy\/learn-for-free\/courses\/opencv-tutorial\" target=\"_blank\" rel=\"noreferrer noopener\">OpenCV tutorial<\/a>.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"image-base-approach\"><strong>Image Base Approach<\/strong><\/h4>\n\n\n\n<p>In general, Image-based methods rely on techniques from <a href=\"https:\/\/www.mygreatlearning.com\/blog\/what-is-statistical-analysis\/\">statistical analysis<\/a> and machine learning to find the relevant characteristics of face and non-face images. The learned characteristics are in the form of distribution models or discriminant functions that is consequently used for face detection. In this method, we use different algorithms such as Neural-networks, HMM, <a href=\"https:\/\/www.mygreatlearning.com\/blog\/introduction-to-support-vector-machine\/\">SVM<\/a>, <a href=\"https:\/\/www.mygreatlearning.com\/blog\/adaboost-algorithm\/\" target=\"_blank\" rel=\"noreferrer noopener\">AdaBoost learning<\/a>. In the coming section, we will see how we can detect faces with MTCNN or Multi-Task Cascaded Convolutional <a href=\"https:\/\/www.mygreatlearning.com\/blog\/types-of-neural-networks\/\" target=\"_blank\" rel=\"noreferrer noopener\">Neural Network<\/a>, which is an Image-based approach of face detection<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"face-detection-algorithm\"><strong>Face detection algorithm<\/strong><\/h2>\n\n\n\n<p>One of the popular algorithms that use a feature-based approach is the <a href=\"https:\/\/www.mygreatlearning.com\/blog\/viola-jones-algorithm\/\" target=\"_blank\" rel=\"noreferrer noopener\">Viola-Jones algorithm<\/a> and here I am briefly going to discuss it. If you want to know about it in detail, I would suggest going through this article, Face Detection using Viola Jones Algorithm.<\/p>\n\n\n\n<p><strong>Viola-Jones<\/strong>&nbsp;algorithm is named after two computer vision researchers who proposed the method in 2001, Paul&nbsp;<strong>Viola<\/strong>&nbsp;and Michael&nbsp;<strong>Jones<\/strong>&nbsp;in their paper, \u201cRapid Object Detection using a Boosted Cascade of Simple Features\u201d. Despite being an outdated framework,&nbsp;Viola-Jones&nbsp;is quite powerful, and its application has proven to be exceptionally notable in real-time face detection. This algorithm is painfully slow to train but can detect faces in real-time with impressive speed.<\/p>\n\n\n\n<p>Given an image(this algorithm works on grayscale images), the algorithm looks at many smaller subregions and tries to find a face by looking for specific features in each subregion. It needs to check many different positions and scales because an image can contain many faces of various sizes.&nbsp;Viola&nbsp;and&nbsp;Jones&nbsp;used Haar-like features to detect faces in this algorithm.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"face-recognition\"><strong>Face Recognition<\/strong><\/h2>\n\n\n\n<p>Face detection and Face Recognition are often used interchangeably but these are quite different. In fact, Face detection is just part of Face Recognition.<\/p>\n\n\n\n<p>Face recognition is a method of identifying or verifying the identity of an individual using their face. There are various algorithms that can do face recognition but their accuracy might vary. Here I am going to describe how we do face recognition using deep learning.<\/p>\n\n\n\n<p>In fact here is an article, Face Recognition Python which shows how to implement Face Recognition.<\/p>\n\n\n\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\n<iframe title=\"Real-Time Face Detection implementation with python - Great Learning\" width=\"500\" height=\"281\" src=\"https:\/\/www.youtube.com\/embed\/mPZdL2xGI_g?start=765&feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe>\n<\/div><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"face-detection-using-python\"><strong><a href=\"https:\/\/www.mygreatlearning.com\/academy\/learn-for-free\/courses\/face-detection-with-opencv-in-python\" target=\"_blank\" rel=\"noreferrer noopener\">Face Detection using Python<\/a><\/strong><\/h3>\n\n\n\n<p>As mentioned before, here we are going to see how we can detect faces by using an Image-based approach. MTCNN or Multi-Task Cascaded Convolutional Neural Network is unquestionably one of the most popular and most accurate face detection tools that work this principle. As such, it is based on a <a href=\"https:\/\/www.mygreatlearning.com\/deep-learning\/free-courses\" target=\"_blank\" rel=\"noreferrer noopener\">deep learning<\/a> architecture, it specifically consists of 3 neural networks (P-Net, R-Net, and O-Net) connected in a cascade.<\/p>\n\n\n\n<p>So, let\u2019s see how we can use this algorithm in Python to detect faces in real-time. First, you need to install MTCNN library which contains a trained model that can detect faces.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>pip install mtcnn<\/code><\/pre>\n\n\n\n<p>Now let us see how to use MTCNN:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom mtcnn import MTCNN\nimport cv2\ndetector = MTCNN()\n#Load a videopip TensorFlow\nvideo_capture = cv2.VideoCapture(0)\n\nwhile (True):\n    ret, frame = video_capture.read()\n    frame = cv2.resize(frame, (600, 400))\n    boxes = detector.detect_faces(frame)\n    if boxes:\n\n        box = boxes&#x5B;0]&#x5B;&#039;box&#039;]\n        conf = boxes&#x5B;0]&#x5B;&#039;confidence&#039;]\n        x, y, w, h = box&#x5B;0], box&#x5B;1], box&#x5B;2], box&#x5B;3]\n\n        if conf &gt; 0.5:\n            cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 255, 255), 1)\n\n    cv2.imshow(&quot;Frame&quot;, frame)\n    if cv2.waitKey(25) &amp; 0xFF == ord(&#039;q&#039;):\n        break\n\nvideo_capture.release()\ncv2.destroyAllWindows()\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"face-detection-using-opencv\"><strong>Face Detection using OpenCV<\/strong><\/h2>\n\n\n\n<p>In this section, we are going to perform real-time <a href=\"https:\/\/www.mygreatlearning.com\/academy\/learn-for-free\/courses\/face-detection-with-opencv-in-python\" target=\"_blank\" rel=\"noreferrer noopener\">face detection using OpenCV<\/a> from a live stream via our webcam. <\/p>\n\n\n\n<p>As you know videos are basically made up of frames, which are still images. We perform face detection for each frame in a video. So when it comes to detecting a face in a still image and detecting a face in a real-time video stream, there is not much difference between them.<\/p>\n\n\n\n<p>We will be using Haar Cascade algorithm, also known as Voila-Jones algorithm to detect faces. It is basically a machine learning object detection algorithm that is used to identify objects in an image or video. In OpenCV, we have several trained&nbsp; Haar Cascade models which are saved as XML files. Instead of creating and training the model from scratch, we use this file. We are going to use \u201chaarcascade_frontalface_alt2.xml\u201d file in this project. Now let us start coding this up<\/p>\n\n\n\n<p>The first step is to find the path to the \u201chaarcascade_frontalface_alt2.xml\u201d file. We do this by using the os module of Python language.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import os\ncascPath = os.path.dirname(\n    cv2.__file__) + \"\/data\/haarcascade_frontalface_alt2.xml\"<\/code><\/pre>\n\n\n\n<p>The next step is to load our classifier. The path to the above XML file goes as an argument to CascadeClassifier() method of OpenCV.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>faceCascade = cv2.CascadeClassifier(cascPath)<\/code><\/pre>\n\n\n\n<p>After loading the classifier, let us open the webcam using this simple OpenCV one-liner code<br><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>video_capture = cv2.VideoCapture(0)<\/code><\/pre>\n\n\n\n<p>Next, we need to get the frames from the webcam stream, we do this using the read() function. We use it in infinite loop to get all the frames until the time we want to close the stream.<br><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>while True:\n    # Capture frame-by-frame\n    ret, frame = video_capture.read()<\/code><\/pre>\n\n\n\n<p>The read() function returns:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>The actual video frame read (one frame on each loop)<\/li>\n\n\n\n<li>A return code<\/li>\n<\/ol>\n\n\n\n<p>The return code tells us if we have run out of frames, which will happen if we are reading from a file. This doesn\u2019t matter when reading from the webcam since we can record forever, so we will ignore it.<\/p>\n\n\n\n<p>For this specific classifier to work, we need to convert the frame into greyscale.<br><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)<\/code><\/pre>\n\n\n\n<p>The faceCascade object has a method detectMultiScale(), which receives a frame(image) as an argument and runs the classifier cascade over the image. The term MultiScale indicates that the algorithm looks at subregions of the image in multiple scales, to detect faces of varying sizes.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>  faces = faceCascade.detectMultiScale(gray,\n                                         scaleFactor=1.1,\n                                         minNeighbors=5,\n                                         minSize=(60, 60),\n                                         flags=cv2.CASCADE_SCALE_IMAGE)<\/code><\/pre>\n\n\n\n<p>Let us go through these arguments of this function:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>scaleFactor \u2013 Parameter specifying how much the image size is reduced at each image scale. By rescaling the input image, you can resize a larger face to a smaller one, making it detectable by the algorithm. 1.05 is a good possible value for this, which means you use a small step for resizing, i.e. reduce the size by 5%, you increase the chance of a matching size with the model for detection is found.<\/li>\n\n\n\n<li>minNeighbors \u2013 Parameter specifying how many neighbors each candidate rectangle should have to retain it. This parameter will affect the quality of the detected faces. Higher value results in fewer detections but with higher quality. 3~6 is a good value for it.<\/li>\n\n\n\n<li>flags \u2013Mode of operation<\/li>\n\n\n\n<li>minSize \u2013 Minimum possible object size. Objects smaller than that are ignored.<\/li>\n<\/ul>\n\n\n\n<p>The variable faces now contain all the detections for the target image. Detections are saved as pixel coordinates. Each detection is defined by its top-left corner coordinates and the width and height of the rectangle that encompasses the detected face.<br><\/p>\n\n\n\n<p>To show the detected face, we will draw a rectangle over it.OpenCV\u2019s rectangle() draws rectangles over images, and it needs to know the pixel coordinates of the top-left and bottom-right corners. The coordinates indicate the row and column of pixels in the image. We can easily get these coordinates from the variable face.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>for (x,y,w,h) in faces:\n        cv2.rectangle(frame, (x, y), (x + w, y + h),(0,255,0), 2)<\/code><\/pre>\n\n\n\n<p>rectangle() accepts the following arguments:<br><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The original image<\/li>\n\n\n\n<li>The coordinates of the top-left point of the detection<\/li>\n\n\n\n<li>The coordinates of the bottom-right point of the detection<\/li>\n\n\n\n<li>The colour of the rectangle (a tuple that defines the amount of red, green, and blue (0-255)).In our case, we set as green just keeping the green component as 255 and rest as zero.<\/li>\n\n\n\n<li>The thickness of the rectangle lines<\/li>\n<\/ul>\n\n\n\n<p>Next, we just display the resulting frame and also set a way to exit this infinite loop and close the video feed. By pressing the \u2018q\u2019 key, we can exit the script here<br><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code> cv2.imshow('Video', frame)\n    if cv2.waitKey(1) &amp; 0xFF == ord('q'):\n        break<\/code><\/pre>\n\n\n\n<p>The next two lines are just to clean up and release the picture.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>video_capture.release()\ncv2.destroyAllWindows()<\/code><\/pre>\n\n\n\n<p>Here are the full code and output.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport cv2\nimport os\ncascPath = os.path.dirname(\n    cv2.__file__) + &quot;\/data\/haarcascade_frontalface_alt2.xml&quot;\nfaceCascade = cv2.CascadeClassifier(cascPath)\nvideo_capture = cv2.VideoCapture(0)\nwhile True:\n    # Capture frame-by-frame\n    ret, frame = video_capture.read()\n    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n    faces = faceCascade.detectMultiScale(gray,\n                                         scaleFactor=1.1,\n                                         minNeighbors=5,\n                                         minSize=(60, 60),\n                                         flags=cv2.CASCADE_SCALE_IMAGE)\n    for (x,y,w,h) in faces:\n        cv2.rectangle(frame, (x, y), (x + w, y + h),(0,255,0), 2)\n        # Display the resulting frame\n    cv2.imshow(&#039;Video&#039;, frame)\n    if cv2.waitKey(1) &amp; 0xFF == ord(&#039;q&#039;):\n        break\nvideo_capture.release()\ncv2.destroyAllWindows()\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"create-a-model-to-recognize-faces-wearing-a-mask\"><strong>Create a model to recognize faces wearing a mask <\/strong><\/h2>\n\n\n\n<p>In this section, we are going to make a classifier that can differentiate between faces with masks and without masks. In case you want to skip this part, here is a <a aria-label=\"link (opens in a new tab)\" href=\"https:\/\/drive.google.com\/file\/d\/16uMH4YwdkA8sdnMlJNE7nv_tBJkX5eNe\/view?usp=sharing\" target=\"_blank\" rel=\"nofollow noreferrer noopener\">link<\/a> to download the pre-trained model. Save it and move on to the next section to know how to use it to detect masks using OpenCV. Check out our collection of <a href=\"https:\/\/www.mygreatlearning.com\/opencv\/free-courses\" target=\"_blank\" rel=\"noreferrer noopener\">OpenCV courses<\/a> to help you develop your skills and understand better.<\/p>\n\n\n\n<p>So for creating this classifier, we need data in the form of Images. Luckily we have a dataset containing images faces with mask and without a mask. Since these images are very less in number, we cannot train a neural network from scratch. Instead, we finetune a pre-trained network called MobileNetV2 which is trained on the Imagenet dataset.<\/p>\n\n\n\n<p>Let us first import all the necessary libraries we are going to need.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import MobileNetV2\nfrom tensorflow.keras.layers import AveragePooling2D\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import Input\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input\nfrom tensorflow.keras.preprocessing.image import img_to_array\nfrom tensorflow.keras.preprocessing.image import load_img\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.model_selection import train_test_split\nfrom imutils import paths\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os<\/code><\/pre>\n\n\n\n<p>The next step is to read all the images and assign them to some list. Here we get all the paths associated with these images and then label them accordingly. Remember our dataset is contained in two folders viz- with_masks and without_masks. So we can easily get the labels by extracting the folder name from the path. Also, we preprocess the image and resize it to 224x 224 dimensions.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>imagePaths = list(paths.list_images('\/content\/drive\/My Drive\/dataset'))\ndata = &#91;]\nlabels = &#91;]\n# loop over the image paths\nfor imagePath in imagePaths:\n\t# extract the class label from the filename\n\tlabel = imagePath.split(os.path.sep)&#91;-2]\n\t# load the input image (224x224) and preprocess it\n\timage = load_img(imagePath, target_size=(224, 224))\n\timage = img_to_array(image)\n\timage = preprocess_input(image)\n\t# update the data and labels lists, respectively\n\tdata.append(image)\n\tlabels.append(label)\n# convert the data and labels to NumPy arrays\ndata = np.array(data, dtype=\"float32\")\nlabels = np.array(labels)<\/code><\/pre>\n\n\n\n<p>The next step is to load the pre-trained model and customize it according to our problem. So we just remove the top layers of this pre-trained model and add few layers of our own. As you can see the last layer has two nodes as we have only two outputs. This is called transfer learning.<br><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>baseModel = MobileNetV2(weights=\"imagenet\", include_top=False,\n\tinput_shape=(224, 224, 3))\n# construct the head of the model that will be placed on top of the\n# the base model\nheadModel = baseModel.output\nheadModel = AveragePooling2D(pool_size=(7, 7))(headModel)\nheadModel = Flatten(name=\"flatten\")(headModel)\nheadModel = Dense(128, activation=\"relu\")(headModel)\nheadModel = Dropout(0.5)(headModel)\nheadModel = Dense(2, activation=\"softmax\")(headModel)\n\n# place the head FC model on top of the base model (this will become\n# the actual model we will train)\nmodel = Model(inputs=baseModel.input, outputs=headModel)\n# loop over all layers in the base model and freeze them so they will\n# *not* be updated during the first training process\nfor layer in baseModel.layers:\n\tlayer.trainable = False<\/code><\/pre>\n\n\n\n<p>Now we need to convert the labels into one-hot encoding. After that, we split the data into training and testing sets to evaluate them. Also, the next step is data augmentation which significantly increases the diversity of data available for training models, without actually collecting new data. Data augmentation techniques such as cropping, rotation, shearing and horizontal flipping are commonly used to train large neural networks.<br><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>lb = LabelBinarizer()\nlabels = lb.fit_transform(labels)\nlabels = to_categorical(labels)\n# partition the data into training and testing splits using 80% of\n# the data for training and the remaining 20% for testing\n(trainX, testX, trainY, testY) = train_test_split(data, labels,\n\ttest_size=0.20, stratify=labels, random_state=42)\n# construct the training image generator for data augmentation\naug = ImageDataGenerator(\n\trotation_range=20,\n\tzoom_range=0.15,\n\twidth_shift_range=0.2,\n\theight_shift_range=0.2,\n\tshear_range=0.15,\n\thorizontal_flip=True,\n\tfill_mode=\"nearest\")<\/code><\/pre>\n\n\n\n<p>The next step is to compile the model and train it on the augmented data.<br><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>INIT_LR = 1e-4\nEPOCHS = 20\nBS = 32\nprint(\"&#91;INFO] compiling model...\")\nopt = Adam(lr=INIT_LR, decay=INIT_LR \/ EPOCHS)\nmodel.compile(loss=\"binary_crossentropy\", optimizer=opt,\n\tmetrics=&#91;\"accuracy\"])\n# train the head of the network\nprint(\"&#91;INFO] training head...\")\nH = model.fit(\n\taug.flow(trainX, trainY, batch_size=BS),\n\tsteps_per_epoch=len(trainX) \/\/ BS,\n\tvalidation_data=(testX, testY),\n\tvalidation_steps=len(testX) \/\/ BS,\n\tepochs=EPOCHS)<\/code><\/pre>\n\n\n\n<p>Now that our model is trained, let us plot a graph to see its learning curve. Also, we save the model for later use. Here is a<a href=\"https:\/\/drive.google.com\/file\/d\/16uMH4YwdkA8sdnMlJNE7nv_tBJkX5eNe\/view?usp=sharing\" target=\"_blank\" rel=\"nofollow noreferrer noopener\" aria-label=\" link (opens in a new tab)\"> link<\/a> to this trained model.<br><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>N = EPOCHS\nplt.style.use(\"ggplot\")\nplt.figure()\nplt.plot(np.arange(0, N), H.history&#91;\"loss\"], label=\"train_loss\")\nplt.plot(np.arange(0, N), H.history&#91;\"val_loss\"], label=\"val_loss\")\nplt.plot(np.arange(0, N), H.history&#91;\"accuracy\"], label=\"train_acc\")\nplt.plot(np.arange(0, N), H.history&#91;\"val_accuracy\"], label=\"val_acc\")\nplt.title(\"Training Loss and Accuracy\")\nplt.xlabel(\"Epoch #\")\nplt.ylabel(\"Loss\/Accuracy\")\nplt.legend(loc=\"lower left\")<\/code><\/pre>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n<figure class=\"wp-block-image size-large is-resized zoomable\" data-full=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/07\/download.png\"><img decoding=\"async\" width=\"389\" height=\"282\" src=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/07\/download.png\" alt=\"face detection\" class=\"wp-image-17587\" style=\"width:473px;height:343px\" srcset=\"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/07\/download.png 389w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/07\/download-300x217.png 300w, https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/07\/download-324x235.png 324w\" sizes=\"(max-width: 389px) 100vw, 389px\" \/><\/figure>\n\n\n\n<pre class=\"wp-block-code\"><code>#To save the trained model\nmodel.save('mask_recog_ver2.h5')<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"how-to-do-real-time-mask-detection\"><strong>How to do Real-time Mask detection&nbsp;<\/strong><br><\/h2>\n\n\n\n<p>Before moving to the next part, make sure to download the above model from this <a href=\"https:\/\/drive.google.com\/file\/d\/16uMH4YwdkA8sdnMlJNE7nv_tBJkX5eNe\/view?usp=sharing\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">link<\/a> and place it in the same folder as the python script you are going to write the below code in. <\/p>\n\n\n\n<p>Now that our model is trained, we can modify the code in the first section so that it can detect faces and also tell us if the person is wearing a mask or not.<\/p>\n\n\n\n<p>In order for our mask detector model to work, it needs images of faces. For this, we will detect the frames with faces using the methods as shown in the first section and then pass them to our model after preprocessing them. So let us first import all the libraries we need.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import cv2\nimport os\nfrom tensorflow.keras.preprocessing.image import img_to_array\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input\nimport numpy as np<\/code><\/pre>\n\n\n\n<p>The first few lines are exactly the same as the first section. The only thing that is different is that we have assigned our pre-trained mask detector model to the variable model.<br><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>ascPath = os.path.dirname(\n    cv2.__file__) + \"\/data\/haarcascade_frontalface_alt2.xml\"\nfaceCascade = cv2.CascadeClassifier(cascPath)\nmodel = load_model(\"mask_recog1.h5\")\n\nvideo_capture = cv2.VideoCapture(0)\nwhile True:\n    # Capture frame-by-frame\n    ret, frame = video_capture.read()\n    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n    faces = faceCascade.detectMultiScale(gray,\n                                         scaleFactor=1.1,\n                                         minNeighbors=5,\n                                         minSize=(60, 60),\n                                         flags=cv2.CASCADE_SCALE_IMAGE)<\/code><\/pre>\n\n\n\n<p>Next, we define some lists. The faces_list contains all the faces that are detected by the faceCascade model and the preds list is used to store the predictions made by the mask detector model.<br><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>faces_list=&#91;]\npreds=&#91;]<\/code><\/pre>\n\n\n\n<p>Also since the faces variable contains the top-left corner coordinates, height and width of the rectangle encompassing the faces, we can use that to get a frame of the face and then preprocess that frame so that it can be fed into the model for prediction. The preprocessing steps are same that are followed when training the model in the second section. For example, the model is trained on RGB images so we convert the image into RGB here<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    for (x, y, w, h) in faces:\n        face_frame = frame&#91;y:y+h,x:x+w]\n        face_frame = cv2.cvtColor(face_frame, cv2.COLOR_BGR2RGB)\n        face_frame = cv2.resize(face_frame, (224, 224))\n        face_frame = img_to_array(face_frame)\n        face_frame = np.expand_dims(face_frame, axis=0)\n        face_frame =  preprocess_input(face_frame)\n        faces_list.append(face_frame)\n        if len(faces_list)&gt;0:\n            preds = model.predict(faces_list)\n        for pred in preds:\n        #mask contain probabily of wearing a mask and vice versa\n            (mask, withoutMask) = pred <\/code><\/pre>\n\n\n\n<p>After getting the predictions, we draw a rectangle over the face and put a label according to the predictions.<br><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>label = \"Mask\" if mask &gt; withoutMask else \"No Mask\"\n        color = (0, 255, 0) if label == \"Mask\" else (0, 0, 255)\n        label = \"{}: {:.2f}%\".format(label, max(mask, withoutMask) * 100)\n        cv2.putText(frame, label, (x, y- 10),\n                    cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2)\n\n        cv2.rectangle(frame, (x, y), (x + w, y + h),color, 2)<\/code><\/pre>\n\n\n\n<p>The rest of the steps are the same as the first section.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>cv2.imshow('Video', frame)\n    if cv2.waitKey(1) &amp; 0xFF == ord('q'):\n        break\nvideo_capture.release()\ncv2.destroyAllWindows()<\/code><\/pre>\n\n\n\n<p>Here is the complete code and output:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport cv2\nimport os\nfrom tensorflow.keras.preprocessing.image import img_to_array\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input\nimport numpy as np\n\ncascPath = os.path.dirname(\n    cv2.__file__) + &quot;\/data\/haarcascade_frontalface_alt2.xml&quot;\nfaceCascade = cv2.CascadeClassifier(cascPath)\nmodel = load_model(&quot;mask_recog1.h5&quot;)\n\nvideo_capture = cv2.VideoCapture(0)\nwhile True:\n    # Capture frame-by-frame\n    ret, frame = video_capture.read()\n    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n    faces = faceCascade.detectMultiScale(gray,\n                                         scaleFactor=1.1,\n                                         minNeighbors=5,\n                                         minSize=(60, 60),\n                                         flags=cv2.CASCADE_SCALE_IMAGE)\n    faces_list=&#x5B;]\n    preds=&#x5B;]\n    for (x, y, w, h) in faces:\n        face_frame = frame&#x5B;y:y+h,x:x+w]\n        face_frame = cv2.cvtColor(face_frame, cv2.COLOR_BGR2RGB)\n        face_frame = cv2.resize(face_frame, (224, 224))\n        face_frame = img_to_array(face_frame)\n        face_frame = np.expand_dims(face_frame, axis=0)\n        face_frame =  preprocess_input(face_frame)\n        faces_list.append(face_frame)\n        if len(faces_list)&gt;0:\n            preds = model.predict(faces_list)\n        for pred in preds:\n            (mask, withoutMask) = pred\n        label = &quot;Mask&quot; if mask &gt; withoutMask else &quot;No Mask&quot;\n        color = (0, 255, 0) if label == &quot;Mask&quot; else (0, 0, 255)\n        label = &quot;{}: {:.2f}%&quot;.format(label, max(mask, withoutMask) * 100)\n        cv2.putText(frame, label, (x, y- 10),\n                    cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2)\n\n        cv2.rectangle(frame, (x, y), (x + w, y + h),color, 2)\n        # Display the resulting frame\n    cv2.imshow(&#039;Video&#039;, frame)\n    if cv2.waitKey(1) &amp; 0xFF == ord(&#039;q&#039;):\n        break\nvideo_capture.release()\ncv2.destroyAllWindows()\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<p>This brings us to the end of this article where we learned how to detect faces in real-time and also designed a model that can detect faces with masks. Using this model we were able to modify the face detector to mask detector.<\/p>\n\n\n\n<p><strong>Update<\/strong>: I trained another model which can classify images into wearing a mask, not wearing a mask and not properly wearing a mask. Here is a link of the <a href=\"https:\/\/www.kaggle.com\/mirzamujtaba\/face-mask-detection\" target=\"_blank\" rel=\"nofollow noreferrer noopener\" aria-label=\"Kaggle notebook (opens in a new tab)\">Kaggle notebook<\/a> of this model. You can modify it and also download the model from there and use it in instead of the model we trained in this article. Although this model is not as efficient as the model we trained here, it has an extra feature of detecting not properly worn masks.<\/p>\n\n\n\n<p>If you are using this model you need to make some minor changes to the code. Replace the previous lines with these lines.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#Here are some minor changes in opencv code\nfor (box, pred) in zip(locs, preds):\n        # unpack the bounding box and predictions\n        (startX, startY, endX, endY) = box\n        (mask, withoutMask,notproper) = pred\n\n        # determine the class label and color we'll use to draw\n        # the bounding box and text\n        if (mask &gt; withoutMask and mask&gt;notproper):\n            label = \"Without Mask\"\n        elif ( withoutMask &gt; notproper and withoutMask &gt; mask):\n            label = \"Mask\"\n        else:\n            label = \"Wear Mask Properly\"\n\n        if label == \"Mask\":\n            color = (0, 255, 0)\n        elif label==\"Without Mask\":\n            color = (0, 0, 255)\n        else:\n            color = (255, 140, 0)\n\n        # include the probability in the label\n        label = \"{}: {:.2f}%\".format(label,\n                                     max(mask, withoutMask, notproper) * 100)\n\n        # display the label and bounding box rectangle on the output\n        # frame\n        cv2.putText(frame, label, (startX, startY - 10),\n                    cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2)\n        cv2.rectangle(frame, (startX, startY), (endX, endY), color, 2)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"how-to-get-started-with-learning-real-time-face-detection-face-mask-detection-using-opencv\"><strong>How to Get Started with Learning Real-time Face Detection &amp; Face Mask Detection Using OpenCV?<\/strong><\/h3>\n\n\n\n<p>If you're interested in diving into real-time face detection and face mask detection using OpenCV, Great Learning offers specialized courses designed to help you gain hands-on experience with these critical AI technologies. OpenCV, a popular open-source computer vision library, is widely used for real-time image processing and AI applications, including face detection and facial recognition tasks.<\/p>\n\n\n\n<p>Here\u2019s how you can get started with learning these exciting AI technologies through Great Learning:<\/p>\n\n\n\n<p>1. <strong>Explore Specialized AI Courses in Computer Vision:<\/strong><br>Great Learning\u2019s <strong><a href=\"https:\/\/www.mygreatlearning.com\/artificial-intelligence\/courses\">AI and Machine Learning courses<\/a><\/strong> include detailed modules on Computer Vision using OpenCV, where you\u2019ll learn how to implement real-time face detection and face mask detection systems. These technologies are especially important in sectors like security, healthcare, and retail, and are gaining significant attention in today\u2019s AI landscape.<\/p>\n\n\n\n<p>2. <strong>Hands-On Projects with OpenCV:<\/strong><br>Gain practical experience by working on projects that focus on real-time face detection and face mask detection. You'll use OpenCV to build applications that can detect faces in images and videos, as well as identify whether individuals are wearing face masks. These projects will enhance your understanding of AI's role in image processing and computer vision.<\/p>\n\n\n\n<p>3. <strong>Get Personalized Mentorship:<\/strong><br>With <strong><a href=\"https:\/\/www.mygreatlearning.com\/artificial-intelligence\/courses\">Great Learning's AI courses<\/a><\/strong>, you\u2019ll receive personalized guidance from dedicated Program Managers. They\u2019ll support you throughout your learning process, ensuring that you gain the expertise needed to implement real-time face and mask detection systems successfully.<\/p>\n\n\n\n<p>4. <strong>Earn Accredited Certifications:<\/strong><br>Upon completion, you\u2019ll receive an accredited certification that validates your skills in computer vision and AI, making you more attractive to potential employers. The certification will also demonstrate your proficiency in using OpenCV and developing real-time detection applications.<\/p>\n\n\n\n<p>5. <strong>Learn from Experts:<\/strong><br>Great Learning\u2019s expert instructors, who bring the latest AI and computer vision trends to their teaching, will help you grasp complex concepts. Learn how to work with deep learning techniques, facial recognition models, and object detection frameworks within OpenCV.<\/p>\n\n\n\n<p>By enrolling in <strong>Great Learning\u2019s AI courses<\/strong>, you can quickly master the art of <strong>real-time face detection<\/strong> and <strong>face mask detection<\/strong> using OpenCV and gain valuable skills in computer vision that are in high demand across various industries. Start your AI learning journey today and open doors to exciting career opportunities in the world of artificial intelligence.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"conclusion\">Conclusion<\/h2>\n\n\n\n<p>You can also upskill with Great Learning's <a href=\"https:\/\/www.mygreatlearning.com\/pg-program-artificial-intelligence-course\" target=\"_blank\" rel=\"noreferrer noopener\">PGP Artificial Intelligence and Machine Learning Course<\/a>. The course offers mentorship from industry leaders, and you will also have the opportunity to work on real-time industry-relevant projects.<\/p>\n\n\n\n<p>Looking to upskill or explore a new field without breaking the bank? Our <a href=\"https:\/\/www.mygreatlearning.com\/academy\" target=\"_blank\" rel=\"noreferrer noopener\">free online courses<\/a> are the perfect solution. Dive into the exciting realms of Cybersecurity, Management, Cloud Computing, IT, and Software, Artificial intelligence and acquire the knowledge that can set you apart. Whether you're a tech enthusiast, an aspiring entrepreneur, or simply curious about the digital landscape, our courses offer a flexible and accessible way to learn.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"further-reading\">Further Reading<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.mygreatlearning.com\/blog\/object-detection-using-tensorflow\/\">Real-Time Object Detection Using TensorFlow<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/www.mygreatlearning.com\/blog\/yolo-object-detection-using-opencv\/\">YOLO object detection using OpenCV<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/www.mygreatlearning.com\/blog\/object-detection-in-pytorch\/\">Object Detection in Pytorch | What is Object Detection?<\/a><\/li>\n<\/ol>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we are going to find out how to detect faces in real-time using OpenCV. After detecting the face from the webcam stream, we are going to save the frames containing the face. Later we will pass these frames (images) to our mask detector classifier to find out if the person is wearing [&hellip;]<\/p>\n","protected":false},"author":41,"featured_media":17597,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"_uag_custom_page_level_css":"","site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"set","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[2],"tags":[],"content_type":[],"class_list":["post-17581","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-artificial-intelligence"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v27.3 (Yoast SEO v27.3) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>Face Recognition | Real Time Face Recognition OpenCV | Great Learning<\/title>\n<meta name=\"description\" content=\"Face Recognition: In This article we learn real time face detection and then use a mask classifier to detect faces wearing masks in live stream from webcam.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.mygreatlearning.com\/blog\/real-time-face-detection\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Real-time Face detection | Face Mask Detection using OpenCV\" \/>\n<meta property=\"og:description\" content=\"Face Recognition: In This article we learn real time face detection and then use a mask classifier to detect faces wearing masks in live stream from webcam.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.mygreatlearning.com\/blog\/real-time-face-detection\/\" \/>\n<meta property=\"og:site_name\" content=\"Great Learning Blog: Free Resources what Matters to shape your Career!\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/GreatLearningOfficial\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-06-09T13:01:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-11T08:07:15+00:00\" \/>\n<meta property=\"og:image\" content=\"http:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/07\/kate-trifo-6Ps0pMoln_A-unsplash1-min.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"2666\" \/>\n\t<meta property=\"og:image:height\" content=\"1500\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Great Learning Editorial Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/Great_Learning\" \/>\n<meta name=\"twitter:site\" content=\"@Great_Learning\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Great Learning Editorial Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"14 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/real-time-face-detection\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/real-time-face-detection\\\/\"},\"author\":{\"name\":\"Great Learning Editorial Team\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#\\\/schema\\\/person\\\/6f993d1be4c584a335951e836f2656ad\"},\"headline\":\"Real-time Face detection | Face Mask Detection using OpenCV\",\"datePublished\":\"2023-06-09T13:01:00+00:00\",\"dateModified\":\"2024-11-11T08:07:15+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/real-time-face-detection\\\/\"},\"wordCount\":3077,\"commentCount\":2,\"publisher\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/real-time-face-detection\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2020\\\/07\\\/kate-trifo-6Ps0pMoln_A-unsplash1-min.jpg\",\"articleSection\":[\"AI and Machine Learning\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/real-time-face-detection\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/real-time-face-detection\\\/\",\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/real-time-face-detection\\\/\",\"name\":\"Face Recognition | Real Time Face Recognition OpenCV | Great Learning\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/real-time-face-detection\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/real-time-face-detection\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2020\\\/07\\\/kate-trifo-6Ps0pMoln_A-unsplash1-min.jpg\",\"datePublished\":\"2023-06-09T13:01:00+00:00\",\"dateModified\":\"2024-11-11T08:07:15+00:00\",\"description\":\"Face Recognition: In This article we learn real time face detection and then use a mask classifier to detect faces wearing masks in live stream from webcam.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/real-time-face-detection\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/real-time-face-detection\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/real-time-face-detection\\\/#primaryimage\",\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2020\\\/07\\\/kate-trifo-6Ps0pMoln_A-unsplash1-min.jpg\",\"contentUrl\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2020\\\/07\\\/kate-trifo-6Ps0pMoln_A-unsplash1-min.jpg\",\"width\":2666,\"height\":1500},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/real-time-face-detection\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Blog\",\"item\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"AI and Machine Learning\",\"item\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/artificial-intelligence\\\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Real-time Face detection | Face Mask Detection using OpenCV\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/\",\"name\":\"Great Learning Blog\",\"description\":\"Learn, Upskill &amp; Career Development Guide and Resources\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#organization\"},\"alternateName\":\"Great Learning\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#organization\",\"name\":\"Great Learning\",\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/GL-Logo.jpg\",\"contentUrl\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/GL-Logo.jpg\",\"width\":900,\"height\":900,\"caption\":\"Great Learning\"},\"image\":{\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/GreatLearningOfficial\\\/\",\"https:\\\/\\\/x.com\\\/Great_Learning\",\"https:\\\/\\\/www.instagram.com\\\/greatlearningofficial\\\/\",\"https:\\\/\\\/www.linkedin.com\\\/school\\\/great-learning\\\/\",\"https:\\\/\\\/in.pinterest.com\\\/greatlearning12\\\/\",\"https:\\\/\\\/www.youtube.com\\\/user\\\/beaconelearning\\\/\"],\"description\":\"Great Learning is a leading global ed-tech company for professional training and higher education. It offers comprehensive, industry-relevant, hands-on learning programs across various business, technology, and interdisciplinary domains driving the digital economy. These programs are developed and offered in collaboration with the world's foremost academic institutions.\",\"email\":\"info@mygreatlearning.com\",\"legalName\":\"Great Learning Education Services Pvt. Ltd\",\"foundingDate\":\"2013-11-29\",\"numberOfEmployees\":{\"@type\":\"QuantitativeValue\",\"minValue\":\"1001\",\"maxValue\":\"5000\"}},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/#\\\/schema\\\/person\\\/6f993d1be4c584a335951e836f2656ad\",\"name\":\"Great Learning Editorial Team\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2022\\\/02\\\/unnamed.webp\",\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2022\\\/02\\\/unnamed.webp\",\"contentUrl\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/wp-content\\\/uploads\\\/2022\\\/02\\\/unnamed.webp\",\"caption\":\"Great Learning Editorial Team\"},\"description\":\"The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.\",\"sameAs\":[\"https:\\\/\\\/www.mygreatlearning.com\\\/\",\"https:\\\/\\\/in.linkedin.com\\\/school\\\/great-learning\\\/\",\"https:\\\/\\\/x.com\\\/https:\\\/\\\/twitter.com\\\/Great_Learning\",\"https:\\\/\\\/www.youtube.com\\\/channel\\\/UCObs0kLIrDjX2LLSybqNaEA\"],\"award\":[\"Best EdTech Company of the Year 2024\",\"Education Economictimes Outstanding Education\\\/Edtech Solution Provider of the Year 2024\",\"Leading E-learning Platform 2024\"],\"url\":\"https:\\\/\\\/www.mygreatlearning.com\\\/blog\\\/author\\\/greatlearning\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Face Recognition | Real Time Face Recognition OpenCV | Great Learning","description":"Face Recognition: In This article we learn real time face detection and then use a mask classifier to detect faces wearing masks in live stream from webcam.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.mygreatlearning.com\/blog\/real-time-face-detection\/","og_locale":"en_US","og_type":"article","og_title":"Real-time Face detection | Face Mask Detection using OpenCV","og_description":"Face Recognition: In This article we learn real time face detection and then use a mask classifier to detect faces wearing masks in live stream from webcam.","og_url":"https:\/\/www.mygreatlearning.com\/blog\/real-time-face-detection\/","og_site_name":"Great Learning Blog: Free Resources what Matters to shape your Career!","article_publisher":"https:\/\/www.facebook.com\/GreatLearningOfficial\/","article_published_time":"2023-06-09T13:01:00+00:00","article_modified_time":"2024-11-11T08:07:15+00:00","og_image":[{"width":2666,"height":1500,"url":"http:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/07\/kate-trifo-6Ps0pMoln_A-unsplash1-min.jpg","type":"image\/jpeg"}],"author":"Great Learning Editorial Team","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/Great_Learning","twitter_site":"@Great_Learning","twitter_misc":{"Written by":"Great Learning Editorial Team","Est. reading time":"14 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.mygreatlearning.com\/blog\/real-time-face-detection\/#article","isPartOf":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/real-time-face-detection\/"},"author":{"name":"Great Learning Editorial Team","@id":"https:\/\/www.mygreatlearning.com\/blog\/#\/schema\/person\/6f993d1be4c584a335951e836f2656ad"},"headline":"Real-time Face detection | Face Mask Detection using OpenCV","datePublished":"2023-06-09T13:01:00+00:00","dateModified":"2024-11-11T08:07:15+00:00","mainEntityOfPage":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/real-time-face-detection\/"},"wordCount":3077,"commentCount":2,"publisher":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/#organization"},"image":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/real-time-face-detection\/#primaryimage"},"thumbnailUrl":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/07\/kate-trifo-6Ps0pMoln_A-unsplash1-min.jpg","articleSection":["AI and Machine Learning"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.mygreatlearning.com\/blog\/real-time-face-detection\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.mygreatlearning.com\/blog\/real-time-face-detection\/","url":"https:\/\/www.mygreatlearning.com\/blog\/real-time-face-detection\/","name":"Face Recognition | Real Time Face Recognition OpenCV | Great Learning","isPartOf":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/real-time-face-detection\/#primaryimage"},"image":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/real-time-face-detection\/#primaryimage"},"thumbnailUrl":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/07\/kate-trifo-6Ps0pMoln_A-unsplash1-min.jpg","datePublished":"2023-06-09T13:01:00+00:00","dateModified":"2024-11-11T08:07:15+00:00","description":"Face Recognition: In This article we learn real time face detection and then use a mask classifier to detect faces wearing masks in live stream from webcam.","breadcrumb":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/real-time-face-detection\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.mygreatlearning.com\/blog\/real-time-face-detection\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.mygreatlearning.com\/blog\/real-time-face-detection\/#primaryimage","url":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/07\/kate-trifo-6Ps0pMoln_A-unsplash1-min.jpg","contentUrl":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/07\/kate-trifo-6Ps0pMoln_A-unsplash1-min.jpg","width":2666,"height":1500},{"@type":"BreadcrumbList","@id":"https:\/\/www.mygreatlearning.com\/blog\/real-time-face-detection\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog","item":"https:\/\/www.mygreatlearning.com\/blog\/"},{"@type":"ListItem","position":2,"name":"AI and Machine Learning","item":"https:\/\/www.mygreatlearning.com\/blog\/artificial-intelligence\/"},{"@type":"ListItem","position":3,"name":"Real-time Face detection | Face Mask Detection using OpenCV"}]},{"@type":"WebSite","@id":"https:\/\/www.mygreatlearning.com\/blog\/#website","url":"https:\/\/www.mygreatlearning.com\/blog\/","name":"Great Learning Blog","description":"Learn, Upskill &amp; Career Development Guide and Resources","publisher":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/#organization"},"alternateName":"Great Learning","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.mygreatlearning.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.mygreatlearning.com\/blog\/#organization","name":"Great Learning","url":"https:\/\/www.mygreatlearning.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.mygreatlearning.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2022\/06\/GL-Logo.jpg","contentUrl":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2022\/06\/GL-Logo.jpg","width":900,"height":900,"caption":"Great Learning"},"image":{"@id":"https:\/\/www.mygreatlearning.com\/blog\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/GreatLearningOfficial\/","https:\/\/x.com\/Great_Learning","https:\/\/www.instagram.com\/greatlearningofficial\/","https:\/\/www.linkedin.com\/school\/great-learning\/","https:\/\/in.pinterest.com\/greatlearning12\/","https:\/\/www.youtube.com\/user\/beaconelearning\/"],"description":"Great Learning is a leading global ed-tech company for professional training and higher education. It offers comprehensive, industry-relevant, hands-on learning programs across various business, technology, and interdisciplinary domains driving the digital economy. These programs are developed and offered in collaboration with the world's foremost academic institutions.","email":"info@mygreatlearning.com","legalName":"Great Learning Education Services Pvt. Ltd","foundingDate":"2013-11-29","numberOfEmployees":{"@type":"QuantitativeValue","minValue":"1001","maxValue":"5000"}},{"@type":"Person","@id":"https:\/\/www.mygreatlearning.com\/blog\/#\/schema\/person\/6f993d1be4c584a335951e836f2656ad","name":"Great Learning Editorial Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2022\/02\/unnamed.webp","url":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2022\/02\/unnamed.webp","contentUrl":"https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2022\/02\/unnamed.webp","caption":"Great Learning Editorial Team"},"description":"The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.","sameAs":["https:\/\/www.mygreatlearning.com\/","https:\/\/in.linkedin.com\/school\/great-learning\/","https:\/\/x.com\/https:\/\/twitter.com\/Great_Learning","https:\/\/www.youtube.com\/channel\/UCObs0kLIrDjX2LLSybqNaEA"],"award":["Best EdTech Company of the Year 2024","Education Economictimes Outstanding Education\/Edtech Solution Provider of the Year 2024","Leading E-learning Platform 2024"],"url":"https:\/\/www.mygreatlearning.com\/blog\/author\/greatlearning\/"}]}},"uagb_featured_image_src":{"full":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/07\/kate-trifo-6Ps0pMoln_A-unsplash1-min.jpg",2666,1500,false],"thumbnail":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/07\/kate-trifo-6Ps0pMoln_A-unsplash1-min-150x150.jpg",150,150,true],"medium":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/07\/kate-trifo-6Ps0pMoln_A-unsplash1-min-300x169.jpg",300,169,true],"medium_large":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/07\/kate-trifo-6Ps0pMoln_A-unsplash1-min-768x432.jpg",768,432,true],"large":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/07\/kate-trifo-6Ps0pMoln_A-unsplash1-min-1024x576.jpg",1024,576,true],"1536x1536":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/07\/kate-trifo-6Ps0pMoln_A-unsplash1-min-1536x864.jpg",1536,864,true],"2048x2048":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/07\/kate-trifo-6Ps0pMoln_A-unsplash1-min-2048x1152.jpg",2048,1152,true],"web-stories-poster-portrait":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/07\/kate-trifo-6Ps0pMoln_A-unsplash1-min.jpg",640,360,false],"web-stories-publisher-logo":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/07\/kate-trifo-6Ps0pMoln_A-unsplash1-min.jpg",96,54,false],"web-stories-thumbnail":["https:\/\/www.mygreatlearning.com\/blog\/wp-content\/uploads\/2020\/07\/kate-trifo-6Ps0pMoln_A-unsplash1-min.jpg",150,84,false]},"uagb_author_info":{"display_name":"Great Learning Editorial Team","author_link":"https:\/\/www.mygreatlearning.com\/blog\/author\/greatlearning\/"},"uagb_comment_info":3,"uagb_excerpt":"In this article, we are going to find out how to detect faces in real-time using OpenCV. After detecting the face from the webcam stream, we are going to save the frames containing the face. Later we will pass these frames (images) to our mask detector classifier to find out if the person is wearing&hellip;","_links":{"self":[{"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/posts\/17581","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/users\/41"}],"replies":[{"embeddable":true,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/comments?post=17581"}],"version-history":[{"count":65,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/posts\/17581\/revisions"}],"predecessor-version":[{"id":105715,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/posts\/17581\/revisions\/105715"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/media\/17597"}],"wp:attachment":[{"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/media?parent=17581"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/categories?post=17581"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/tags?post=17581"},{"taxonomy":"content_type","embeddable":true,"href":"https:\/\/www.mygreatlearning.com\/blog\/wp-json\/wp\/v2\/content_type?post=17581"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}