Code Monkey home page Code Monkey logo

masked_faces's Introduction

Masked_Faces

The goal of this project was to train YOLOv4 on a custom dataset containing images of two classes (Masked and Unmasked Faces).I trained yolov4 using this (https://github.com/AlexeyAB/darknet) darknet repository. You can find more details about the darknet on https://pjreddie.com/darknet/yolo/. I used Google colab GPU to train my model.This (https://github.com/theAIGuysCode/YOLOv4-Cloud-Tutorial) repository includes some colab notebooks that explains how to train your own model on colab with YOLOV4.

Dataset

I used MAFA dataset which can be downloaded from kaggle (https://www.kaggle.com/rahulmangalampalli/mafa-data).This data contains annotations in a .mat file. Yolo accept a specific dataset format for images and annotations. You can find all the details about Yolov4 data formats and other thing from this medium blog (https://towardsdatascience.com/yolov4-in-google-colab-train-your-custom-dataset-traffic-signs-with-ease-3243ca91c81d). I transformed the annotations of MAFA data into yolov4 fomrat using my own script. The transformed dataset can be downloaded from this (https://drive.google.com/file/d/1bVTUwwH9CI0jIQC3XJtycu2btZtVpTiR/view?usp=sharing) drive link.

Training

Training yoloV4 on a custom dataset involves dealing with different thinng like updating the architecture of your detection model depending upn the size and number of classes of your dataset. You can find all the recommended chages on the official darknet repository by AlexeyAB (https://github.com/AlexeyAB/darknet#how-to-train-to-detect-your-custom-objects).After making all the recommended changes by the author, I trained the model for 60000 iterations. The final weights gave me an mAP of 72.79%.

 detections_count = 45332, unique_truth_count = 8493  
class_id = 0, name = Masked, ap = 98.20%   	 (TP = 6245, FP = 281) 
class_id = 1, name = Un-Maked, ap = 47.38%   	 (TP = 883, FP = 345) 

 for conf_thresh = 0.25, precision = 0.92, recall = 0.84, F1-score = 0.88 
 for conf_thresh = 0.25, TP = 7128, FP = 626, FN = 1365, average IoU = 75.15 % 

 IoU threshold = 50 %, used Area-Under-Curve for each unique Recall 
 mean average precision ([email protected]) = 0.727884, or 72.79 % 
Total Detection Time: 113 Seconds

Set -points flag:
 `-points 101` for MS COCO 
 `-points 11` for PascalVOC 2007 (uncomment `difficult` in voc.data) 
 `-points 0` (AUC) for ImageNet, PascalVOC 2010-2012, your custom dataset

Improvements

As you can see the mAP for masked class is less from un-masked. This is because of the non-uniform distribution of data. This can be improved by incresing the number of images containing unmasked faces.

Testing

You can test the model using this (https://drive.google.com/file/d/1-GsG5gZiyDzCrNnWt6RnllFnIbjjLN0y/view?usp=sharing) weight file. You can use darkent test or demo command for running detections on both images or videos respectively.

Images

alt_text alt_text

Videos

IMAGE ALT TEXT HERE IMAGE ALT TEXT HERE

References

masked_faces's People

Stargazers

 avatar

Watchers

 avatar

masked_faces's Issues

It seems that MAFA dataset has many noisy or missing label data.

Noisy data example

image

Missing label data example

refer to left girl
image

Hi, Ehsan!

I have some problem with MAFA dataset.

The below code is the code used to visualize data in MAFA.

I referenced this project code.

It's the problem of the dataset or code?

import scipy.io

import os
import argparse

import cv2

class MAFAReader():
    def __init__(self, base_dir, annotation_file):
        self.base_dir = base_dir
        self.annotation_file = annotation_file
        self.data = scipy.io.loadmat(self.annotation_file)

        if "Train" in annotation_file:
            self.train = True
            self.len_dataset = len(self.data["label_train"][0])
        elif "Test" in annotation_file:
            self.train = False
            self.len_dataset = len(self.data["LabelTest"][0])
        else:
            print("Error: What are you doing now?")
            exit()
            
        print("annotation_file: ", self.annotation_file)
        print("self.len_dataset: ", self.len_dataset)
        
    def read_mat(self, idx):
        if self.train:
            train_image = self.data["label_train"][0][idx]
            train_image_name = str(train_image[1]).strip("['']")  # Test [0]
            train_image_full_path = os.path.join(self.base_dir, "train-images", "images", train_image_name)
            
            print(train_image_full_path)
            
            img = cv2.imread(train_image_full_path)
            
            categories = []
            bboxes = []

            for i in range(0, len(train_image[2])):
                _bbox_label = train_image[2][i]  # Test[1][0]
                _category_id = _bbox_label[12]  # Occ_Type: For Train: 13th, 10th in Test
                _occulution_degree = _bbox_label[13]
                bbox = [_bbox_label[0], _bbox_label[1], _bbox_label[0]+_bbox_label[2], _bbox_label[1]+_bbox_label[3]]
                
                print("_bbox_label: ", _bbox_label)
                print("_category_id: ", _category_id)
                print("_occulution_degree: ", _occulution_degree)
                print("bbox: ", bbox)
                
                if (_category_id != 3 and _occulution_degree > 2):
                    category_name = 'Mask'  # Faces with Mask
                    categories.append(category_name)
                    bboxes.append(bbox)
                elif (_category_id==3 and _occulution_degree<2):
                    category_name = 'No-Mask'  # Faces with Mask
                    categories.append(category_name)
                    bboxes.append(bbox)
                                
                cv2.rectangle(img, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), thickness=2)

            cv2.imshow("img", img)
            cv2.waitKey(0)
        else:
            test_image = self.data["LabelTest"][0][idx]
            test_image_name = str(test_image[0]).strip("['']")  # Test [0]
            test_image_full_path = os.path.join(self.base_dir, "test-images", "images", test_image_name)
            img = cv2.imread(test_image_full_path)
            categories = []
            bboxes = []
            for i in range(0, len(test_image[1])):
                _bbox_label = test_image[1][i]  # Test[1][0]
                # Occ_Type: For Train: 13th, 10th in Test
                # In test Data: refer to Face_type, 5th
                _face_type = _bbox_label[4] # Face Type
                _occ_type = _bbox_label[9]
                _occ_degree = _bbox_label[10]
                bbox = [_bbox_label[0], _bbox_label[1], _bbox_label[0] + _bbox_label[2], _bbox_label[1] + _bbox_label[3]]
                if (_face_type==1 and _occ_type!=3 and _occ_degree > 2):
                    category_name = 'Mask'
                    bboxes.append(bbox)
                    categories.append(category_name)
                elif (_face_type==2):
                    category_name = 'No-Mask'
                    bboxes.append(bbox)
                    categories.append(category_name)
                cv2.rectangle(img, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), thickness=2)

            cv2.imshow("img", img)
            cv2.waitKey(0)
             
if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='MAFA2YOLO')
    parser.add_argument('--base-dir', default="./", type=str)
    opt = parser.parse_args()
    
    training_set = MAFAReader(base_dir=opt.base_dir, 
                              annotation_file=os.path.join(opt.base_dir, 'MAFA-Label-Train/LabelTrainAll.mat'))
    
    for i in range(training_set.len_dataset):
        training_set.read_mat(idx=i)
        break
    
    test_set = MAFAReader(base_dir=opt.base_dir,
                          annotation_file=os.path.join(opt.base_dir, 'MAFA-Label-Test/LabelTestAll.mat'))
    
    for i in range(test_set.len_dataset):
        test_set.read_mat(idx=i)
        

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.