Face Mask Detection using ML.NET Model Builder and C#

Face Mask Detection using ML.NET Model Builder and C#

Face Mask Detection tutorial using ML.NET

Public shaming over not wearing a face mask started almost as soon as the COVID-19 pandemic itself. Nowadays, a lot of countries made it mandatory to wear face masks when in public. Every single person in the world must recognize how important it is to wear a mask to slow the spread of SARS-CoV-2, the virus that caused COVID-19. As a result, today we have a lot of companies pioneering face mask recognition software to get people to comply for the public good.

Up until COVID-19 hit, there were just a handful applications for mask recognition. And traditionally masks have been confounding facial recognition software, until now. With the new machine learning tools, we can increase the accuracy of recognizing if a person wears a face mask.

And this is what we are going to do today. We will learn how to leverage the ML.NET Model Builder to resolve this problem.

The Face Mask Detection Problem

A Facial Recognition software analyzes the features around the eye, nose, mouth, and ears to identify the person whose picture is supplied. Like we mentioned before, wearing a mask obstructs the recognition process. Because of that a lot of companies issued an update to their facial recognition system. Instead of recognizing the person on the image, they now scan for a person wearing a mask. If the person is wearing a face mask, they are prompted to enter their password. Otherwise, the normal face recognition workflow is executed. What I am trying to convey is that a lot of companies had to solve this problem and adapt their system accordingly.

A lot of people are rightfully worried about this type of software. Is it breaking our privacy rights? Well mask recognition software in theory bypasses the privacy issues because programs do not actually identify people. And we will see the correctness of this statement in just a bit. Like others before us, we will train a ML.NET Model on two sets of pictures. One set to teach the algorithm how to recognize a person with a face mask on. And the other set will consist of pictures where the person does not wear a mask.

But before we do that, we must have another module in place. And that one is responsible for Face Detection. We will use a famous algorithm to extract faces from an image. Then the cropped face will be handed over to the face mask recognition system. As you can see our application is not identifying faces in any way. So, it can not link a face to a specific person. That is because we are not using images of faces that are linked to their identities.

ML.NET Model Builder

In this tutorial we will use the ML.NET Model Builder to create a face mask detection module. Model Builder is a simple UI tool for developers to build and train custom machine learning models in their .NET applications. This tool is especially useful for developers that have no prior knowledge on Machine Learning. Because ML.NET Model Builder supports AutoML, it is very easy to find the machine learning model best suited for our scenario. AutoML allows us to load the dataset and train the model right away. As a result, the Machine Learning complexity is delegated to AutoML. Because of this, the Model Builder can be used by anyone trying to solve a Machine Learning problem without a prior knowledge.

Keep in mind is that this tool is shipped with Visual Studio 2019. If you use an older version of Visual Studio, then the Model Builder might be in a Preview Mode.

To make sure that you have your environment set correctly you can go back and check my article on how to activate and use ML.NET with Model Builder.

https://code-ai.mk/how-to-use-ml-net-model-builder-for-image-classification/

This article is not about ML.NET or the Model Builder as a tool. So, I will only focus on some key points. If you want to learn more continue reading up on the following link.

Image Face Detection with C# NET – CODE-AI NET with Source Code (code-ai.mk)

Face Detection App
Face Detection

C# Application

This application is continuation to the Face Detection app we built some time ago. The goal in this article is to detect whether a person on the image, wears a face mask.

Face Mask Detection
Face Recognition with ML.NET and Model Builder application

First, we need to open an image. Because we are using the Haar Classifier we need to set up couple of parameters. Those parameters are explained in the previous post. The addition to this application is the ML.NET Face Mask Recognition module. Once the face is detected, it is cropped. Then the image is passed to the face mask detector and it generates one of two results. Either the person wears a face mask or not.

Face Recognition with ML.NET and Model Builder
Face Recognition with ML.NET and Model Builder application

ML.NET: Data Set

Out dataset consists of two types of face images. Images that contain a face wearing a mask. And images having a person without a mask. This is our goal. Given a face image, we need to classify said image in one of those two categories.

This is how the training set looks like:

ML.NET Model Builder Dataset No Masks
ML.NET Model Builder: Dataset (No Mask)
ML.NET Model Builder Dataset Mask
ML.NET Model Builder: Dataset (Mask)

The dataset is very small. This is because I would like to train my model locally. You can get a bigger data set and train using Azure. We will cover how to train on the cloud soon.

Face Detection

I am not going to talk too much about Face Detection, just because we have covered it in a previous article. So, Face Detection is the process of identifying a human face in a digital image. As a result, we will get a bounding box around the desired object on the image – a human face. In this project we are using the Viola-Jones Object Detector based on Haar-like features.

Accord.NET library has implementation of this technique in the HaarObjectDetector class. This class implements the Viola-Jones object detector algorithm. This technique is used for object detection in images. But it is not only for faces. It can be used on any type of object. But we need faces so, we are going to create an instance of FaceHaarCascade class and pass it to the HaarObjectDetector instance.

One very important thing to note here, is that this algorithm might perform worse on images where a person wears a mask. This is because some key facial features like the nose and mouth are obstructed. The Haar Classifier still works fine most of the time, but do not be surprised if it misses a face. In a situation like this, you can experiment with the face detection parameters and improve your results.

Eventually we will build a face detector using ML.NET and Deep Learning. But for now, this will do.

Face Recognition

The Face Recognition module consists of the ML.NET model generated by the Module Builder. If you have followed my other tutorial on how to use it, you should have two projects. One is a .NET Core project with the Model suffix appended to it, and the other is a .NET Code Console Application.

Your project structure should be something like this:

Project Structure
Project Structure

In my scenario the FaceDetectionAppML.Model contains the trained model produced by the ML.NET Model Builder tool. The FaceDetectionAppML.ConsoleApp is a .NET Core Console Application that consumes and uses the generated model.

The Solution Structure

The Face Mask Detection application uses the .NET Framework. However, the other two projects use the .NET Core 3.1. ML.NET has a known issue with .NET Framework so we will need to find a workaround to use our trained model inside the Face Mask Detection application.

To consume the ML.NET model we will call and send commands to the .NET Core console application. We will launch it as a separate process and send the extracted faces to be processed there. The app will return a string of the category that image belongs to. In other words, it will return a “Mask” or “No Mask” string.

We will execute and control the console application via C#  System.Diagnostics.Process class. We want to be able to pass multiple images on a single application instance. This is because loading up our ML.NET Model can be time consuming. What we want to do, is load the application once and just pass image file paths for classification.

There are two ways we can easily pass an image. We can use Shared Memory Manager, or we can save the image to a disk and send the file path. In this demo the latter is used.

C# Code Walkthrough

Code Walkthrough
Detect Face Mask code

The C# code is quite straightforward. First, we need to load up an image. The Image Selector class checks if the image is valid or not. If the image is valid the Image Processor class takes over. Its soul goal is to optimizes the image for the Face Detector. As you can see, we do a gray scale operation, followed by Histogram Equalization. This prepares the image for the Face Detector module.

Then, the Face Detector executes the algorithm, and it returns a rectangle array. A single rectangle represents the face of the image by its X, Y, Width and Height properties. As a result, we can enumerate the array. For each face rectangle, we crop the image and save it on disk. If the image is saved the Face Mask Recognition module picks it up and passes it to the .NET Core console application. This C# project uses the ML.NET model we trained to classify the face image. As you can see, we call the function PersonWearsMask. This method returns true if the person on the image wears a face mask.

Then all we have left to do is to draw the bounding box with the correct color. Green if face mask is present, red otherwise.

And that is pretty much it.

Face Mask Detection using ML.NET Conclusion

You can see how easy it is to build and train a model using ML.NET. However, using it in .NET Framework application is not that simple. The ML.NET and Model Builder modules are still work in progress. So, there are bound to have some issues at this point of time. But still, we managed to find a solution to our problem. In the next article I will describe it in more detail. Getting comfortable with the Model Builder is very important because soon we will start writing ML.NET code. This article does not contain a project for download simply because it is too big. But you have all the tools to recreate it.

One of the weakest links in this app is the Face Detection module. Please note that we are using Haar features trained on faces without a mask. This means that the face detection algorithm might miss a lot of faces. We will deal with this later. For now if you experiment with the provided parameters, you actually may get decent results

More ML.NET Tutorials

34 thoughts on “Face Mask Detection using ML.NET Model Builder and C#

  1. Reply
    강남섹스출장마사지
    March 10, 2024 at 2:02 pm

    충무로출장업소

  2. Reply
    vpn special coupon code 2024
    April 8, 2024 at 7:55 am

    I’m really enjoying the design and layout of your site.
    It’s a very easy on the eyes which makes it much more enjoyable for
    me to come here and visit more often. Did you hire out a designer to create
    your theme? Exceptional work!

    Have a look at my web-site … vpn special coupon code 2024

  3. Reply
    vpn special code
    April 9, 2024 at 9:26 pm

    Thank you for the auspicious writeup. It in fact was a amusement
    account it. Look advanced to far added agreeable from you!
    By the way, how could we communicate?

    Also visit my homepage :: vpn special code

  4. Reply
    Christoffer
    April 29, 2024 at 7:39 pm

    When I originally commented I appear to have clicked the
    -Notify me when new comments are added- checkbox and from now on whenever a comment is added I
    get 4 emails with the same comment. Is there an easy method you are able to remove me from that service?
    Thank you!

  5. Reply
    naga169
    April 30, 2024 at 8:01 am

    Incredible quest there. What occurred after? Take care!

  6. Reply
    Topaz
    April 30, 2024 at 12:27 pm

    Do you mind if I quote a couple of your articles as long as I provide credit
    and sources back to your website? My website is in the exact same area of
    interest as yours and my users would truly benefit from
    some of the information you present here. Please let
    me know if this okay with you. Cheers!

  7. Reply
    Will
    April 30, 2024 at 12:28 pm

    Post writing is also a excitement, if you know then you can write or else
    it is complicated to write.

  8. Reply
    Senaida
    April 30, 2024 at 12:37 pm

    Howdy! Do you know if they make any plugins to assist with Search
    Engine Optimization? I’m trying to get my blog to rank for
    some targeted keywords but I’m not seeing very good gains.

    If you know of any please share. Cheers!

  9. Reply
    Jubilee
    April 30, 2024 at 12:57 pm

    Fantastic items from you, man. I have keep
    in mind your stuff previous to and you are just extremely wonderful.
    I really like what you have received here, certainly like what you are saying and
    the best way during which you assert it. You make it entertaining and
    you continue to take care of to keep it smart. I can’t wait
    to learn much more from you. This is actually a great site.

  10. Reply
    Hokicoy Daftar
    April 30, 2024 at 1:03 pm

    Hey there! Someone in my Myspace group shared this website with us so I came to check it out.
    I’m definitely enjoying the information. I’m bookmarking and will be tweeting this to
    my followers! Excellent blog and outstanding design.

  11. Reply
    Detron
    April 30, 2024 at 1:06 pm

    May I simply say what a relief to uncover someone who really knows what they’re talking about
    over the internet. You certainly realize how to bring a
    problem to light and make it important. A lot more
    people ought to read this and understand this side of the story.
    I can’t believe you are not more popular since you most certainly have the gift.

  12. Reply
    Bresha
    April 30, 2024 at 1:15 pm

    Your style is unique in comparison to other folks I
    have read stuff from. Many thanks for posting when you have the opportunity,
    Guess I will just book mark this web site.

  13. Reply
    naga169
    April 30, 2024 at 1:36 pm

    Keep this going please, great job!

  14. Reply
    Gregg
    April 30, 2024 at 5:16 pm

    You really make it seem really easy with your presentation however I in finding this topic to be actually one thing
    which I think I might by no means understand. It sort of feels too complex and very wide for me.
    I am looking ahead to your next submit, I’ll try to get the cling of
    it!

  15. Reply
    Satin
    April 30, 2024 at 6:04 pm

    Hello! This post could not be written any better! Reading through this post reminds
    me of my previous room mate! He always kept chatting about this.
    I will forward this write-up to him. Fairly certain he will have
    a good read. Thanks for sharing!

  16. Reply
    Tiajuana
    April 30, 2024 at 6:14 pm

    I am not sure where you’re getting your info, however great topic.
    I needs to spend some time learning more or
    understanding more. Thank you for wonderful information I was in search of this info for my mission.

  17. Reply
    Ophelia
    April 30, 2024 at 6:15 pm

    Magnificent beat ! I wish to apprentice while you amend your website, how can i subscribe for a blog web site?
    The account helped me a acceptable deal. I had been tiny bit
    acquainted of this your broadcast offered bright clear
    concept

  18. Reply
    Shania
    April 30, 2024 at 6:23 pm

    Hi to all, it’s in fact a pleasant for me to visit this site, it consists of important Information.

  19. Reply
    Auren
    April 30, 2024 at 6:29 pm

    Hi there, just became alert to your blog through Google, and found that
    it is really informative. I am going to watch out
    for brussels. I’ll be grateful if you continue this in future.
    Lots of people will be benefited from your writing.
    Cheers!

  20. Reply
    Donetta
    April 30, 2024 at 6:31 pm

    Good day! I could have sworn I’ve been to this website before but after
    browsing through some of the post I realized it’s new to me.
    Nonetheless, I’m definitely happy I found it and I’ll
    be bookmarking and checking back frequently!

  21. Reply
    Felisia
    April 30, 2024 at 6:33 pm

    Hey very nice blog!

  22. Reply
    Maxine
    April 30, 2024 at 6:36 pm

    You have made some decent points there. I looked on the net for additional information about the issue and found most people will
    go along with your views on this web site.

  23. Reply
    Lukas
    April 30, 2024 at 7:04 pm

    Nice post. I was checking constantly this blog and I am impressed!
    Extremely useful info specially the last part 🙂 I care for such information a lot.

    I was looking for this certain info for a very long time.
    Thank you and best of luck.

  24. Reply
    warung makan
    April 30, 2024 at 7:26 pm

    constantly i used to read smaller content which as well clear their motive, and
    that is also happening with this paragraph which I am reading here.

  25. Reply
    slot303
    April 30, 2024 at 9:09 pm

    I am in fact glad to glance at this weblog posts which carries tons of helpful data,
    thanks for providing such information.

  26. Reply
    winning303
    May 1, 2024 at 2:19 am

    Way cool! Some extremely valid points! I appreciate you writing this article plus the rest of the website is extremely good.

  27. Reply
    https://seamacgames.com/user/DaniHeady673834/
    May 1, 2024 at 11:21 am

    When some one searches for his vital thing, so he/she wishes to be available that in detail,
    so that thing is maintained over here.

  28. Reply
    joker123 deposit pulsa indosat
    May 1, 2024 at 2:10 pm

    I really like looking through an article that can make men and women think.

    Also, thanks for permitting me to comment!

  29. Reply
    Situs Judi Slot303
    May 1, 2024 at 3:22 pm

    With havin so much content do you ever run into any issues
    of plagorism or copyright infringement? My blog has a lot of exclusive content I’ve either
    authored myself or outsourced but it looks like a lot of it is
    popping it up all over the internet without my authorization. Do you know any
    techniques to help stop content from being stolen? I’d truly
    appreciate it.

  30. Reply
    Alethea
    May 1, 2024 at 4:19 pm

    excellent issues altogether, you just gained a new reader.
    What may you suggest about your put up that you made a few
    days in the past? Any certain?

  31. Reply
    slot303
    May 1, 2024 at 5:11 pm

    This article presents clear idea in favor of the new people of
    blogging, that really how to do blogging.

  32. Reply
    slot88
    May 1, 2024 at 10:23 pm

    I loved as much as you’ll receive carried out right here.

    The sketch is tasteful, your authored material stylish.
    nonetheless, you command get got an shakiness over that you wish be delivering the following.
    unwell unquestionably come more formerly again since exactly the same nearly a lot often inside case you
    shield this hike.

  33. Reply
    naga169
    May 1, 2024 at 11:52 pm

    I loved as much as you’ll receive carried out right here. The sketch is attractive,
    your authored material stylish. nonetheless, you
    command get got an shakiness over that you wish be delivering the following.

    unwell unquestionably come further formerly again since exactly the same nearly very often inside
    case you shield this increase.

  34. Reply
    naga169
    May 2, 2024 at 1:05 am

    This is a topic which is near to my heart…
    Best wishes! Exactly where are your contact details though?

Leave a Reply

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