Putting a mask on face using OpenCV

This is a example to put a mask on your face. This is a fun application that is meant to be used for entertainment purpose. You might have seen such apps in google hangouts.

Steps:
  1. Detect face from the input video frame
  2. Load the mask and make the white region of the mask transparent.
  3. Put the mask at the face position
  4. Display the image
Any mask can be used for this purpose. I have downloaded some masks from internet which you can download here.

Download masks

Put the mask images in a folder with folder name "masks" inside the project folder.

For achieving higher speed, the parameter are adjusted according to this.

Code:

------------
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

#include <iostream>
#include <stdio.h>

using namespace std;
using namespace cv;

double min_face_size=20;
double max_face_size=200;
Mat mask;

Mat detectFace(Mat src);
Mat putMask(Mat src,Point center,Size face_size);

int main( )
{
    VideoCapture cap(0);
    namedWindow( "window1", 1 );   
    mask = imread("masks/5.jpg");

    while(1)
    {
        Mat frame;
        cap >> frame;         
        frame=detectFace(frame);
        
        imshow( "window1", frame );
        // Press 'c' to escape
        if(waitKey(1) == 'c') break;        
    }

    waitKey(0);                  
    return 0;
}

Mat detectFace(Mat image)
{
    // Load Face cascade (.xml file)
    CascadeClassifier face_cascade( "C:/OpenCV243/data/Haarcascades/haarcascade_frontalface_alt2.xml" );

    // Detect faces
    std::vector<Rect> faces;

    face_cascade.detectMultiScale( image, faces, 1.2, 2, 0|CV_HAAR_SCALE_IMAGE, Size(min_face_size, min_face_size),Size(max_face_size, max_face_size) );
    
    // Draw circles on the detected faces
    for( int i = 0; i < faces.size(); i++ )
    {   // Lets only track the first face, i.e. face[0] 
        min_face_size = faces[0].width*0.7;
        max_face_size = faces[0].width*1.5;
        Point center( faces[i].x + faces[i].width*0.5, faces[i].y + faces[i].height*0.5 );        
        image=putMask(image,center,Size( faces[i].width, faces[i].height));
    }    
    return image;
}

Mat putMask(Mat src,Point center,Size face_size)
{
    Mat mask1,src1;
    resize(mask,mask1,face_size);    

    // ROI selection
     Rect roi(center.x - face_size.width/2, center.y - face_size.width/2, face_size.width, face_size.width);
    src(roi).copyTo(src1);

    // to make the white region transparent
    Mat mask2,m,m1;
    cvtColor(mask1,mask2,CV_BGR2GRAY);
    threshold(mask2,mask2,230,255,CV_THRESH_BINARY_INV); 

    vector<Mat> maskChannels(3),result_mask(3);
    split(mask1, maskChannels);
    bitwise_and(maskChannels[0],mask2,result_mask[0]);
    bitwise_and(maskChannels[1],mask2,result_mask[1]);
    bitwise_and(maskChannels[2],mask2,result_mask[2]);
    merge(result_mask,m );         //    imshow("m",m);

    mask2 = 255 - mask2;
    vector<Mat> srcChannels(3);
    split(src1, srcChannels);
    bitwise_and(srcChannels[0],mask2,result_mask[0]);
    bitwise_and(srcChannels[1],mask2,result_mask[1]);
    bitwise_and(srcChannels[2],mask2,result_mask[2]);
    merge(result_mask,m1 );        //    imshow("m1",m1);

    addWeighted(m,1,m1,1,0,m1);    //    imshow("m2",m1);
    
    m1.copyTo(src(roi));

    return src;
}
------------

Result:


57 comments:

  1. Thanks for good job. It is better if we consider the angle of face. And then the mask will roate with correspoding angle

    ReplyDelete

  2. الكثير منا يريد الانتقال من مكان الى مكان اخر اوسع او افخم او اقيم ولكن تظل الحسابات والمصاريف وعمليات النقل تؤثر على قرار الانتقال نظرا للمصاريف الباهظه ونظرا لعدم التفرغ للفك والتركيب والتغليف وهكذا ولكن اذا كنت تفكر فى الانتقال لاى سبب ولم تأخد القرار بسبب الاسباب المذكوره فلا تفكر كثيرا ولا تحتار مع شركتنا شركة نقل عفش بالدمام هو القرار السليم فى ايجاد شركة تقوم بعمليه النقل بمنتهى السرعه والدقه فى الاداء لكى تحافظ على الاثاث والمنقولات من اى تكسير او خدوش او اى اثار سلبيه مع تحقيق اقل تكاليف ممكنه كل ما عليك هو الاتصال بنا شركة نقل اثاث بالدمام لكى تتعرف على خدماتنا الغير محدوده فى عمليات النقل فنحن نقوم بكافة مراحل النقل من فك وتغليف وتعبئه ونقل وتركيب العفش والاثاث وكافة المنقولات من انتيك وملابس ومفروشات وادوات مطبخ وكل ما يلزم لعميله نقل امنه ومن اجل ان تحافظ على منقولاتك حتى لو كان اثاث مكتبك او شركتك او فندقك مثلا فيكون الاثاث والمفروشات جديد وتريد الحفاظ عليه كل هذا سوف تجده معنا واكثر نحن شركة تخزين اثاث بالدمام وكل هذا يتم فى سرعه بالغه لضمان عدم التاخير عن المواعيد الخاصه بك او تعطيلك عن اعمالك ايا كانت درجه اهميتها فنحن نتواجد من اجل خدمتك وراحتك وتحقيق كل احلامك .
    لمزيد من خدماتنا
    شركة نقل اثاث بالخبر
    شركة نقل عفش بالخبر
    للتواصل
    0537772829

    ReplyDelete
  3. يسعي الكثير من العملاء للتعامل مع مراكز صيانة وايت وستنجهاوس لتواجد فيها جميع انواع الصيانة و يثقون بجميع الاعمال التي تقوم بها صيانة وستنجهاوس لتواجد فيها جميع الامكانيات التي يحتاجون اليها في اداء عملهم
    http://www.maintenanceg.com/White-Westinghouse-Center-Agent.html

    ReplyDelete
  4. تتميز شركة حراسات امنيةة بتواجد فيها خدمة تامين المشاريع تحت الانشاء لما يتواجد لديها من كثير من القدرات و الات التي تمكن شركة امن وحراسة من اداء جميع اعمالهم علي درجة كبيرة من الدقة
    http://www.guards-security.com/

    ReplyDelete
  5. تتميز جليسات مسنين في مصر التي تقوم بتوفيرهم دار مسنين بقدراتهم علي تقديم جميع انواع الرعاية المطلوبة
    http://www.careolder.com/

    ReplyDelete
  6. الآن ستتمكن من تنظيف منزلك و ابادة الحشرات الموجودة فيه ، عند التواصل مع شركة مكافحة حشرات بالخبر المتخصصة و الرائدة التي تقدمها شركة ابراج دبي

    ReplyDelete
  7. Have you been thinking about the power sources and the tiles whom use blocks I wanted to thank you for this great read!! I definitely enjoyed every little bit of it and I have you bookmarked to check out the new stuff you post
    Data Science training in marathahalli
    Data Science training in btm
    Data Science training in rajaji nagar
    Data Science training in chennai
    Data Science training in kalyan nagar
    Data Science training in electronic city
    Data Science training in USA
    Data science training in pune



    ReplyDelete
  8. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging.
    java training in tambaram | java training in velachery

    java training in omr | oracle training in chennai

    java training in annanagar | java training in chennai

    ReplyDelete
  9. يسعي الكثير من الباحثين الي استخدام موقع مكتبتك للحصول علي جميع خدمات البحث العلمي منها الحصول علي الدراسات السابقة الاجنبية لاستكمال الابحاث العلمية بمختلف تخصصاتها

    ReplyDelete
  10. This is a good post. This post give truly quality information. I’m definitely going to look into it. Really very useful tips are provided here. thank you so much. Keep up the good works.
    python training in pune
    python online training
    python training in OMR

    ReplyDelete
  11. Really great post, I simply unearthed your site and needed to say that I have truly appreciated perusing your blog entries.
    Blue Prism Training Course in Pune

    Blue Prism Training Institute in Bangalore

    ReplyDelete
  12. يحتاج لكثير من الباحثين الي الحصول علي خدمة اعداد اطار نظري للبحث العلمي التي يقوم به فيتجه الي موقع مكتبتك المتطور في الخدمات البحثية التي يقوم بها

    ReplyDelete
  13. يتم تخصيص جزء في الرسالة العلمية والابحاث يضم الدراسات السابقة في البحث العلمي مما جعل موقت مكتبتك يسلط عليها الضوء ويدعم عرض كافة الدراسات السابقة العربية والاجنبية ومراجع البحث العلمي التي تم الاستعانة بها خلال الدراسة والبحث

    ReplyDelete
  14. Am visit of many blog but not get valuable information, but after seen your blog provide it me a lot of valuable and useful information I really like to thank you so much for share this information with us, if are inserted in grow up your life style and also grow up your looking so please come on my website am put it on many information so and visit again time thank you so much for read my comment I hope your also like my comment and you also go on my web page.
    Lifestyle Magazine

    ReplyDelete
  15. Nice and interesting post,I appreciate your hard work,keep uploading more, Thank you for sharing valuable information.

    Heart diseases can cause instant death, thus, they have to be cured shortly. Being a trusted Heart Hospital In India, Indo American Health provides you treatment for multiple heart disorders that call for various surgeries, device implantation and more. All this is just a call away.

    ReplyDelete
  16. Hi, It's a great a post. Thanks For Sharing me a valuable and informative information.

    Choose from Sartojiva’s leather striped belt, textured reversible belt and a lot more crafted with the best fabric that is available in the market. We have the right fit for your style, so come, choose and Buy Men Belts Online with us now.

    ReplyDelete
  17. I’ve learned a lot from your blog here, Keep on going, my friend, I will keep an eye on it.
    Refresh Mattress In Delhi

    ReplyDelete
  18. I’ve learned a lot from your blog here, Keep on going, my friend, I will keep an eye on it.
    WPC BOARD PANEL MANUFACTURERS

    ReplyDelete
  19. I Got Job in my dream company with decent 12 Lacks Per Annum salary, I have learned this world most demanding course out there in the current IT Market from the big data training in bangaloreProviders who helped me a lot to achieve my dreams comes true. Really worth trying Freelance seo expert in bangalore

    ReplyDelete
  20. blockchain has a huge growth in the market in nowadays. learn blockchain through blockchain course online

    ReplyDelete
  21. I learned World's Trending Technology from certified experts for free of cost.i Got job in decent Top MNC Company with handsome 14 LPA salary, i have learned the World's Trending Technology from Python training in pune experts who know advanced concepts which can helps to solve any type of Real time issues in the field of Python. Really worth trying instant approval blog commenting sites

    ReplyDelete
  22. The azure technology has a various applications like hosting, designing cloud based applications, web based applications azure online training india

    ReplyDelete
  23. Thank you for sharing such this type critical important topic

    ReplyDelete
  24. Aanal Magnetic Industries is one of the preeminent Magnetic Separator Manufacturers.


    Aanal Magnetic Industries is one of the high-priority Permanent Suspension Magnets Manufacturers In Ahmedabad.


    Aanal Magnetic Industries is a leading Roller Type Magnetic Separator Manufacturers In Ahmedabad.

    Aanal Magnetic Industries is a reliable Plate Magnet Manufacturers in Ahmedabad, Gujarat.

    ReplyDelete
  25. Dhariwal Industries is one of the paramount Aluminium Coil Sheet Manufacturers. You can rely on our quality as it has passed several quality parameters. You can also contact us for placing your bulk orders. We are available only a call away.

    ReplyDelete
  26. This is a great post. Your Blog the very informative, I have learned some information about your blog. Virtual Class Software

    ReplyDelete
  27. As one of the legit Ladies Suits Manufacturers, Saranga sell alluring Suits at a considerable price range.

    Saranga is the leading Ladies Kurti Manufacturers and Designer Kurti Wholesalers.

    Searching for one of the trusted Designer Pants Manufacturers in Delhi? Saranga is the one you can trust blindly.

    Saranga - one of the paramount Palazzo Manufacturers in Delhi, We have the most beautiful collection of palazzo available in different patterns, styles and fabrics.

    At Saranga, we have a fabulous collection of Muslin Salwar Suit available in different fabrics. As one of the best Muslin Salwar Suit Manufacturers in Delhi.

    ReplyDelete
  28. نقل اثاث العين

    لا تقدم شركة الطريق لامي لنقل الأثاث خدمات نقل الأثاث فقط في عجمان ودبي وأبو ظبي ولكن أيضًا في العين. العملاء من العين هم
    نقدر في الغالب خدمات شركتنا ، لأننا أفضل شركاتنقل اثاث العين
    https://tareeqlamie.com/

    ReplyDelete
  29. Evermore Technologies let businesses avail greater lead generation and higher conversions with its technical expertise. Evermore also provides Website Designing and Development Company in Noida for better online visibility and brand perception.
    Website Designing Company in Noida

    ReplyDelete

  30. Gir AmritPhal is one of the best organic & Pure Cow Milk Provider in Gurgaon. We provide 100% pure and natively produced Desi cow milk at best price.

    ReplyDelete
  31. Infycle Technologies, the best software training institute in Chennai offers the No.1 Big Data Training in Chennai for tech professionals. Apart from the Big Data training, other courses such as Oracle, Java, Hadoop, Selenium, Android, and iOS Development, Data Science will also be trained with 100% hands-on training. After the completion of training, the students will be sent for placement interviews in the core MNC's. Dial 7502633633 to get more info and a free demo.No.1 Big Data Training Chennai | Infycle Technologies

    ReplyDelete
  32. Fine Organics is counted among the top-notch Menthol Crystals Manufacturers , Suppliers & Exporters and natural mint derivatives in USA.Manufacturer of Menthol Crystals in USA provides an unparalleled quality when compared to any other alternative in the market.We find the most organic source for procuring and deriving these products to get the best of the environment.

    ReplyDelete
  33. Chemistry is our forte. We provide chemicals ranging from fine chemcials for early R&D application to large scale industrial production. Glycidol (556-52-5 ) manufacturer USA is a leading developer, manufacturer and exporter of API, intermediates of API, Fragrance intermediates, Specialty Chemicals & other Customized Products. Located in Asia's largest chemical industrial estate, Rampur, U.P., Agex Pharma begins its operations as a small scale unit in 1990 and in a span of three decades in market has emerged as a leading player which believes in quality. Today with an inventory of 500+ products, 200+ clients globally Agex Pharma has placed itself in one of the most sought after companies in the nation for Fine and Rare Specialty chemicals.Our business is based on a simple philosophy: to provide our customers with high quality fine chemicals at reasonable prices and with fast turn-around schedules.

    ReplyDelete
  34. Hi, I am John Smith I am Web Developer, It is an amazing blog thanks for the sharing the blog. Frantic infotech provide the java web development such as an information about software development for costumer service. Frantic infotech also provide the angularjs web development. Theve delopment of advanced web applications is Orient Software’s specialty and we will successfully fulfill all your web application development requirements, from small-sized to wider-ranged projects.

    ReplyDelete
  35. Fine Organics offer our clients Natural Mentha Oil and its Products that is specially extracted from mint leaves. These are sourced
    from reliable vendors who are known for offering quality products.Manufacturer of Menthol
    Crystals in India
    are world's leading Manufacturer and Exporter of Dihydromyrcenol (DHMOH), Natural Menthol Large Crystals IP/BP/USP,
    Dementholised Peppermint Oil (Tri-Rectified) and other Phytochemicals. We have a High-Tech Manufacturing facility sprawling over 10,000 sq.mts,
    capable of quality and quantity production at Rampur(UP, India).

    ReplyDelete
  36. You have really amazing website thanku for sharing with us.

    ReplyDelete