Overlaying A Facemask

Detect Faces

  1.         // Capture the current frame
  2.         cap >> frame;
  3.  
  4.         // Resize the frame
  5.         resize(frame, frame, Size(), scalingFactor, scalingFactor, INTER_AREA);
  6.  
  7.         // Convert to grayscale
  8.         cvtColor(frame, frameGray, CV_BGR2GRAY);
  9.  
  10.         // Equalize the histogram
  11.         equalizeHist(frameGray, frameGray);
  12.  
  13.         // Detect faces
  14.         faceCascade.detectMultiScale(frameGray, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(30, 30) );

Add Mask Image

  1.         // Draw green rectangle around the face
  2.         for(int i = 0; i < faces.size(); i++)
  3.         {
  4.             //Rect faceRect(faces[i].x, faces[i].y, faces[i].width, faces[i].height);
  5.  
  6.             // Custom parameters to make the mask fit your face. You may have to play around with them to make sure it works.
  7.             int x = faces[i].x - int(0.1*faces[i].width);
  8.             int y = faces[i].y - int(0.1*faces[i].height); // 0.0*faces[i].height
  9.             int w = int(1.1 * faces[i].width);
  10.             int h = int(1.3 * faces[i].height);
  11.  
  12.             // Extract region of interest (ROI) covering your face
  13.             frameROI = frame(Rect(x,y,w,h));
  14.  
  15.             // Resize the face mask image based on the dimensions of the above ROI
  16.             resize(faceMask, faceMaskSmall, Size(w,h));
  17.  
  18.             // Convert the above image to grayscale
  19.             cvtColor(faceMaskSmall, grayMaskSmall, CV_BGR2GRAY);
  20.  
  21.             // Threshold the above image to isolate the pixels associated only with the face mask
  22.             threshold(grayMaskSmall, grayMaskSmallThresh, 230, 255, CV_THRESH_BINARY_INV);
  23.  
  24.             // Create mask by inverting the above image (because we don't want the background to affect the overlay)
  25.             bitwise_not(grayMaskSmallThresh, grayMaskSmallThreshInv);
  26.  
  27.             // Use bitwise "AND" operator to extract precise boundary of face mask
  28.             bitwise_and(faceMaskSmall, faceMaskSmall, maskedFace, grayMaskSmallThresh);
  29.  
  30.             // Use bitwise "AND" operator to overlay face mask
  31.             bitwise_and(frameROI, frameROI, maskedFrame, grayMaskSmallThreshInv);
  32.  
  33.             // Add the above masked images and place it in the original frame ROI to create the final image
  34.             add(maskedFace, maskedFrame, frame(Rect(x,y,w,h)));
  35.         }

Leave a Reply

Your email address will not be published. Required fields are marked *