Skip to content

Face Recognition, Face Liveness Detection, Face Anti-Spoofing, Face Detection, Face Landmarks, Face Compare, Face Matching, Face Pose, Face Expression, Face Attributes, Face Templates Extraction, Face Landmarks

initial files

andyfaceplugina1729f32c08c
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..b24d71e
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,50 @@
+# These are some examples of commonly ignored file patterns.
+# You should customize this list as applicable to your project.
+# Learn more about .gitignore:
+# https://www.atlassian.com/git/tutorials/saving-changes/gitignore
+
+# Node artifact files
+node_modules/
+dist/
+
+# Compiled Java class files
+*.class
+
+# Compiled Python bytecode
+*.py[cod]
+
+# Log files
+*.log
+
+# Package files
+*.jar
+
+# Maven
+target/
+dist/
+
+# JetBrains IDE
+.idea/
+
+# Unit test reports
+TEST*.xml
+
+# Generated by MacOS
+.DS_Store
+
+# Generated by Windows
+Thumbs.db
+
+# Applications
+*.app
+*.exe
+*.war
+
+# Large media files
+*.mp4
+*.tiff
+*.avi
+*.flv
+*.mov
+*.wmv
+
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..f10d08e
--- /dev/null
+++ b/README.md
@@ -0,0 +1,76 @@
+<div align="center">
+<img alt="" src="https://github.com/Faceplugin-ltd/FaceRecognition-Javascript/assets/160750757/657130a9-50f2-486d-b6d5-b78bcec5e6e2.png" width=200/>
+</div>
+
+# Face Recognition SDK for Windows and Linux - Fully On Premise
+
+![Forks](https://img.shields.io/github/forks/Faceplugin-ltd/Face-Recognition)
+![Stars](https://img.shields.io/github/stars/Faceplugin-ltd/Face-Recognition)
+
+## Overview
+The world's 1st **Completely Free and Open Source** `Face Recognition SDK` from [Faceplugin](https://faceplugin.com/) for developers to integrate face recognition capabilities into applications. Supports real-time, high-accuracy face recognition with deep learning models.
+<br>This is `on-premise face recognition SDK` which means everything is processed in your phone and **NO** data leaves the device
+<br>You can use this SDK on Windows and Linux
+<br><br>**Please contact us if you need the SDK with higher accuracy.**
+<br></br>
+
+## Key Features
+- **Real-Time Face Recognition**: Can detect and recognize faces from live video streams. Currently only supports face recognition from an image.
+- **High Accuracy**: Built with deep learning models trained on large datasets.
+- **Cross-Platform**: Compatible with Windows and Linux.
+- **Flexible Integration**: Easy-to-use APIs for seamless integration into any project.
+- **Scalable**: Works on local devices, cloud, or embedded systems.
+- **Python SDK**: Comprehensive support for Python with extensive documentation and examples.
+
+## Applications
+This **Face Recognition SDK** is ideal for a wide range of applications, including:
+- **Time Attendance Systems**: Monitor arrivals and depatures using face recognition.
+- **Security Systems**: Access control and surveillance.
+- **User Authentication**: Biometric login and multi-factor authentication.
+- **Smart Devices**: Integration into IoT devices for smart home or office applications.
+- **Augmented Reality**: Enhance AR applications with real-time facial recognition.
+- **Retail**: Personalized marketing and customer analytics.
+
+## Installation
+Please download anaconda on your computer and install it.
+We used Windows machine without GPU for testing.
+
+### create anaconda environment
+conda create -n facesdk python=3.9
+
+### activate env
+conda activate facesdk
+
+### install dependencies
+pip install -r requirements.txt
+
+### compare 1.jpg and 2.png in the test directory.
+python run.py
+
+## APIs and Parameters
+
+**GetImageInfo(image, faceMaxCount):** returns face bounding boxes, landmarks and feature embeddings<br>
+**get_similarity(feat1, feat2):** returns similarity between two feature embeddings. 0 to 100<br>
+**Threshold**: value to determine if two embeddings belong to same person, default = 75
+
+
+## List of our Products
+
+* **[FaceRecognition-LivenessDetection-Android](https://github.com/Faceplugin-ltd/FaceRecognition-Android)**
+* **[FaceRecognition-LivenessDetection-iOS](https://github.com/Faceplugin-ltd/FaceRecognition-iOS)**
+* **[FaceRecognition-LivenessDetection-Javascript](https://github.com/Faceplugin-ltd/FaceRecognition-LivenessDetection-Javascript)**
+* **[FaceLivenessDetection-Android](https://github.com/Faceplugin-ltd/FaceLivenessDetection-Android)**
+* **[FaceLivenessDetection-iOS](https://github.com/Faceplugin-ltd/FaceLivenessDetection-iOS)**
+* **[FaceLivenessDetection-Linux](https://github.com/Faceplugin-ltd/FaceLivenessDetection-Linux)**
+* **[FaceRecognition-LivenessDetection-React](https://github.com/Faceplugin-ltd/FaceRecognition-LivenessDetection-React)**
+* **[FaceRecognition-LivenessDetection-Vue](https://github.com/Faceplugin-ltd/FaceRecognition-LivenessDetection-Vue)**
+* **[Face Recognition SDK](https://github.com/Faceplugin-ltd/Face-Recognition-SDK)**
+* **[Liveness Detection SDK](https://github.com/Faceplugin-ltd/Face-Liveness-Detection-SDK)**
+* **[ID Card Recognition](https://github.com/Faceplugin-ltd/ID-Card-Recognition)**
+
+## Contact
+<div align="left">
+<a target="_blank" href="mailto:[email protected]"><img src="https://img.shields.io/badge/[email protected]?logo=gmail " alt="faceplugin.com"></a>&emsp;
+<a target="_blank" href="https://t.me/faceplugin"><img src="https://img.shields.io/badge/[email protected]?logo=telegram " alt="faceplugin.com"></a>&emsp;
+<a target="_blank" href="https://wa.me/+14422295661"><img src="https://img.shields.io/badge/whatsapp-faceplugin-blue.svg?logo=whatsapp " alt="faceplugin.com"></a>
+</div>
diff --git a/face_detect/detect_imgs.py b/face_detect/detect_imgs.py
new file mode 100644
index 0000000..59f546f
--- /dev/null
+++ b/face_detect/detect_imgs.py
@@ -0,0 +1,65 @@
+"""
+This code is used to batch detect images in a folder.
+"""
+
+import os
+import sys
+import cv2
+import numpy as np
+import torch
+
+from face_detect.vision.ssd.config.fd_config import define_img_size
+
+input_size = 320
+test_device = 'cpu'
+net_type = 'slim'
+threshold = 0.6
+candidate_size = 1500
+
+define_img_size(input_size) # must put define_img_size() before 'import create_mb_tiny_fd, create_mb_tiny_fd_predictor'
+
+from face_detect.vision.ssd.mb_tiny_fd import create_mb_tiny_fd, create_mb_tiny_fd_predictor
+from face_detect.vision.ssd.mb_tiny_RFB_fd import create_Mb_Tiny_RFB_fd, create_Mb_Tiny_RFB_fd_predictor
+
+label_path = "./face_detect/models/voc-model-labels.txt"
+test_device = test_device
+
+class_names = [name.strip() for name in open(label_path).readlines()]
+if net_type == 'slim':
+ model_path = "./face_detect/models/pretrained/version-slim-320.pth"
+ # model_path = "./face_detect/models/pretrained/version-slim-640.pth"
+ net = create_mb_tiny_fd(len(class_names), is_test=True, device=test_device)
+ predictor = create_mb_tiny_fd_predictor(net, candidate_size=candidate_size, device=test_device)
+elif net_type == 'RFB':
+ model_path = "./face_detect/models/pretrained/version-RFB-320.pth"
+ # model_path = "./face_detect/models/pretrained/version-RFB-640.pth"
+ net = create_Mb_Tiny_RFB_fd(len(class_names), is_test=True, device=test_device)
+ predictor = create_Mb_Tiny_RFB_fd_predictor(net, candidate_size=candidate_size, device=test_device)
+else:
+ print("The net type is wrong!")
+ sys.exit(1)
+net.load(model_path)
+
+def get_face_boundingbox(orig_image):
+ """
+ Description:
+ In input image, detect face
+
+ Args:
+ orig_image: input BGR image.
+ """
+ boxes, labels, probs = predictor.predict(cv2.cvtColor(orig_image, cv2.COLOR_BGR2RGB), candidate_size / 2, threshold)
+
+ if len(boxes) == 0:
+ return torch.tensor([]), torch.tensor([])
+
+ height, width, _ = orig_image.shape
+ valid_face = np.logical_and(
+ np.logical_and(boxes[:,0] >= 0, boxes[:,1] >= 0),
+ np.logical_and(boxes[:,2] < width, boxes[:,3] < height)
+ )
+
+ boxes = boxes[valid_face]
+ probs = probs[valid_face]
+
+ return boxes, probs
diff --git a/face_detect/models/pretrained/version-slim-320.pth b/face_detect/models/pretrained/version-slim-320.pth
new file mode 100644
index 0000000..bfd7379
Binary files /dev/null and b/face_detect/models/pretrained/version-slim-320.pth differ
diff --git a/face_detect/models/voc-model-labels.txt b/face_detect/models/voc-model-labels.txt
new file mode 100644
index 0000000..f80c069
--- /dev/null
+++ b/face_detect/models/voc-model-labels.txt
@@ -0,0 +1,2 @@
+BACKGROUND
+face
\ No newline at end of file
diff --git a/face_detect/vision/__init__.py b/face_detect/vision/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/face_detect/vision/nn/__init__.py b/face_detect/vision/nn/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/face_detect/vision/nn/mb_tiny.py b/face_detect/vision/nn/mb_tiny.py
new file mode 100644
index 0000000..7cade4f
--- /dev/null
+++ b/face_detect/vision/nn/mb_tiny.py
@@ -0,0 +1,51 @@
+import torch.nn as nn
+import torch.nn.functional as F
+
+
+class Mb_Tiny(nn.Module):
+
+ def __init__(self, num_classes=2):
+ super(Mb_Tiny, self).__init__()
+ self.base_channel = 8 * 2
+
+ def conv_bn(inp, oup, stride):
+ return nn.Sequential(
+ nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
+ nn.BatchNorm2d(oup),
+ nn.ReLU(inplace=True)
+ )
+
+ def conv_dw(inp, oup, stride):
+ return nn.Sequential(
+ nn.Conv2d(inp, inp, 3, stride, 1, groups=inp, bias=False),
+ nn.BatchNorm2d(inp),
+ nn.ReLU(inplace=True),
+
+ nn.Conv2d(inp, oup, 1, 1, 0, bias=False),
+ nn.BatchNorm2d(oup),
+ nn.ReLU(inplace=True),
+ )
+
+ self.model = nn.Sequential(
+ conv_bn(3, self.base_channel, 2), # 160*120
+ conv_dw(self.base_channel, self.base_channel * 2, 1),
+ conv_dw(self.base_channel * 2, self.base_channel * 2, 2), # 80*60
+ conv_dw(self.base_channel * 2, self.base_channel * 2, 1),
+ conv_dw(self.base_channel * 2, self.base_channel * 4, 2), # 40*30
+ conv_dw(self.base_channel * 4, self.base_channel * 4, 1),
+ conv_dw(self.base_channel * 4, self.base_channel * 4, 1),
+ conv_dw(self.base_channel * 4, self.base_channel * 4, 1),
+ conv_dw(self.base_channel * 4, self.base_channel * 8, 2), # 20*15
+ conv_dw(self.base_channel * 8, self.base_channel * 8, 1),
+ conv_dw(self.base_channel * 8, self.base_channel * 8, 1),
+ conv_dw(self.base_channel * 8, self.base_channel * 16, 2), # 10*8
+ conv_dw(self.base_channel * 16, self.base_channel * 16, 1)
+ )
+ self.fc = nn.Linear(1024, num_classes)
+
+ def forward(self, x):
+ x = self.model(x)
+ x = F.avg_pool2d(x, 7)
+ x = x.view(-1, 1024)
+ x = self.fc(x)
+ return x
diff --git a/face_detect/vision/nn/mb_tiny_RFB.py b/face_detect/vision/nn/mb_tiny_RFB.py
new file mode 100644
index 0000000..432186d
--- /dev/null
+++ b/face_detect/vision/nn/mb_tiny_RFB.py
@@ -0,0 +1,118 @@
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+
+class BasicConv(nn.Module):
+
+ def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1, groups=1, relu=True, bn=True):
+ super(BasicConv, self).__init__()
+ self.out_channels = out_planes
+ if bn:
+ self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups, bias=False)
+ self.bn = nn.BatchNorm2d(out_planes, eps=1e-5, momentum=0.01, affine=True)
+ self.relu = nn.ReLU(inplace=True) if relu else None
+ else:
+ self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups, bias=True)
+ self.bn = None
+ self.relu = nn.ReLU(inplace=True) if relu else None
+
+ def forward(self, x):
+ x = self.conv(x)
+ if self.bn is not None:
+ x = self.bn(x)
+ if self.relu is not None:
+ x = self.relu(x)
+ return x
+
+
+class BasicRFB(nn.Module):
+
+ def __init__(self, in_planes, out_planes, stride=1, scale=0.1, map_reduce=8, vision=1, groups=1):
+ super(BasicRFB, self).__init__()
+ self.scale = scale
+ self.out_channels = out_planes
+ inter_planes = in_planes // map_reduce
+
+ self.branch0 = nn.Sequential(
+ BasicConv(in_planes, inter_planes, kernel_size=1, stride=1, groups=groups, relu=False),
+ BasicConv(inter_planes, 2 * inter_planes, kernel_size=(3, 3), stride=stride, padding=(1, 1), groups=groups),
+ BasicConv(2 * inter_planes, 2 * inter_planes, kernel_size=3, stride=1, padding=vision + 1, dilation=vision + 1, relu=False, groups=groups)
+ )
+ self.branch1 = nn.Sequential(
+ BasicConv(in_planes, inter_planes, kernel_size=1, stride=1, groups=groups, relu=False),
+ BasicConv(inter_planes, 2 * inter_planes, kernel_size=(3, 3), stride=stride, padding=(1, 1), groups=groups),
+ BasicConv(2 * inter_planes, 2 * inter_planes, kernel_size=3, stride=1, padding=vision + 2, dilation=vision + 2, relu=False, groups=groups)
+ )
+ self.branch2 = nn.Sequential(
+ BasicConv(in_planes, inter_planes, kernel_size=1, stride=1, groups=groups, relu=False),
+ BasicConv(inter_planes, (inter_planes // 2) * 3, kernel_size=3, stride=1, padding=1, groups=groups),
+ BasicConv((inter_planes // 2) * 3, 2 * inter_planes, kernel_size=3, stride=stride, padding=1, groups=groups),
+ BasicConv(2 * inter_planes, 2 * inter_planes, kernel_size=3, stride=1, padding=vision + 4, dilation=vision + 4, relu=False, groups=groups)
+ )
+
+ self.ConvLinear = BasicConv(6 * inter_planes, out_planes, kernel_size=1, stride=1, relu=False)
+ self.shortcut = BasicConv(in_planes, out_planes, kernel_size=1, stride=stride, relu=False)
+ self.relu = nn.ReLU(inplace=False)
+
+ def forward(self, x):
+ x0 = self.branch0(x)
+ x1 = self.branch1(x)
+ x2 = self.branch2(x)
+
+ out = torch.cat((x0, x1, x2), 1)
+ out = self.ConvLinear(out)
+ short = self.shortcut(x)
+ out = out * self.scale + short
+ out = self.relu(out)
+
+ return out
+
+
+class Mb_Tiny_RFB(nn.Module):
+
+ def __init__(self, num_classes=2):
+ super(Mb_Tiny_RFB, self).__init__()
+ self.base_channel = 8 * 2
+
+ def conv_bn(inp, oup, stride):
+ return nn.Sequential(
+ nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
+ nn.BatchNorm2d(oup),
+ nn.ReLU(inplace=True)
+ )
+
+ def conv_dw(inp, oup, stride):
+ return nn.Sequential(
+ nn.Conv2d(inp, inp, 3, stride, 1, groups=inp, bias=False),
+ nn.BatchNorm2d(inp),
+ nn.ReLU(inplace=True),
+
+ nn.Conv2d(inp, oup, 1, 1, 0, bias=False),
+ nn.BatchNorm2d(oup),
+ nn.ReLU(inplace=True),
+ )
+
+ self.model = nn.Sequential(
+ conv_bn(3, self.base_channel, 2), # 160*120
+ conv_dw(self.base_channel, self.base_channel * 2, 1),
+ conv_dw(self.base_channel * 2, self.base_channel * 2, 2), # 80*60
+ conv_dw(self.base_channel * 2, self.base_channel * 2, 1),
+ conv_dw(self.base_channel * 2, self.base_channel * 4, 2), # 40*30
+ conv_dw(self.base_channel * 4, self.base_channel * 4, 1),
+ conv_dw(self.base_channel * 4, self.base_channel * 4, 1),
+ BasicRFB(self.base_channel * 4, self.base_channel * 4, stride=1, scale=1.0),
+ conv_dw(self.base_channel * 4, self.base_channel * 8, 2), # 20*15
+ conv_dw(self.base_channel * 8, self.base_channel * 8, 1),
+ conv_dw(self.base_channel * 8, self.base_channel * 8, 1),
+ conv_dw(self.base_channel * 8, self.base_channel * 16, 2), # 10*8
+ conv_dw(self.base_channel * 16, self.base_channel * 16, 1)
+ )
+ self.fc = nn.Linear(1024, num_classes)
+
+ def forward(self, x):
+ x = self.model(x)
+ x = F.avg_pool2d(x, 7)
+ x = x.view(-1, 1024)
+ x = self.fc(x)
+ return x
diff --git a/face_detect/vision/nn/multibox_loss.py b/face_detect/vision/nn/multibox_loss.py
new file mode 100644
index 0000000..a312882
--- /dev/null
+++ b/face_detect/vision/nn/multibox_loss.py
@@ -0,0 +1,46 @@
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from ..utils import box_utils
+
+
+class MultiboxLoss(nn.Module):
+ def __init__(self, priors, neg_pos_ratio,
+ center_variance, size_variance, device):
+ """Implement SSD Multibox Loss.
+
+ Basically, Multibox loss combines classification loss
+ and Smooth L1 regression loss.
+ """
+ super(MultiboxLoss, self).__init__()
+ self.neg_pos_ratio = neg_pos_ratio
+ self.center_variance = center_variance
+ self.size_variance = size_variance
+ self.priors = priors
+ self.priors.to(device)
+
+ def forward(self, confidence, predicted_locations, labels, gt_locations):
+ """Compute classification loss and smooth l1 loss.
+
+ Args:
+ confidence (batch_size, num_priors, num_classes): class predictions.
+ locations (batch_size, num_priors, 4): predicted locations.
+ labels (batch_size, num_priors): real labels of all the priors.
+ boxes (batch_size, num_priors, 4): real boxes corresponding all the priors.
+ """
+ num_classes = confidence.size(2)
+ with torch.no_grad():
+ # derived from cross_entropy=sum(log(p))
+ loss = -F.log_softmax(confidence, dim=2)[:, :, 0]
+ mask = box_utils.hard_negative_mining(loss, labels, self.neg_pos_ratio)
+
+ confidence = confidence[mask, :]
+ classification_loss = F.cross_entropy(confidence.reshape(-1, num_classes), labels[mask], reduction='sum')
+ pos_mask = labels > 0
+ predicted_locations = predicted_locations[pos_mask, :].reshape(-1, 4)
+ gt_locations = gt_locations[pos_mask, :].reshape(-1, 4)
+ smooth_l1_loss = F.smooth_l1_loss(predicted_locations, gt_locations, reduction='sum') # smooth_l1_loss
+ # smooth_l1_loss = F.mse_loss(predicted_locations, gt_locations, reduction='sum') #l2 loss
+ num_pos = gt_locations.size(0)
+ return smooth_l1_loss / num_pos, classification_loss / num_pos
diff --git a/face_detect/vision/ssd/__init__.py b/face_detect/vision/ssd/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/face_detect/vision/ssd/config/__init__.py b/face_detect/vision/ssd/config/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/face_detect/vision/ssd/config/fd_config.py b/face_detect/vision/ssd/config/fd_config.py
new file mode 100644
index 0000000..0d23f2a
--- /dev/null
+++ b/face_detect/vision/ssd/config/fd_config.py
@@ -0,0 +1,41 @@
+import numpy as np
+
+from face_detect.vision.utils.box_utils import generate_priors
+
+image_mean_test = image_mean = np.array([127, 127, 127])
+image_std = 128.0
+iou_threshold = 0.3
+center_variance = 0.1
+size_variance = 0.2
+
+min_boxes = [[10, 16, 24], [32, 48], [64, 96], [128, 192, 256]]
+shrinkage_list = []
+image_size = [320, 240] # default input size 320*240
+feature_map_w_h_list = [[40, 20, 10, 5], [30, 15, 8, 4]] # default feature map size
+priors = []
+
+
+def define_img_size(size):
+ global image_size, feature_map_w_h_list, priors
+ img_size_dict = {128: [128, 96],
+ 160: [160, 120],
+ 320: [320, 240],
+ 480: [480, 360],
+ 640: [640, 480],
+ 1280: [1280, 960]}
+ image_size = img_size_dict[size]
+
+ feature_map_w_h_list_dict = {128: [[16, 8, 4, 2], [12, 6, 3, 2]],
+ 160: [[20, 10, 5, 3], [15, 8, 4, 2]],
+ 320: [[40, 20, 10, 5], [30, 15, 8, 4]],
+ 480: [[60, 30, 15, 8], [45, 23, 12, 6]],
+ 640: [[80, 40, 20, 10], [60, 30, 15, 8]],
+ 1280: [[160, 80, 40, 20], [120, 60, 30, 15]]}
+ feature_map_w_h_list = feature_map_w_h_list_dict[size]
+
+ for i in range(0, len(image_size)):
+ item_list = []
+ for k in range(0, len(feature_map_w_h_list[i])):
+ item_list.append(image_size[i] / feature_map_w_h_list[i][k])
+ shrinkage_list.append(item_list)
+ priors = generate_priors(feature_map_w_h_list, shrinkage_list, image_size, min_boxes)
diff --git a/face_detect/vision/ssd/data_preprocessing.py b/face_detect/vision/ssd/data_preprocessing.py
new file mode 100644
index 0000000..170b1b1
--- /dev/null
+++ b/face_detect/vision/ssd/data_preprocessing.py
@@ -0,0 +1,61 @@
+from ..transforms.transforms import *
+
+
+class TrainAugmentation:
+ def __init__(self, size, mean=0, std=1.0):
+ """
+ Args:
+ size: the size the of final image.
+ mean: mean pixel value per channel.
+ """
+ self.mean = mean
+ self.size = size
+ self.augment = Compose([
+ ConvertFromInts(),
+ PhotometricDistort(),
+ RandomSampleCrop_v2(),
+ RandomMirror(),
+ ToPercentCoords(),
+ Resize(self.size),
+ SubtractMeans(self.mean),
+ lambda img, boxes=None, labels=None: (img / std, boxes, labels),
+ ToTensor(),
+ ])
+
+ def __call__(self, img, boxes, labels):
+ """
+
+ Args:
+ img: the output of cv.imread in RGB layout.
+ boxes: boundding boxes in the form of (x1, y1, x2, y2).
+ labels: labels of boxes.
+ """
+ return self.augment(img, boxes, labels)
+
+
+class TestTransform:
+ def __init__(self, size, mean=0.0, std=1.0):
+ self.transform = Compose([
+ ToPercentCoords(),
+ Resize(size),
+ SubtractMeans(mean),
+ lambda img, boxes=None, labels=None: (img / std, boxes, labels),
+ ToTensor(),
+ ])
+
+ def __call__(self, image, boxes, labels):
+ return self.transform(image, boxes, labels)
+
+
+class PredictionTransform:
+ def __init__(self, size, mean=0.0, std=1.0):
+ self.transform = Compose([
+ Resize(size),
+ SubtractMeans(mean),
+ lambda img, boxes=None, labels=None: (img / std, boxes, labels),
+ ToTensor()
+ ])
+
+ def __call__(self, image):
+ image, _, _ = self.transform(image)
+ return image
diff --git a/face_detect/vision/ssd/mb_tiny_RFB_fd.py b/face_detect/vision/ssd/mb_tiny_RFB_fd.py
new file mode 100644
index 0000000..09327da
--- /dev/null
+++ b/face_detect/vision/ssd/mb_tiny_RFB_fd.py
@@ -0,0 +1,64 @@
+from torch.nn import Conv2d, Sequential, ModuleList, ReLU
+
+from face_detect.vision.nn.mb_tiny_RFB import Mb_Tiny_RFB
+from face_detect.vision.ssd.config import fd_config as config
+from face_detect.vision.ssd.predictor import Predictor
+from face_detect.vision.ssd.ssd import SSD
+
+
+def SeperableConv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0):
+ """Replace Conv2d with a depthwise Conv2d and Pointwise Conv2d.
+ """
+ return Sequential(
+ Conv2d(in_channels=in_channels, out_channels=in_channels, kernel_size=kernel_size,
+ groups=in_channels, stride=stride, padding=padding),
+ ReLU(),
+ Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1),
+ )
+
+
+def create_Mb_Tiny_RFB_fd(num_classes, is_test=False, device="cuda"):
+ base_net = Mb_Tiny_RFB(2)
+ base_net_model = base_net.model # disable dropout layer
+
+ source_layer_indexes = [
+ 8,
+ 11,
+ 13
+ ]
+ extras = ModuleList([
+ Sequential(
+ Conv2d(in_channels=base_net.base_channel * 16, out_channels=base_net.base_channel * 4, kernel_size=1),
+ ReLU(),
+ SeperableConv2d(in_channels=base_net.base_channel * 4, out_channels=base_net.base_channel * 16, kernel_size=3, stride=2, padding=1),
+ ReLU()
+ )
+ ])
+
+ regression_headers = ModuleList([
+ SeperableConv2d(in_channels=base_net.base_channel * 4, out_channels=3 * 4, kernel_size=3, padding=1),
+ SeperableConv2d(in_channels=base_net.base_channel * 8, out_channels=2 * 4, kernel_size=3, padding=1),
+ SeperableConv2d(in_channels=base_net.base_channel * 16, out_channels=2 * 4, kernel_size=3, padding=1),
+ Conv2d(in_channels=base_net.base_channel * 16, out_channels=3 * 4, kernel_size=3, padding=1)
+ ])
+
+ classification_headers = ModuleList([
+ SeperableConv2d(in_channels=base_net.base_channel * 4, out_channels=3 * num_classes, kernel_size=3, padding=1),
+ SeperableConv2d(in_channels=base_net.base_channel * 8, out_channels=2 * num_classes, kernel_size=3, padding=1),
+ SeperableConv2d(in_channels=base_net.base_channel * 16, out_channels=2 * num_classes, kernel_size=3, padding=1),
+ Conv2d(in_channels=base_net.base_channel * 16, out_channels=3 * num_classes, kernel_size=3, padding=1)
+ ])
+
+ return SSD(num_classes, base_net_model, source_layer_indexes,
+ extras, classification_headers, regression_headers, is_test=is_test, config=config, device=device)
+
+
+def create_Mb_Tiny_RFB_fd_predictor(net, candidate_size=200, nms_method=None, sigma=0.5, device=None):
+ predictor = Predictor(net, config.image_size, config.image_mean_test,
+ config.image_std,
+ nms_method=nms_method,
+ iou_threshold=config.iou_threshold,
+ candidate_size=candidate_size,
+ sigma=sigma,
+ device=device)
+ return predictor
diff --git a/face_detect/vision/ssd/mb_tiny_fd.py b/face_detect/vision/ssd/mb_tiny_fd.py
new file mode 100644
index 0000000..c79880b
--- /dev/null
+++ b/face_detect/vision/ssd/mb_tiny_fd.py
@@ -0,0 +1,64 @@
+from torch.nn import Conv2d, Sequential, ModuleList, ReLU
+
+from face_detect.vision.nn.mb_tiny import Mb_Tiny
+from face_detect.vision.ssd.config import fd_config as config
+from face_detect.vision.ssd.predictor import Predictor
+from face_detect.vision.ssd.ssd import SSD
+
+
+def SeperableConv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0):
+ """Replace Conv2d with a depthwise Conv2d and Pointwise Conv2d.
+ """
+ return Sequential(
+ Conv2d(in_channels=in_channels, out_channels=in_channels, kernel_size=kernel_size,
+ groups=in_channels, stride=stride, padding=padding),
+ ReLU(),
+ Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1),
+ )
+
+
+def create_mb_tiny_fd(num_classes, is_test=False, device="cuda"):
+ base_net = Mb_Tiny(2)
+ base_net_model = base_net.model # disable dropout layer
+
+ source_layer_indexes = [
+ 8,
+ 11,
+ 13
+ ]
+ extras = ModuleList([
+ Sequential(
+ Conv2d(in_channels=base_net.base_channel * 16, out_channels=base_net.base_channel * 4, kernel_size=1),
+ ReLU(),
+ SeperableConv2d(in_channels=base_net.base_channel * 4, out_channels=base_net.base_channel * 16, kernel_size=3, stride=2, padding=1),
+ ReLU()
+ )
+ ])
+
+ regression_headers = ModuleList([
+ SeperableConv2d(in_channels=base_net.base_channel * 4, out_channels=3 * 4, kernel_size=3, padding=1),
+ SeperableConv2d(in_channels=base_net.base_channel * 8, out_channels=2 * 4, kernel_size=3, padding=1),
+ SeperableConv2d(in_channels=base_net.base_channel * 16, out_channels=2 * 4, kernel_size=3, padding=1),
+ Conv2d(in_channels=base_net.base_channel * 16, out_channels=3 * 4, kernel_size=3, padding=1)
+ ])
+
+ classification_headers = ModuleList([
+ SeperableConv2d(in_channels=base_net.base_channel * 4, out_channels=3 * num_classes, kernel_size=3, padding=1),
+ SeperableConv2d(in_channels=base_net.base_channel * 8, out_channels=2 * num_classes, kernel_size=3, padding=1),
+ SeperableConv2d(in_channels=base_net.base_channel * 16, out_channels=2 * num_classes, kernel_size=3, padding=1),
+ Conv2d(in_channels=base_net.base_channel * 16, out_channels=3 * num_classes, kernel_size=3, padding=1)
+ ])
+
+ return SSD(num_classes, base_net_model, source_layer_indexes,
+ extras, classification_headers, regression_headers, is_test=is_test, config=config, device=device)
+
+
+def create_mb_tiny_fd_predictor(net, candidate_size=200, nms_method=None, sigma=0.5, device=None):
+ predictor = Predictor(net, config.image_size, config.image_mean_test,
+ config.image_std,
+ nms_method=nms_method,
+ iou_threshold=config.iou_threshold,
+ candidate_size=candidate_size,
+ sigma=sigma,
+ device=device)
+ return predictor
diff --git a/face_detect/vision/ssd/predictor.py b/face_detect/vision/ssd/predictor.py
new file mode 100644
index 0000000..110b70a
--- /dev/null
+++ b/face_detect/vision/ssd/predictor.py
@@ -0,0 +1,70 @@
+import torch
+
+from ..utils import box_utils
+from .data_preprocessing import PredictionTransform
+from ..utils.misc import Timer
+
+
+class Predictor:
+ def __init__(self, net, size, mean=0.0, std=1.0, nms_method=None,
+ iou_threshold=0.3, filter_threshold=0.01, candidate_size=200, sigma=0.5, device=None):
+ self.net = net
+ self.transform = PredictionTransform(size, mean, std)
+ self.iou_threshold = iou_threshold
+ self.filter_threshold = filter_threshold
+ self.candidate_size = candidate_size
+ self.nms_method = nms_method
+
+ self.sigma = sigma
+ if device:
+ self.device = device
+ else:
+ self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
+
+ self.net.to(self.device)
+ self.net.eval()
+
+ self.timer = Timer()
+
+ def predict(self, image, top_k=-1, prob_threshold=None):
+ cpu_device = torch.device("cpu")
+ height, width, _ = image.shape
+ image = self.transform(image)
+ images = image.unsqueeze(0)
+ images = images.to(self.device)
+ with torch.no_grad():
+ for i in range(1):
+ scores, boxes = self.net.forward(images)
+ boxes = boxes[0]
+ scores = scores[0]
+ if not prob_threshold:
+ prob_threshold = self.filter_threshold
+ # this version of nms is slower on GPU, so we move data to CPU.
+ boxes = boxes.to(cpu_device)
+ scores = scores.to(cpu_device)
+ picked_box_probs = []
+ picked_labels = []
+ for class_index in range(1, scores.size(1)):
+ probs = scores[:, class_index]
+ mask = probs > prob_threshold
+ probs = probs[mask]
+ if probs.size(0) == 0:
+ continue
+ subset_boxes = boxes[mask, :]
+ box_probs = torch.cat([subset_boxes, probs.reshape(-1, 1)], dim=1)
+ box_probs = box_utils.nms(box_probs, self.nms_method,
+ score_threshold=prob_threshold,
+ iou_threshold=self.iou_threshold,
+ sigma=self.sigma,
+ top_k=top_k,
+ candidate_size=self.candidate_size)
+ picked_box_probs.append(box_probs)
+ picked_labels.extend([class_index] * box_probs.size(0))
+ if not picked_box_probs:
+ return torch.tensor([]), torch.tensor([]), torch.tensor([])
+ picked_box_probs = torch.cat(picked_box_probs)
+ picked_box_probs[:, 0] *= width
+ picked_box_probs[:, 1] *= height
+ picked_box_probs[:, 2] *= width
+ picked_box_probs[:, 3] *= height
+ return picked_box_probs[:, :4], torch.tensor(picked_labels), picked_box_probs[:, 4]
diff --git a/face_detect/vision/ssd/ssd.py b/face_detect/vision/ssd/ssd.py
new file mode 100644
index 0000000..6704ed7
--- /dev/null
+++ b/face_detect/vision/ssd/ssd.py
@@ -0,0 +1,166 @@
+from collections import namedtuple
+from typing import List, Tuple
+
+import numpy as np
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from face_detect.vision.utils import box_utils
+
+GraphPath = namedtuple("GraphPath", ['s0', 'name', 's1'])
+
+
+class SSD(nn.Module):
+ def __init__(self, num_classes: int, base_net: nn.ModuleList, source_layer_indexes: List[int],
+ extras: nn.ModuleList, classification_headers: nn.ModuleList,
+ regression_headers: nn.ModuleList, is_test=False, config=None, device=None):
+ """Compose a SSD model using the given components.
+ """
+ super(SSD, self).__init__()
+
+ self.num_classes = num_classes
+ self.base_net = base_net
+ self.source_layer_indexes = source_layer_indexes
+ self.extras = extras
+ self.classification_headers = classification_headers
+ self.regression_headers = regression_headers
+ self.is_test = is_test
+ self.config = config
+
+ # register layers in source_layer_indexes by adding them to a module list
+ self.source_layer_add_ons = nn.ModuleList([t[1] for t in source_layer_indexes
+ if isinstance(t, tuple) and not isinstance(t, GraphPath)])
+ if device:
+ self.device = device
+ else:
+ self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
+ if is_test:
+ self.config = config
+ self.priors = config.priors.to(self.device)
+
+ def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ confidences = []
+ locations = []
+ start_layer_index = 0
+ header_index = 0
+ end_layer_index = 0
+ for end_layer_index in self.source_layer_indexes:
+ if isinstance(end_layer_index, GraphPath):
+ path = end_layer_index
+ end_layer_index = end_layer_index.s0
+ added_layer = None
+ elif isinstance(end_layer_index, tuple):
+ added_layer = end_layer_index[1]
+ end_layer_index = end_layer_index[0]
+ path = None
+ else:
+ added_layer = None
+ path = None
+ for layer in self.base_net[start_layer_index: end_layer_index]:
+ x = layer(x)
+ if added_layer:
+ y = added_layer(x)
+ else:
+ y = x
+ if path:
+ sub = getattr(self.base_net[end_layer_index], path.name)
+ for layer in sub[:path.s1]:
+ x = layer(x)
+ y = x
+ for layer in sub[path.s1:]:
+ x = layer(x)
+ end_layer_index += 1
+ start_layer_index = end_layer_index
+ confidence, location = self.compute_header(header_index, y)
+ header_index += 1
+ confidences.append(confidence)
+ locations.append(location)
+
+ for layer in self.base_net[end_layer_index:]:
+ x = layer(x)
+
+ for layer in self.extras:
+ x = layer(x)
+ confidence, location = self.compute_header(header_index, x)
+ header_index += 1
+ confidences.append(confidence)
+ locations.append(location)
+
+ confidences = torch.cat(confidences, 1)
+ locations = torch.cat(locations, 1)
+
+ if self.is_test:
+ confidences = F.softmax(confidences, dim=2)
+ boxes = box_utils.convert_locations_to_boxes(
+ locations, self.priors, self.config.center_variance, self.config.size_variance
+ )
+ boxes = box_utils.center_form_to_corner_form(boxes)
+ return confidences, boxes
+ else:
+ return confidences, locations
+
+ def compute_header(self, i, x):
+ confidence = self.classification_headers[i](x)
+ confidence = confidence.permute(0, 2, 3, 1).contiguous()
+ confidence = confidence.view(confidence.size(0), -1, self.num_classes)
+
+ location = self.regression_headers[i](x)
+ location = location.permute(0, 2, 3, 1).contiguous()
+ location = location.view(location.size(0), -1, 4)
+
+ return confidence, location
+
+ def init_from_base_net(self, model):
+ self.base_net.load_state_dict(torch.load(model, map_location=lambda storage, loc: storage), strict=True)
+ self.source_layer_add_ons.apply(_xavier_init_)
+ self.extras.apply(_xavier_init_)
+ self.classification_headers.apply(_xavier_init_)
+ self.regression_headers.apply(_xavier_init_)
+
+ def init_from_pretrained_ssd(self, model):
+ state_dict = torch.load(model, map_location=lambda storage, loc: storage)
+ state_dict = {k: v for k, v in state_dict.items() if not (k.startswith("classification_headers") or k.startswith("regression_headers"))}
+ model_dict = self.state_dict()
+ model_dict.update(state_dict)
+ self.load_state_dict(model_dict)
+ self.classification_headers.apply(_xavier_init_)
+ self.regression_headers.apply(_xavier_init_)
+
+ def init(self):
+ self.base_net.apply(_xavier_init_)
+ self.source_layer_add_ons.apply(_xavier_init_)
+ self.extras.apply(_xavier_init_)
+ self.classification_headers.apply(_xavier_init_)
+ self.regression_headers.apply(_xavier_init_)
+
+ def load(self, model):
+ self.load_state_dict(torch.load(model, map_location=lambda storage, loc: storage))
+
+ def save(self, model_path):
+ torch.save(self.state_dict(), model_path)
+
+
+class MatchPrior(object):
+ def __init__(self, center_form_priors, center_variance, size_variance, iou_threshold):
+ self.center_form_priors = center_form_priors
+ self.corner_form_priors = box_utils.center_form_to_corner_form(center_form_priors)
+ self.center_variance = center_variance
+ self.size_variance = size_variance
+ self.iou_threshold = iou_threshold
+
+ def __call__(self, gt_boxes, gt_labels):
+ if type(gt_boxes) is np.ndarray:
+ gt_boxes = torch.from_numpy(gt_boxes)
+ if type(gt_labels) is np.ndarray:
+ gt_labels = torch.from_numpy(gt_labels)
+ boxes, labels = box_utils.assign_priors(gt_boxes, gt_labels,
+ self.corner_form_priors, self.iou_threshold)
+ boxes = box_utils.corner_form_to_center_form(boxes)
+ locations = box_utils.convert_boxes_to_locations(boxes, self.center_form_priors, self.center_variance, self.size_variance)
+ return locations, labels
+
+
+def _xavier_init_(m: nn.Module):
+ if isinstance(m, nn.Conv2d):
+ nn.init.xavier_uniform_(m.weight)
diff --git a/face_detect/vision/transforms/__init__.py b/face_detect/vision/transforms/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/face_detect/vision/transforms/transforms.py b/face_detect/vision/transforms/transforms.py
new file mode 100644
index 0000000..c53b38e
--- /dev/null
+++ b/face_detect/vision/transforms/transforms.py
@@ -0,0 +1,541 @@
+# from https://github.com/amdegroot/ssd.pytorch
+
+
+import types
+
+import cv2
+import numpy as np
+import torch
+from numpy import random
+from torchvision import transforms
+
+
+def intersect(box_a, box_b):
+ max_xy = np.minimum(box_a[:, 2:], box_b[2:])
+ min_xy = np.maximum(box_a[:, :2], box_b[:2])
+ inter = np.clip((max_xy - min_xy), a_min=0, a_max=np.inf)
+ return inter[:, 0] * inter[:, 1]
+
+
+def jaccard_numpy(box_a, box_b):
+ """Compute the jaccard overlap of two sets of boxes. The jaccard overlap
+ is simply the intersection over union of two boxes.
+ E.g.:
+ A ∩ B / A ∪ B = A ∩ B / (area(A) + area(B) - A ∩ B)
+ Args:
+ box_a: Multiple bounding boxes, Shape: [num_boxes,4]
+ box_b: Single bounding box, Shape: [4]
+ Return:
+ jaccard overlap: Shape: [box_a.shape[0], box_a.shape[1]]
+ """
+ inter = intersect(box_a, box_b)
+ area_a = ((box_a[:, 2] - box_a[:, 0]) *
+ (box_a[:, 3] - box_a[:, 1])) # [A,B]
+ area_b = ((box_b[2] - box_b[0]) *
+ (box_b[3] - box_b[1])) # [A,B]
+ union = area_a + area_b - inter
+ return inter / union # [A,B]
+
+
+def object_converage_numpy(box_a, box_b):
+ """Compute the jaccard overlap of two sets of boxes. The jaccard overlap
+ is simply the intersection over union of two boxes.
+ E.g.:
+ A ∩ B / A ∪ B = A ∩ B / (area(A) + area(B) - A ∩ B)
+ Args:
+ box_a: Multiple bounding boxes, Shape: [num_boxes,4]
+ box_b: Single bounding box, Shape: [4]
+ Return:
+ jaccard overlap: Shape: [box_a.shape[0], box_a.shape[1]]
+ """
+ inter = intersect(box_a, box_b)
+ area_a = ((box_a[:, 2] - box_a[:, 0]) *
+ (box_a[:, 3] - box_a[:, 1])) # [A,B]
+ area_b = ((box_b[2] - box_b[0]) *
+ (box_b[3] - box_b[1])) # [A,B]
+ return inter / area_a # [A,B]
+
+
+class Compose(object):
+ """Composes several augmentations together.
+ Args:
+ transforms (List[Transform]): list of transforms to compose.
+ Example:
+ >>> augmentations.Compose([
+ >>> transforms.CenterCrop(10),
+ >>> transforms.ToTensor(),
+ >>> ])
+ """
+
+ def __init__(self, transforms):
+ self.transforms = transforms
+
+ def __call__(self, img, boxes=None, labels=None):
+ for t in self.transforms:
+ img, boxes, labels = t(img, boxes, labels)
+ return img, boxes, labels
+
+
+class Lambda(object):
+ """Applies a lambda as a transform."""
+
+ def __init__(self, lambd):
+ assert isinstance(lambd, types.LambdaType)
+ self.lambd = lambd
+
+ def __call__(self, img, boxes=None, labels=None):
+ return self.lambd(img, boxes, labels)
+
+
+class ConvertFromInts(object):
+ def __call__(self, image, boxes=None, labels=None):
+ return image.astype(np.float32), boxes, labels
+
+
+class SubtractMeans(object):
+ def __init__(self, mean):
+ self.mean = np.array(mean, dtype=np.float32)
+
+ def __call__(self, image, boxes=None, labels=None):
+ image = image.astype(np.float32)
+ image -= self.mean
+ return image.astype(np.float32), boxes, labels
+
+
+class imgprocess(object):
+ def __init__(self, std):
+ self.std = np.array(std, dtype=np.float32)
+
+ def __call__(self, image, boxes=None, labels=None):
+ image = image.astype(np.float32)
+ image /= self.std
+ return image.astype(np.float32), boxes, labels
+
+
+class ToAbsoluteCoords(object):
+ def __call__(self, image, boxes=None, labels=None):
+ height, width, channels = image.shape
+ boxes[:, 0] *= width
+ boxes[:, 2] *= width
+ boxes[:, 1] *= height
+ boxes[:, 3] *= height
+
+ return image, boxes, labels
+
+
+class ToPercentCoords(object):
+ def __call__(self, image, boxes=None, labels=None):
+ height, width, channels = image.shape
+ boxes[:, 0] /= width
+ boxes[:, 2] /= width
+ boxes[:, 1] /= height
+ boxes[:, 3] /= height
+
+ return image, boxes, labels
+
+
+class Resize(object):
+ def __init__(self, size=(300, 300)):
+ self.size = size
+
+ def __call__(self, image, boxes=None, labels=None):
+ image = cv2.resize(image, (self.size[0],
+ self.size[1]))
+ return image, boxes, labels
+
+
+class RandomSaturation(object):
+ def __init__(self, lower=0.5, upper=1.5):
+ self.lower = lower
+ self.upper = upper
+ assert self.upper >= self.lower, "contrast upper must be >= lower."
+ assert self.lower >= 0, "contrast lower must be non-negative."
+
+ def __call__(self, image, boxes=None, labels=None):
+ if random.randint(2):
+ image[:, :, 1] *= random.uniform(self.lower, self.upper)
+
+ return image, boxes, labels
+
+
+class RandomHue(object):
+ def __init__(self, delta=18.0):
+ assert delta >= 0.0 and delta <= 360.0
+ self.delta = delta
+
+ def __call__(self, image, boxes=None, labels=None):
+ if random.randint(2):
+ image[:, :, 0] += random.uniform(-self.delta, self.delta)
+ image[:, :, 0][image[:, :, 0] > 360.0] -= 360.0
+ image[:, :, 0][image[:, :, 0] < 0.0] += 360.0
+ return image, boxes, labels
+
+
+class RandomLightingNoise(object):
+ def __init__(self):
+ self.perms = ((0, 1, 2), (0, 2, 1),
+ (1, 0, 2), (1, 2, 0),
+ (2, 0, 1), (2, 1, 0))
+
+ def __call__(self, image, boxes=None, labels=None):
+ if random.randint(2):
+ swap = self.perms[random.randint(len(self.perms))]
+ shuffle = SwapChannels(swap) # shuffle channels
+ image = shuffle(image)
+ return image, boxes, labels
+
+
+class ConvertColor(object):
+ def __init__(self, current, transform):
+ self.transform = transform
+ self.current = current
+
+ def __call__(self, image, boxes=None, labels=None):
+ if self.current == 'BGR' and self.transform == 'HSV':
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
+ elif self.current == 'RGB' and self.transform == 'HSV':
+ image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
+ elif self.current == 'BGR' and self.transform == 'RGB':
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
+ elif self.current == 'HSV' and self.transform == 'BGR':
+ image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR)
+ elif self.current == 'HSV' and self.transform == "RGB":
+ image = cv2.cvtColor(image, cv2.COLOR_HSV2RGB)
+ else:
+ raise NotImplementedError
+ return image, boxes, labels
+
+
+class RandomContrast(object):
+ def __init__(self, lower=0.5, upper=1.5):
+ self.lower = lower
+ self.upper = upper
+ assert self.upper >= self.lower, "contrast upper must be >= lower."
+ assert self.lower >= 0, "contrast lower must be non-negative."
+
+ # expects float image
+ def __call__(self, image, boxes=None, labels=None):
+ if random.randint(2):
+ alpha = random.uniform(self.lower, self.upper)
+ image *= alpha
+ return image, boxes, labels
+
+
+class RandomBrightness(object):
+ def __init__(self, delta=32):
+ assert delta >= 0.0
+ assert delta <= 255.0
+ self.delta = delta
+
+ def __call__(self, image, boxes=None, labels=None):
+ if random.randint(2):
+ delta = random.uniform(-self.delta, self.delta)
+ image += delta
+ return image, boxes, labels
+
+
+class ToCV2Image(object):
+ def __call__(self, tensor, boxes=None, labels=None):
+ return tensor.cpu().numpy().astype(np.float32).transpose((1, 2, 0)), boxes, labels
+
+
+class ToTensor(object):
+ def __call__(self, cvimage, boxes=None, labels=None):
+ return torch.from_numpy(cvimage.astype(np.float32)).permute(2, 0, 1), boxes, labels
+
+
+class RandomSampleCrop(object):
+ """Crop
+ Arguments:
+ img (Image): the image being input during training
+ boxes (Tensor): the original bounding boxes in pt form
+ labels (Tensor): the class labels for each bbox
+ mode (float tuple): the min and max jaccard overlaps
+ Return:
+ (img, boxes, classes)
+ img (Image): the cropped image
+ boxes (Tensor): the adjusted bounding boxes in pt form
+ labels (Tensor): the class labels for each bbox
+ """
+
+ def __init__(self):
+ self.sample_options = (
+ # using entire original input image
+ None,
+ # sample a patch s.t. MIN jaccard w/ obj in .1,.3,.4,.7,.9
+ (0.1, None),
+ (0.3, None),
+ (0.7, None),
+ (0.9, None),
+ # randomly sample a patch
+ (None, None),
+ )
+
+ def __call__(self, image, boxes=None, labels=None):
+ height, width, _ = image.shape
+ while True:
+ # randomly choose a mode
+ mode = random.choice(self.sample_options)
+ if mode is None:
+ return image, boxes, labels
+
+ min_iou, max_iou = mode
+ if min_iou is None:
+ min_iou = float('-inf')
+ if max_iou is None:
+ max_iou = float('inf')
+
+ # max trails (50)
+ for _ in range(50):
+ current_image = image
+
+ w = random.uniform(0.3 * width, width)
+ h = random.uniform(0.3 * height, height)
+
+ # aspect ratio constraint b/t .5 & 2
+ if h / w < 0.5 or h / w > 2:
+ continue
+
+ left = random.uniform(width - w)
+ top = random.uniform(height - h)
+
+ # convert to integer rect x1,y1,x2,y2
+ rect = np.array([int(left), int(top), int(left + w), int(top + h)])
+
+ # calculate IoU (jaccard overlap) b/t the cropped and gt boxes
+ overlap = jaccard_numpy(boxes, rect)
+
+ # is min and max overlap constraint satisfied? if not try again
+ if overlap.max() < min_iou or overlap.min() > max_iou:
+ continue
+
+ # cut the crop from the image
+ current_image = current_image[rect[1]:rect[3], rect[0]:rect[2],
+ :]
+
+ # keep overlap with gt box IF center in sampled patch
+ centers = (boxes[:, :2] + boxes[:, 2:]) / 2.0
+
+ # mask in all gt boxes that above and to the left of centers
+ m1 = (rect[0] < centers[:, 0]) * (rect[1] < centers[:, 1])
+
+ # mask in all gt boxes that under and to the right of centers
+ m2 = (rect[2] > centers[:, 0]) * (rect[3] > centers[:, 1])
+
+ # mask in that both m1 and m2 are true
+ mask = m1 * m2
+
+ # have any valid boxes? try again if not
+ if not mask.any():
+ continue
+
+ # take only matching gt boxes
+ current_boxes = boxes[mask, :].copy()
+
+ # take only matching gt labels
+ current_labels = labels[mask]
+
+ # should we use the box left and top corner or the crop's
+ current_boxes[:, :2] = np.maximum(current_boxes[:, :2],
+ rect[:2])
+ # adjust to crop (by substracting crop's left,top)
+ current_boxes[:, :2] -= rect[:2]
+
+ current_boxes[:, 2:] = np.minimum(current_boxes[:, 2:],
+ rect[2:])
+ # adjust to crop (by substracting crop's left,top)
+ current_boxes[:, 2:] -= rect[:2]
+
+ return current_image, current_boxes, current_labels
+
+
+class RandomSampleCrop_v2(object):
+ """Crop
+ Arguments:
+ img (Image): the image being input during training
+ boxes (Tensor): the original bounding boxes in pt form
+ labels (Tensor): the class labels for each bbox
+ mode (float tuple): the min and max jaccard overlaps
+ Return:
+ (img, boxes, classes)
+ img (Image): the cropped image
+ boxes (Tensor): the adjusted bounding boxes in pt form
+ labels (Tensor): the class labels for each bbox
+ """
+
+ def __init__(self):
+ self.sample_options = (
+ # using entire original input image
+ None,
+ # sample a patch s.t. MIN jaccard w/ obj in .1,.3,.4,.7,.9
+
+ # randomly sample a patch
+ (1, None),
+ (1, None),
+ (1, None),
+ (1, None),
+ )
+
+ def __call__(self, image, boxes=None, labels=None):
+ height, width, _ = image.shape
+ while True:
+ # randomly choose a mode
+ mode = random.choice(self.sample_options)
+ if mode is None:
+ return image, boxes, labels
+
+ min_iou, max_iou = mode
+ if min_iou is None:
+ min_iou = float('-inf')
+ if max_iou is None:
+ max_iou = float('inf')
+
+ # max trails (50)
+ for _ in range(50):
+ current_image = image
+
+ w = random.uniform(0.3 * width, width)
+ h = random.uniform(0.3 * height, height)
+
+ # aspect ratio constraint b/t .5 & 2
+ if h / w != 1:
+ continue
+ left = random.uniform(width - w)
+ top = random.uniform(height - h)
+
+ # convert to integer rect x1,y1,x2,y2
+ rect = np.array([int(left), int(top), int(left + w), int(top + h)])
+
+ # calculate IoU (jaccard overlap) b/t the cropped and gt boxes
+ overlap = object_converage_numpy(boxes, rect)
+
+ # is min and max overlap constraint satisfied? if not try again
+ if overlap.max() < min_iou or overlap.min() > max_iou:
+ continue
+
+ # cut the crop from the image
+ current_image = current_image[rect[1]:rect[3], rect[0]:rect[2],
+ :]
+
+ # keep overlap with gt box IF center in sampled patch
+ centers = (boxes[:, :2] + boxes[:, 2:]) / 2.0
+
+ # mask in all gt boxes that above and to the left of centers
+ m1 = (rect[0] < centers[:, 0]) * (rect[1] < centers[:, 1])
+
+ # mask in all gt boxes that under and to the right of centers
+ m2 = (rect[2] > centers[:, 0]) * (rect[3] > centers[:, 1])
+
+ # mask in that both m1 and m2 are true
+ mask = m1 * m2
+
+ # have any valid boxes? try again if not
+ if not mask.any():
+ continue
+
+ # take only matching gt boxes
+ current_boxes = boxes[mask, :].copy()
+
+ # take only matching gt labels
+ current_labels = labels[mask]
+
+ # should we use the box left and top corner or the crop's
+ current_boxes[:, :2] = np.maximum(current_boxes[:, :2],
+ rect[:2])
+ # adjust to crop (by substracting crop's left,top)
+ current_boxes[:, :2] -= rect[:2]
+
+ current_boxes[:, 2:] = np.minimum(current_boxes[:, 2:],
+ rect[2:])
+ # adjust to crop (by substracting crop's left,top)
+ current_boxes[:, 2:] -= rect[:2]
+
+ return current_image, current_boxes, current_labels
+
+
+class Expand(object):
+ def __init__(self, mean):
+ self.mean = mean
+
+ def __call__(self, image, boxes, labels):
+ if random.randint(2):
+ return image, boxes, labels
+
+ height, width, depth = image.shape
+ ratio = random.uniform(1, 4)
+ left = random.uniform(0, width * ratio - width)
+ top = random.uniform(0, height * ratio - height)
+
+ expand_image = np.zeros(
+ (int(height * ratio), int(width * ratio), depth),
+ dtype=image.dtype)
+ expand_image[:, :, :] = self.mean
+ expand_image[int(top):int(top + height),
+ int(left):int(left + width)] = image
+ image = expand_image
+
+ boxes = boxes.copy()
+ boxes[:, :2] += (int(left), int(top))
+ boxes[:, 2:] += (int(left), int(top))
+
+ return image, boxes, labels
+
+
+class RandomMirror(object):
+ def __call__(self, image, boxes, classes):
+ _, width, _ = image.shape
+ if random.randint(2):
+ image = image[:, ::-1]
+ boxes = boxes.copy()
+ boxes[:, 0::2] = width - boxes[:, 2::-2]
+ return image, boxes, classes
+
+
+class SwapChannels(object):
+ """Transforms a tensorized image by swapping the channels in the order
+ specified in the swap tuple.
+ Args:
+ swaps (int triple): final order of channels
+ eg: (2, 1, 0)
+ """
+
+ def __init__(self, swaps):
+ self.swaps = swaps
+
+ def __call__(self, image):
+ """
+ Args:
+ image (Tensor): image tensor to be transformed
+ Return:
+ a tensor with channels swapped according to swap
+ """
+ # if torch.is_tensor(image):
+ # image = image.data.cpu().numpy()
+ # else:
+ # image = np.array(image)
+ image = image[:, :, self.swaps]
+ return image
+
+
+class PhotometricDistort(object):
+ def __init__(self):
+ self.pd = [
+ RandomContrast(), # RGB
+ ConvertColor(current="RGB", transform='HSV'), # HSV
+ RandomSaturation(), # HSV
+ RandomHue(), # HSV
+ ConvertColor(current='HSV', transform='RGB'), # RGB
+ RandomContrast() # RGB
+ ]
+ self.rand_brightness = RandomBrightness()
+ self.rand_light_noise = RandomLightingNoise()
+
+ def __call__(self, image, boxes, labels):
+ im = image.copy()
+ im, boxes, labels = self.rand_brightness(im, boxes, labels)
+ if random.randint(2):
+ distort = Compose(self.pd[:-1])
+ else:
+ distort = Compose(self.pd[1:])
+ im, boxes, labels = distort(im, boxes, labels)
+ return self.rand_light_noise(im, boxes, labels)
diff --git a/face_detect/vision/utils/__init__.py b/face_detect/vision/utils/__init__.py
new file mode 100644
index 0000000..0789bdb
--- /dev/null
+++ b/face_detect/vision/utils/__init__.py
@@ -0,0 +1 @@
+from .misc import *
diff --git a/face_detect/vision/utils/box_utils.py b/face_detect/vision/utils/box_utils.py
new file mode 100644
index 0000000..32be008
--- /dev/null
+++ b/face_detect/vision/utils/box_utils.py
@@ -0,0 +1,241 @@
+import math
+
+import torch
+
+
+def generate_priors(feature_map_list, shrinkage_list, image_size, min_boxes, clamp=True) -> torch.Tensor:
+ priors = []
+ for index in range(0, len(feature_map_list[0])):
+ scale_w = image_size[0] / shrinkage_list[0][index]
+ scale_h = image_size[1] / shrinkage_list[1][index]
+ for j in range(0, feature_map_list[1][index]):
+ for i in range(0, feature_map_list[0][index]):
+ x_center = (i + 0.5) / scale_w
+ y_center = (j + 0.5) / scale_h
+
+ for min_box in min_boxes[index]:
+ w = min_box / image_size[0]
+ h = min_box / image_size[1]
+ priors.append([
+ x_center,
+ y_center,
+ w,
+ h
+ ])
+ print("priors nums:{}".format(len(priors)))
+ priors = torch.tensor(priors)
+ if clamp:
+ torch.clamp(priors, 0.0, 1.0, out=priors)
+ return priors
+
+
+def convert_locations_to_boxes(locations, priors, center_variance,
+ size_variance):
+ """Convert regressional location results of SSD into boxes in the form of (center_x, center_y, h, w).
+
+ The conversion:
+ $$predicted\_center * center_variance = \frac {real\_center - prior\_center} {prior\_hw}$$
+ $$exp(predicted\_hw * size_variance) = \frac {real\_hw} {prior\_hw}$$
+ We do it in the inverse direction here.
+ Args:
+ locations (batch_size, num_priors, 4): the regression output of SSD. It will contain the outputs as well.
+ priors (num_priors, 4) or (batch_size/1, num_priors, 4): prior boxes.
+ center_variance: a float used to change the scale of center.
+ size_variance: a float used to change of scale of size.
+ Returns:
+ boxes: priors: [[center_x, center_y, h, w]]. All the values
+ are relative to the image size.
+ """
+ # priors can have one dimension less.
+ if priors.dim() + 1 == locations.dim():
+ priors = priors.unsqueeze(0)
+ return torch.cat([
+ locations[..., :2] * center_variance * priors[..., 2:] + priors[..., :2],
+ torch.exp(locations[..., 2:] * size_variance) * priors[..., 2:]
+ ], dim=locations.dim() - 1)
+
+
+def convert_boxes_to_locations(center_form_boxes, center_form_priors, center_variance, size_variance):
+ # priors can have one dimension less
+ if center_form_priors.dim() + 1 == center_form_boxes.dim():
+ center_form_priors = center_form_priors.unsqueeze(0)
+ return torch.cat([
+ (center_form_boxes[..., :2] - center_form_priors[..., :2]) / center_form_priors[..., 2:] / center_variance,
+ torch.log(center_form_boxes[..., 2:] / center_form_priors[..., 2:]) / size_variance
+ ], dim=center_form_boxes.dim() - 1)
+
+
+def area_of(left_top, right_bottom) -> torch.Tensor:
+ """Compute the areas of rectangles given two corners.
+
+ Args:
+ left_top (N, 2): left top corner.
+ right_bottom (N, 2): right bottom corner.
+
+ Returns:
+ area (N): return the area.
+ """
+ hw = torch.clamp(right_bottom - left_top, min=0.0)
+ return hw[..., 0] * hw[..., 1]
+
+
+def iou_of(boxes0, boxes1, eps=1e-5):
+ """Return intersection-over-union (Jaccard index) of boxes.
+
+ Args:
+ boxes0 (N, 4): ground truth boxes.
+ boxes1 (N or 1, 4): predicted boxes.
+ eps: a small number to avoid 0 as denominator.
+ Returns:
+ iou (N): IoU values.
+ """
+ overlap_left_top = torch.max(boxes0[..., :2], boxes1[..., :2])
+ overlap_right_bottom = torch.min(boxes0[..., 2:], boxes1[..., 2:])
+
+ overlap_area = area_of(overlap_left_top, overlap_right_bottom)
+ area0 = area_of(boxes0[..., :2], boxes0[..., 2:])
+ area1 = area_of(boxes1[..., :2], boxes1[..., 2:])
+ return overlap_area / (area0 + area1 - overlap_area + eps)
+
+
+def assign_priors(gt_boxes, gt_labels, corner_form_priors,
+ iou_threshold):
+ """Assign ground truth boxes and targets to priors.
+
+ Args:
+ gt_boxes (num_targets, 4): ground truth boxes.
+ gt_labels (num_targets): labels of targets.
+ priors (num_priors, 4): corner form priors
+ Returns:
+ boxes (num_priors, 4): real values for priors.
+ labels (num_priros): labels for priors.
+ """
+ # size: num_priors x num_targets
+ ious = iou_of(gt_boxes.unsqueeze(0), corner_form_priors.unsqueeze(1))
+ # size: num_priors
+ best_target_per_prior, best_target_per_prior_index = ious.max(1)
+ # size: num_targets
+ best_prior_per_target, best_prior_per_target_index = ious.max(0)
+
+ for target_index, prior_index in enumerate(best_prior_per_target_index):
+ best_target_per_prior_index[prior_index] = target_index
+ # 2.0 is used to make sure every target has a prior assigned
+ best_target_per_prior.index_fill_(0, best_prior_per_target_index, 2)
+ # size: num_priors
+ labels = gt_labels[best_target_per_prior_index]
+ labels[best_target_per_prior < iou_threshold] = 0 # the backgournd id
+ boxes = gt_boxes[best_target_per_prior_index]
+ return boxes, labels
+
+
+def hard_negative_mining(loss, labels, neg_pos_ratio):
+ """
+ It used to suppress the presence of a large number of negative prediction.
+ It works on image level not batch level.
+ For any example/image, it keeps all the positive predictions and
+ cut the number of negative predictions to make sure the ratio
+ between the negative examples and positive examples is no more
+ the given ratio for an image.
+
+ Args:
+ loss (N, num_priors): the loss for each example.
+ labels (N, num_priors): the labels.
+ neg_pos_ratio: the ratio between the negative examples and positive examples.
+ """
+ pos_mask = labels > 0
+ num_pos = pos_mask.long().sum(dim=1, keepdim=True)
+ num_neg = num_pos * neg_pos_ratio
+
+ loss[pos_mask] = -math.inf
+ _, indexes = loss.sort(dim=1, descending=True)
+ _, orders = indexes.sort(dim=1)
+ neg_mask = orders < num_neg
+ return pos_mask | neg_mask
+
+
+def center_form_to_corner_form(locations):
+ return torch.cat([locations[..., :2] - locations[..., 2:] / 2,
+ locations[..., :2] + locations[..., 2:] / 2], locations.dim() - 1)
+
+
+def corner_form_to_center_form(boxes):
+ return torch.cat([
+ (boxes[..., :2] + boxes[..., 2:]) / 2,
+ boxes[..., 2:] - boxes[..., :2]
+ ], boxes.dim() - 1)
+
+
+def hard_nms(box_scores, iou_threshold, top_k=-1, candidate_size=200):
+ """
+
+ Args:
+ box_scores (N, 5): boxes in corner-form and probabilities.
+ iou_threshold: intersection over union threshold.
+ top_k: keep top_k results. If k <= 0, keep all the results.
+ candidate_size: only consider the candidates with the highest scores.
+ Returns:
+ picked: a list of indexes of the kept boxes
+ """
+ scores = box_scores[:, -1]
+ boxes = box_scores[:, :-1]
+ picked = []
+ _, indexes = scores.sort(descending=True)
+ indexes = indexes[:candidate_size]
+ while len(indexes) > 0:
+ current = indexes[0]
+ picked.append(current.item())
+ if 0 < top_k == len(picked) or len(indexes) == 1:
+ break
+ current_box = boxes[current, :]
+ indexes = indexes[1:]
+ rest_boxes = boxes[indexes, :]
+ iou = iou_of(
+ rest_boxes,
+ current_box.unsqueeze(0),
+ )
+ indexes = indexes[iou <= iou_threshold]
+
+ return box_scores[picked, :]
+
+
+def nms(box_scores, nms_method=None, score_threshold=None, iou_threshold=None,
+ sigma=0.5, top_k=-1, candidate_size=200):
+ if nms_method == "soft":
+ return soft_nms(box_scores, score_threshold, sigma, top_k)
+ else:
+ return hard_nms(box_scores, iou_threshold, top_k, candidate_size=candidate_size)
+
+
+def soft_nms(box_scores, score_threshold, sigma=0.5, top_k=-1):
+ """Soft NMS implementation.
+
+ References:
+ https://arxiv.org/abs/1704.04503
+ https://github.com/facebookresearch/Detectron/blob/master/detectron/utils/cython_nms.pyx
+
+ Args:
+ box_scores (N, 5): boxes in corner-form and probabilities.
+ score_threshold: boxes with scores less than value are not considered.
+ sigma: the parameter in score re-computation.
+ scores[i] = scores[i] * exp(-(iou_i)^2 / simga)
+ top_k: keep top_k results. If k <= 0, keep all the results.
+ Returns:
+ picked_box_scores (K, 5): results of NMS.
+ """
+ picked_box_scores = []
+ while box_scores.size(0) > 0:
+ max_score_index = torch.argmax(box_scores[:, 4])
+ cur_box_prob = torch.tensor(box_scores[max_score_index, :])
+ picked_box_scores.append(cur_box_prob)
+ if len(picked_box_scores) == top_k > 0 or box_scores.size(0) == 1:
+ break
+ cur_box = cur_box_prob[:-1]
+ box_scores[max_score_index, :] = box_scores[-1, :]
+ box_scores = box_scores[:-1, :]
+ ious = iou_of(cur_box.unsqueeze(0), box_scores[:, :-1])
+ box_scores[:, -1] = box_scores[:, -1] * torch.exp(-(ious * ious) / sigma)
+ box_scores = box_scores[box_scores[:, -1] > score_threshold, :]
+ if len(picked_box_scores) > 0:
+ return torch.stack(picked_box_scores)
+ else:
+ return torch.tensor([])
diff --git a/face_detect/vision/utils/box_utils_numpy.py b/face_detect/vision/utils/box_utils_numpy.py
new file mode 100644
index 0000000..a6a6c4e
--- /dev/null
+++ b/face_detect/vision/utils/box_utils_numpy.py
@@ -0,0 +1,119 @@
+import numpy as np
+
+
+def convert_locations_to_boxes(locations, priors, center_variance,
+ size_variance):
+ """Convert regressional location results of SSD into boxes in the form of (center_x, center_y, h, w).
+
+ The conversion:
+ $$predicted\_center * center_variance = \frac {real\_center - prior\_center} {prior\_hw}$$
+ $$exp(predicted\_hw * size_variance) = \frac {real\_hw} {prior\_hw}$$
+ We do it in the inverse direction here.
+ Args:
+ locations (batch_size, num_priors, 4): the regression output of SSD. It will contain the outputs as well.
+ priors (num_priors, 4) or (batch_size/1, num_priors, 4): prior boxes.
+ center_variance: a float used to change the scale of center.
+ size_variance: a float used to change of scale of size.
+ Returns:
+ boxes: priors: [[center_x, center_y, h, w]]. All the values
+ are relative to the image size.
+ """
+ # priors can have one dimension less.
+ if len(priors.shape) + 1 == len(locations.shape):
+ priors = np.expand_dims(priors, 0)
+ return np.concatenate([
+ locations[..., :2] * center_variance * priors[..., 2:] + priors[..., :2],
+ np.exp(locations[..., 2:] * size_variance) * priors[..., 2:]
+ ], axis=len(locations.shape) - 1)
+
+
+def convert_boxes_to_locations(center_form_boxes, center_form_priors, center_variance, size_variance):
+ # priors can have one dimension less
+ if len(center_form_priors.shape) + 1 == len(center_form_boxes.shape):
+ center_form_priors = np.expand_dims(center_form_priors, 0)
+ return np.concatenate([
+ (center_form_boxes[..., :2] - center_form_priors[..., :2]) / center_form_priors[..., 2:] / center_variance,
+ np.log(center_form_boxes[..., 2:] / center_form_priors[..., 2:]) / size_variance
+ ], axis=len(center_form_boxes.shape) - 1)
+
+
+def area_of(left_top, right_bottom):
+ """Compute the areas of rectangles given two corners.
+
+ Args:
+ left_top (N, 2): left top corner.
+ right_bottom (N, 2): right bottom corner.
+
+ Returns:
+ area (N): return the area.
+ """
+ hw = np.clip(right_bottom - left_top, 0.0, None)
+ return hw[..., 0] * hw[..., 1]
+
+
+def iou_of(boxes0, boxes1, eps=1e-5):
+ """Return intersection-over-union (Jaccard index) of boxes.
+
+ Args:
+ boxes0 (N, 4): ground truth boxes.
+ boxes1 (N or 1, 4): predicted boxes.
+ eps: a small number to avoid 0 as denominator.
+ Returns:
+ iou (N): IoU values.
+ """
+ overlap_left_top = np.maximum(boxes0[..., :2], boxes1[..., :2])
+ overlap_right_bottom = np.minimum(boxes0[..., 2:], boxes1[..., 2:])
+
+ overlap_area = area_of(overlap_left_top, overlap_right_bottom)
+ area0 = area_of(boxes0[..., :2], boxes0[..., 2:])
+ area1 = area_of(boxes1[..., :2], boxes1[..., 2:])
+ return overlap_area / (area0 + area1 - overlap_area + eps)
+
+
+def center_form_to_corner_form(locations):
+ return np.concatenate([locations[..., :2] - locations[..., 2:] / 2,
+ locations[..., :2] + locations[..., 2:] / 2], len(locations.shape) - 1)
+
+
+def corner_form_to_center_form(boxes):
+ return np.concatenate([
+ (boxes[..., :2] + boxes[..., 2:]) / 2,
+ boxes[..., 2:] - boxes[..., :2]
+ ], len(boxes.shape) - 1)
+
+
+def hard_nms(box_scores, iou_threshold, top_k=-1, candidate_size=200):
+ """
+
+ Args:
+ box_scores (N, 5): boxes in corner-form and probabilities.
+ iou_threshold: intersection over union threshold.
+ top_k: keep top_k results. If k <= 0, keep all the results.
+ candidate_size: only consider the candidates with the highest scores.
+ Returns:
+ picked: a list of indexes of the kept boxes
+ """
+ scores = box_scores[:, -1]
+ boxes = box_scores[:, :-1]
+ picked = []
+ # _, indexes = scores.sort(descending=True)
+ indexes = np.argsort(scores)
+ # indexes = indexes[:candidate_size]
+ indexes = indexes[-candidate_size:]
+ while len(indexes) > 0:
+ # current = indexes[0]
+ current = indexes[-1]
+ picked.append(current)
+ if 0 < top_k == len(picked) or len(indexes) == 1:
+ break
+ current_box = boxes[current, :]
+ # indexes = indexes[1:]
+ indexes = indexes[:-1]
+ rest_boxes = boxes[indexes, :]
+ iou = iou_of(
+ rest_boxes,
+ np.expand_dims(current_box, axis=0),
+ )
+ indexes = indexes[iou <= iou_threshold]
+
+ return box_scores[picked, :]
diff --git a/face_detect/vision/utils/misc.py b/face_detect/vision/utils/misc.py
new file mode 100644
index 0000000..ea45dff
--- /dev/null
+++ b/face_detect/vision/utils/misc.py
@@ -0,0 +1,46 @@
+import datetime
+
+import torch
+
+
+def str2bool(s):
+ return s.lower() in ('true', '1')
+
+
+class Timer:
+ def __init__(self):
+ self.clock = {}
+
+ def start(self, key="default"):
+ self.clock[key] = datetime.datetime.now()
+
+ def end(self, key="default"):
+ if key not in self.clock:
+ raise Exception(f"{key} is not in the clock.")
+ interval = datetime.datetime.now() - self.clock[key]
+ del self.clock[key]
+ return interval.total_seconds()
+
+
+def save_checkpoint(epoch, net_state_dict, optimizer_state_dict, best_score, checkpoint_path, model_path):
+ torch.save({
+ 'epoch': epoch,
+ 'model': net_state_dict,
+ 'optimizer': optimizer_state_dict,
+ 'best_score': best_score
+ }, checkpoint_path)
+ torch.save(net_state_dict, model_path)
+
+
+def load_checkpoint(checkpoint_path):
+ return torch.load(checkpoint_path)
+
+
+def freeze_net_layers(net):
+ for param in net.parameters():
+ param.requires_grad = False
+
+
+def store_labels(path, labels):
+ with open(path, "w") as f:
+ f.write("\n".join(labels))
diff --git a/face_feature/GetFeature.py b/face_feature/GetFeature.py
new file mode 100644
index 0000000..55a5afb
--- /dev/null
+++ b/face_feature/GetFeature.py
@@ -0,0 +1,24 @@
+
+import cv2
+import numpy as np
+import torch
+from face_feature.irn50_pytorch import irn50_pytorch
+from face_util.faceutil import align_vertical
+
+import ctypes
+
+model_feature = irn50_pytorch("./face_feature/irn50_pytorch.npy")
+model_feature.eval()
+feature_align_image = np.zeros([128, 128, 3], dtype=np.uint8)
+
+def get_face_feature(image, landmark):
+ landmark_vec = (ctypes.c_float * len(landmark))(*landmark)
+ align_vertical(image, image.shape[1], image.shape[0], feature_align_image, 128, 128, 3, landmark_vec, 48, 64, 40)
+ # cv2.imwrite("D:/align.png", feature_align_image)
+ feature_align_image_proc = feature_align_image / 256
+ feature_align_image_proc = torch.from_numpy(feature_align_image_proc.astype(np.float32))
+ feature_align_image_proc = feature_align_image_proc.permute(2, 0, 1)
+ feature_align_image_proc = feature_align_image_proc.unsqueeze(0)
+ feature_out = model_feature(feature_align_image_proc)
+ feature_out = torch.nn.functional.normalize(feature_out)[0, :]
+ return feature_align_image, feature_out.data.numpy()
diff --git a/face_feature/irn50_pytorch.py b/face_feature/irn50_pytorch.py
new file mode 100644
index 0000000..78b43b2
--- /dev/null
+++ b/face_feature/irn50_pytorch.py
@@ -0,0 +1,288 @@
+import numpy as np
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import math
+
+_weights_dict = dict()
+
+def load_weights(weight_file):
+ if weight_file == None:
+ return
+
+ try:
+ weights_dict = np.load(weight_file, allow_pickle=True).item()
+ except:
+ weights_dict = np.load(weight_file, allow_pickle=True, encoding='bytes').item()
+
+ return weights_dict
+
+class irn50_pytorch(nn.Module):
+ def __init__(self, weight_file):
+ super(irn50_pytorch, self).__init__()
+ global _weights_dict
+ _weights_dict = load_weights(weight_file)
+
+ self.Convolution1 = self.__conv(2, name='Convolution1', in_channels=3, out_channels=32, kernel_size=(3, 3), stride=(2, 2), groups=1, bias=False)
+ self.BatchNorm1 = self.__batch_normalization(2, 'BatchNorm1', num_features=32, eps=9.999999747378752e-06, momentum=0.0)
+ self.Convolution2 = self.__conv(2, name='Convolution2', in_channels=32, out_channels=32, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=False)
+ self.BatchNorm2 = self.__batch_normalization(2, 'BatchNorm2', num_features=32, eps=9.999999747378752e-06, momentum=0.0)
+ self.Convolution3 = self.__conv(2, name='Convolution3', in_channels=32, out_channels=64, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=False)
+ self.BatchNorm3 = self.__batch_normalization(2, 'BatchNorm3', num_features=64, eps=9.999999747378752e-06, momentum=0.0)
+ self.Convolution4 = self.__conv(2, name='Convolution4', in_channels=64, out_channels=80, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
+ self.BatchNorm4 = self.__batch_normalization(2, 'BatchNorm4', num_features=80, eps=9.999999747378752e-06, momentum=0.0)
+ self.Convolution5 = self.__conv(2, name='Convolution5', in_channels=80, out_channels=192, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=False)
+ self.BatchNorm5 = self.__batch_normalization(2, 'BatchNorm5', num_features=192, eps=9.999999747378752e-06, momentum=0.0)
+ self.Convolution6 = self.__conv(2, name='Convolution6', in_channels=192, out_channels=256, kernel_size=(3, 3), stride=(2, 2), groups=1, bias=False)
+ self.BatchNorm6 = self.__batch_normalization(2, 'BatchNorm6', num_features=256, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv2_res1_proj = self.__conv(2, name='conv2_res1_proj', in_channels=256, out_channels=256, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
+ self.conv2_res1_conv1 = self.__conv(2, name='conv2_res1_conv1', in_channels=256, out_channels=64, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
+ self.conv2_res1_conv1_bn = self.__batch_normalization(2, 'conv2_res1_conv1_bn', num_features=64, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv2_res1_conv2 = self.__conv(2, name='conv2_res1_conv2', in_channels=64, out_channels=64, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=False)
+ self.conv2_res1_conv2_bn = self.__batch_normalization(2, 'conv2_res1_conv2_bn', num_features=64, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv2_res1_conv3 = self.__conv(2, name='conv2_res1_conv3', in_channels=64, out_channels=256, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
+ self.conv2_res2_pre_bn = self.__batch_normalization(2, 'conv2_res2_pre_bn', num_features=256, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv2_res2_conv1 = self.__conv(2, name='conv2_res2_conv1', in_channels=256, out_channels=64, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
+ self.conv2_res2_conv1_bn = self.__batch_normalization(2, 'conv2_res2_conv1_bn', num_features=64, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv2_res2_conv2 = self.__conv(2, name='conv2_res2_conv2', in_channels=64, out_channels=64, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=False)
+ self.conv2_res2_conv2_bn = self.__batch_normalization(2, 'conv2_res2_conv2_bn', num_features=64, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv2_res2_conv3 = self.__conv(2, name='conv2_res2_conv3', in_channels=64, out_channels=256, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
+ self.conv2_res3_pre_bn = self.__batch_normalization(2, 'conv2_res3_pre_bn', num_features=256, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv2_res3_conv1 = self.__conv(2, name='conv2_res3_conv1', in_channels=256, out_channels=64, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
+ self.conv2_res3_conv1_bn = self.__batch_normalization(2, 'conv2_res3_conv1_bn', num_features=64, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv2_res3_conv2 = self.__conv(2, name='conv2_res3_conv2', in_channels=64, out_channels=64, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=False)
+ self.conv2_res3_conv2_bn = self.__batch_normalization(2, 'conv2_res3_conv2_bn', num_features=64, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv2_res3_conv3 = self.__conv(2, name='conv2_res3_conv3', in_channels=64, out_channels=256, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
+ self.conv3_res1_pre_bn = self.__batch_normalization(2, 'conv3_res1_pre_bn', num_features=256, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv3_res1_proj = self.__conv(2, name='conv3_res1_proj', in_channels=256, out_channels=512, kernel_size=(1, 1), stride=(2, 2), groups=1, bias=False)
+ self.conv3_res1_conv1 = self.__conv(2, name='conv3_res1_conv1', in_channels=256, out_channels=128, kernel_size=(1, 1), stride=(2, 2), groups=1, bias=False)
+ self.conv3_res1_conv1_bn = self.__batch_normalization(2, 'conv3_res1_conv1_bn', num_features=128, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv3_res1_conv2 = self.__conv(2, name='conv3_res1_conv2', in_channels=128, out_channels=128, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=False)
+ self.conv3_res1_conv2_bn = self.__batch_normalization(2, 'conv3_res1_conv2_bn', num_features=128, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv3_res1_conv3 = self.__conv(2, name='conv3_res1_conv3', in_channels=128, out_channels=512, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
+ self.conv3_res2_pre_bn = self.__batch_normalization(2, 'conv3_res2_pre_bn', num_features=512, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv3_res2_conv1 = self.__conv(2, name='conv3_res2_conv1', in_channels=512, out_channels=128, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
+ self.conv3_res2_conv1_bn = self.__batch_normalization(2, 'conv3_res2_conv1_bn', num_features=128, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv3_res2_conv2 = self.__conv(2, name='conv3_res2_conv2', in_channels=128, out_channels=128, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=False)
+ self.conv3_res2_conv2_bn = self.__batch_normalization(2, 'conv3_res2_conv2_bn', num_features=128, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv3_res2_conv3 = self.__conv(2, name='conv3_res2_conv3', in_channels=128, out_channels=512, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
+ self.conv3_res3_pre_bn = self.__batch_normalization(2, 'conv3_res3_pre_bn', num_features=512, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv3_res3_conv1 = self.__conv(2, name='conv3_res3_conv1', in_channels=512, out_channels=128, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
+ self.conv3_res3_conv1_bn = self.__batch_normalization(2, 'conv3_res3_conv1_bn', num_features=128, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv3_res3_conv2 = self.__conv(2, name='conv3_res3_conv2', in_channels=128, out_channels=128, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=False)
+ self.conv3_res3_conv2_bn = self.__batch_normalization(2, 'conv3_res3_conv2_bn', num_features=128, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv3_res3_conv3 = self.__conv(2, name='conv3_res3_conv3', in_channels=128, out_channels=512, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
+ self.conv3_res4_pre_bn = self.__batch_normalization(2, 'conv3_res4_pre_bn', num_features=512, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv3_res4_conv1 = self.__conv(2, name='conv3_res4_conv1', in_channels=512, out_channels=128, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
+ self.conv3_res4_conv1_bn = self.__batch_normalization(2, 'conv3_res4_conv1_bn', num_features=128, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv3_res4_conv2 = self.__conv(2, name='conv3_res4_conv2', in_channels=128, out_channels=128, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=False)
+ self.conv3_res4_conv2_bn = self.__batch_normalization(2, 'conv3_res4_conv2_bn', num_features=128, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv3_res4_conv3 = self.__conv(2, name='conv3_res4_conv3', in_channels=128, out_channels=512, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
+ self.conv4_res1_pre_bn = self.__batch_normalization(2, 'conv4_res1_pre_bn', num_features=512, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv4_res1_proj = self.__conv(2, name='conv4_res1_proj', in_channels=512, out_channels=512, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
+ self.conv4_res1_conv1 = self.__conv(2, name='conv4_res1_conv1', in_channels=512, out_channels=128, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=False)
+ self.conv4_res1_conv1_bn = self.__batch_normalization(2, 'conv4_res1_conv1_bn', num_features=128, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv4_res1_conv2 = self.__conv(2, name='conv4_res1_conv2', in_channels=128, out_channels=512, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
+ self.conv4_res2_pre_bn = self.__batch_normalization(2, 'conv4_res2_pre_bn', num_features=512, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv4_res2_conv1_proj = self.__conv(2, name='conv4_res2_conv1_proj', in_channels=512, out_channels=1024, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
+ self.conv4_res2_conv1 = self.__conv(2, name='conv4_res2_conv1', in_channels=512, out_channels=256, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
+ self.conv4_res2_conv1_bn = self.__batch_normalization(2, 'conv4_res2_conv1_bn', num_features=256, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv4_res2_conv2 = self.__conv(2, name='conv4_res2_conv2', in_channels=256, out_channels=256, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=False)
+ self.conv4_res2_conv2_bn = self.__batch_normalization(2, 'conv4_res2_conv2_bn', num_features=256, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv4_res2_conv3 = self.__conv(2, name='conv4_res2_conv3', in_channels=256, out_channels=1024, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
+ self.conv4_res3_pre_bn = self.__batch_normalization(2, 'conv4_res3_pre_bn', num_features=1024, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv4_res3_conv1 = self.__conv(2, name='conv4_res3_conv1', in_channels=1024, out_channels=256, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
+ self.conv4_res3_conv1_bn = self.__batch_normalization(2, 'conv4_res3_conv1_bn', num_features=256, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv4_res3_conv2 = self.__conv(2, name='conv4_res3_conv2', in_channels=256, out_channels=256, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=False)
+ self.conv4_res3_conv2_bn = self.__batch_normalization(2, 'conv4_res3_conv2_bn', num_features=256, eps=9.999999747378752e-06, momentum=0.0)
+ self.conv4_res3_conv3 = self.__conv(2, name='conv4_res3_conv3', in_channels=256, out_channels=1024, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
+ self.conv5_bn = self.__batch_normalization(2, 'conv5_bn', num_features=1024, eps=9.999999747378752e-06, momentum=0.0)
+ self.fc1_1 = self.__dense(name = 'fc1_1', in_features = 16384, out_features = 512, bias = False)
+ self.bn_fc1 = self.__batch_normalization(1, 'bn_fc1', num_features=512, eps=9.999999747378752e-06, momentum=0.0)
+
+ def forward(self, x):
+ Convolution1 = self.Convolution1(x)
+ BatchNorm1 = self.BatchNorm1(Convolution1)
+ ReLU1 = F.relu(BatchNorm1)
+ Convolution2 = self.Convolution2(ReLU1)
+ BatchNorm2 = self.BatchNorm2(Convolution2)
+ ReLU2 = F.relu(BatchNorm2)
+ Convolution3_pad = F.pad(ReLU2, (1, 1, 1, 1))
+ Convolution3 = self.Convolution3(Convolution3_pad)
+ BatchNorm3 = self.BatchNorm3(Convolution3)
+ ReLU3 = F.relu(BatchNorm3)
+ Pooling1_pad = F.pad(ReLU3, (0, 1, 0, 1), value=float('-inf'))
+ Pooling1, Pooling1_idx = F.max_pool2d(Pooling1_pad, kernel_size=(3, 3), stride=(2, 2), padding=0, ceil_mode=False, return_indices=True)
+ Convolution4 = self.Convolution4(Pooling1)
+ BatchNorm4 = self.BatchNorm4(Convolution4)
+ ReLU4 = F.relu(BatchNorm4)
+ Convolution5 = self.Convolution5(ReLU4)
+ BatchNorm5 = self.BatchNorm5(Convolution5)
+ ReLU5 = F.relu(BatchNorm5)
+ Convolution6_pad = F.pad(ReLU5, (1, 1, 1, 1))
+ Convolution6 = self.Convolution6(Convolution6_pad)
+ BatchNorm6 = self.BatchNorm6(Convolution6)
+ ReLU6 = F.relu(BatchNorm6)
+ conv2_res1_proj = self.conv2_res1_proj(ReLU6)
+ conv2_res1_conv1 = self.conv2_res1_conv1(ReLU6)
+ conv2_res1_conv1_bn = self.conv2_res1_conv1_bn(conv2_res1_conv1)
+ conv2_res1_conv1_relu = F.relu(conv2_res1_conv1_bn)
+ conv2_res1_conv2_pad = F.pad(conv2_res1_conv1_relu, (1, 1, 1, 1))
+ conv2_res1_conv2 = self.conv2_res1_conv2(conv2_res1_conv2_pad)
+ conv2_res1_conv2_bn = self.conv2_res1_conv2_bn(conv2_res1_conv2)
+ conv2_res1_conv2_relu = F.relu(conv2_res1_conv2_bn)
+ conv2_res1_conv3 = self.conv2_res1_conv3(conv2_res1_conv2_relu)
+ conv2_res1 = conv2_res1_proj + conv2_res1_conv3
+ conv2_res2_pre_bn = self.conv2_res2_pre_bn(conv2_res1)
+ conv2_res2_pre_relu = F.relu(conv2_res2_pre_bn)
+ conv2_res2_conv1 = self.conv2_res2_conv1(conv2_res2_pre_relu)
+ conv2_res2_conv1_bn = self.conv2_res2_conv1_bn(conv2_res2_conv1)
+ conv2_res2_conv1_relu = F.relu(conv2_res2_conv1_bn)
+ conv2_res2_conv2_pad = F.pad(conv2_res2_conv1_relu, (1, 1, 1, 1))
+ conv2_res2_conv2 = self.conv2_res2_conv2(conv2_res2_conv2_pad)
+ conv2_res2_conv2_bn = self.conv2_res2_conv2_bn(conv2_res2_conv2)
+ conv2_res2_conv2_relu = F.relu(conv2_res2_conv2_bn)
+ conv2_res2_conv3 = self.conv2_res2_conv3(conv2_res2_conv2_relu)
+ conv2_res2 = conv2_res1 + conv2_res2_conv3
+ conv2_res3_pre_bn = self.conv2_res3_pre_bn(conv2_res2)
+ conv2_res3_pre_relu = F.relu(conv2_res3_pre_bn)
+ conv2_res3_conv1 = self.conv2_res3_conv1(conv2_res3_pre_relu)
+ conv2_res3_conv1_bn = self.conv2_res3_conv1_bn(conv2_res3_conv1)
+ conv2_res3_conv1_relu = F.relu(conv2_res3_conv1_bn)
+ conv2_res3_conv2_pad = F.pad(conv2_res3_conv1_relu, (1, 1, 1, 1))
+ conv2_res3_conv2 = self.conv2_res3_conv2(conv2_res3_conv2_pad)
+ conv2_res3_conv2_bn = self.conv2_res3_conv2_bn(conv2_res3_conv2)
+ conv2_res3_conv2_relu = F.relu(conv2_res3_conv2_bn)
+ conv2_res3_conv3 = self.conv2_res3_conv3(conv2_res3_conv2_relu)
+ conv2_res3 = conv2_res2 + conv2_res3_conv3
+ conv3_res1_pre_bn = self.conv3_res1_pre_bn(conv2_res3)
+ conv3_res1_pre_relu = F.relu(conv3_res1_pre_bn)
+ conv3_res1_proj = self.conv3_res1_proj(conv3_res1_pre_relu)
+ conv3_res1_conv1 = self.conv3_res1_conv1(conv3_res1_pre_relu)
+ conv3_res1_conv1_bn = self.conv3_res1_conv1_bn(conv3_res1_conv1)
+ conv3_res1_conv1_relu = F.relu(conv3_res1_conv1_bn)
+ conv3_res1_conv2_pad = F.pad(conv3_res1_conv1_relu, (1, 1, 1, 1))
+ conv3_res1_conv2 = self.conv3_res1_conv2(conv3_res1_conv2_pad)
+ conv3_res1_conv2_bn = self.conv3_res1_conv2_bn(conv3_res1_conv2)
+ conv3_res1_conv2_relu = F.relu(conv3_res1_conv2_bn)
+ conv3_res1_conv3 = self.conv3_res1_conv3(conv3_res1_conv2_relu)
+ conv3_res1 = conv3_res1_proj + conv3_res1_conv3
+ conv3_res2_pre_bn = self.conv3_res2_pre_bn(conv3_res1)
+ conv3_res2_pre_relu = F.relu(conv3_res2_pre_bn)
+ conv3_res2_conv1 = self.conv3_res2_conv1(conv3_res2_pre_relu)
+ conv3_res2_conv1_bn = self.conv3_res2_conv1_bn(conv3_res2_conv1)
+ conv3_res2_conv1_relu = F.relu(conv3_res2_conv1_bn)
+ conv3_res2_conv2_pad = F.pad(conv3_res2_conv1_relu, (1, 1, 1, 1))
+ conv3_res2_conv2 = self.conv3_res2_conv2(conv3_res2_conv2_pad)
+ conv3_res2_conv2_bn = self.conv3_res2_conv2_bn(conv3_res2_conv2)
+ conv3_res2_conv2_relu = F.relu(conv3_res2_conv2_bn)
+ conv3_res2_conv3 = self.conv3_res2_conv3(conv3_res2_conv2_relu)
+ conv3_res2 = conv3_res1 + conv3_res2_conv3
+ conv3_res3_pre_bn = self.conv3_res3_pre_bn(conv3_res2)
+ conv3_res3_pre_relu = F.relu(conv3_res3_pre_bn)
+ conv3_res3_conv1 = self.conv3_res3_conv1(conv3_res3_pre_relu)
+ conv3_res3_conv1_bn = self.conv3_res3_conv1_bn(conv3_res3_conv1)
+ conv3_res3_conv1_relu = F.relu(conv3_res3_conv1_bn)
+ conv3_res3_conv2_pad = F.pad(conv3_res3_conv1_relu, (1, 1, 1, 1))
+ conv3_res3_conv2 = self.conv3_res3_conv2(conv3_res3_conv2_pad)
+ conv3_res3_conv2_bn = self.conv3_res3_conv2_bn(conv3_res3_conv2)
+ conv3_res3_conv2_relu = F.relu(conv3_res3_conv2_bn)
+ conv3_res3_conv3 = self.conv3_res3_conv3(conv3_res3_conv2_relu)
+ conv3_res3 = conv3_res2 + conv3_res3_conv3
+ conv3_res4_pre_bn = self.conv3_res4_pre_bn(conv3_res3)
+ conv3_res4_pre_relu = F.relu(conv3_res4_pre_bn)
+ conv3_res4_conv1 = self.conv3_res4_conv1(conv3_res4_pre_relu)
+ conv3_res4_conv1_bn = self.conv3_res4_conv1_bn(conv3_res4_conv1)
+ conv3_res4_conv1_relu = F.relu(conv3_res4_conv1_bn)
+ conv3_res4_conv2_pad = F.pad(conv3_res4_conv1_relu, (1, 1, 1, 1))
+ conv3_res4_conv2 = self.conv3_res4_conv2(conv3_res4_conv2_pad)
+ conv3_res4_conv2_bn = self.conv3_res4_conv2_bn(conv3_res4_conv2)
+ conv3_res4_conv2_relu = F.relu(conv3_res4_conv2_bn)
+ conv3_res4_conv3 = self.conv3_res4_conv3(conv3_res4_conv2_relu)
+ conv3_res4 = conv3_res3 + conv3_res4_conv3
+ conv4_res1_pre_bn = self.conv4_res1_pre_bn(conv3_res4)
+ conv4_res1_pre_relu = F.relu(conv4_res1_pre_bn)
+ conv4_res1_proj = self.conv4_res1_proj(conv4_res1_pre_relu)
+ conv4_res1_conv1_pad = F.pad(conv4_res1_pre_relu, (1, 1, 1, 1))
+ conv4_res1_conv1 = self.conv4_res1_conv1(conv4_res1_conv1_pad)
+ conv4_res1_conv1_bn = self.conv4_res1_conv1_bn(conv4_res1_conv1)
+ conv4_res1_conv1_relu = F.relu(conv4_res1_conv1_bn)
+ conv4_res1_conv2 = self.conv4_res1_conv2(conv4_res1_conv1_relu)
+ conv4_res1 = conv4_res1_proj + conv4_res1_conv2
+ conv4_res2_pre_bn = self.conv4_res2_pre_bn(conv4_res1)
+ conv4_res2_pre_relu = F.relu(conv4_res2_pre_bn)
+ conv4_res2_conv1_proj = self.conv4_res2_conv1_proj(conv4_res2_pre_relu)
+ conv4_res2_conv1 = self.conv4_res2_conv1(conv4_res2_pre_relu)
+ conv4_res2_conv1_bn = self.conv4_res2_conv1_bn(conv4_res2_conv1)
+ conv4_res2_conv1_relu = F.relu(conv4_res2_conv1_bn)
+ conv4_res2_conv2_pad = F.pad(conv4_res2_conv1_relu, (1, 1, 1, 1))
+ conv4_res2_conv2 = self.conv4_res2_conv2(conv4_res2_conv2_pad)
+ conv4_res2_conv2_bn = self.conv4_res2_conv2_bn(conv4_res2_conv2)
+ conv4_res2_conv2_relu = F.relu(conv4_res2_conv2_bn)
+ conv4_res2_conv3 = self.conv4_res2_conv3(conv4_res2_conv2_relu)
+ conv4_res2 = conv4_res2_conv1_proj + conv4_res2_conv3
+ conv4_res3_pre_bn = self.conv4_res3_pre_bn(conv4_res2)
+ conv4_res3_pre_relu = F.relu(conv4_res3_pre_bn)
+ conv4_res3_conv1 = self.conv4_res3_conv1(conv4_res3_pre_relu)
+ conv4_res3_conv1_bn = self.conv4_res3_conv1_bn(conv4_res3_conv1)
+ conv4_res3_conv1_relu = F.relu(conv4_res3_conv1_bn)
+ conv4_res3_conv2_pad = F.pad(conv4_res3_conv1_relu, (1, 1, 1, 1))
+ conv4_res3_conv2 = self.conv4_res3_conv2(conv4_res3_conv2_pad)
+ conv4_res3_conv2_bn = self.conv4_res3_conv2_bn(conv4_res3_conv2)
+ conv4_res3_conv2_relu = F.relu(conv4_res3_conv2_bn)
+ conv4_res3_conv3 = self.conv4_res3_conv3(conv4_res3_conv2_relu)
+ conv4_res3 = conv4_res2 + conv4_res3_conv3
+ conv5_bn = self.conv5_bn(conv4_res3)
+ conv5_relu = F.relu(conv5_bn)
+ pool5 = F.avg_pool2d(conv5_relu, kernel_size=(4, 4), stride=(1, 1), padding=(0,), ceil_mode=False, count_include_pad=False)
+ fc1_0 = pool5.view(pool5.size(0), -1)
+ fc1_1 = self.fc1_1(fc1_0)
+ bn_fc1 = self.bn_fc1(fc1_1)
+ #return bn_fc1
+ bn_fc1 = bn_fc1.reshape(bn_fc1.size()[0], bn_fc1.size()[1])
+ slice_fc1, slice_fc2 = bn_fc1[:, :256], bn_fc1[:, 256:]
+ eltwise_fc1 = torch.max(slice_fc1, slice_fc2)
+
+ return eltwise_fc1
+
+ @staticmethod
+ def __conv(dim, name, **kwargs):
+ if dim == 1: layer = nn.Conv1d(**kwargs)
+ elif dim == 2: layer = nn.Conv2d(**kwargs)
+ elif dim == 3: layer = nn.Conv3d(**kwargs)
+ else: raise NotImplementedError()
+
+ layer.state_dict()['weight'].copy_(torch.from_numpy(_weights_dict[name]['weights']))
+ if 'bias' in _weights_dict[name]:
+ layer.state_dict()['bias'].copy_(torch.from_numpy(_weights_dict[name]['bias']))
+ return layer
+
+ @staticmethod
+ def __batch_normalization(dim, name, **kwargs):
+ if dim == 0 or dim == 1: layer = nn.BatchNorm1d(**kwargs)
+ elif dim == 2: layer = nn.BatchNorm2d(**kwargs)
+ elif dim == 3: layer = nn.BatchNorm3d(**kwargs)
+ else: raise NotImplementedError()
+
+ if 'scale' in _weights_dict[name]:
+ layer.state_dict()['weight'].copy_(torch.from_numpy(_weights_dict[name]['scale']))
+ else:
+ layer.weight.data.fill_(1)
+
+ if 'bias' in _weights_dict[name]:
+ layer.state_dict()['bias'].copy_(torch.from_numpy(_weights_dict[name]['bias']))
+ else:
+ layer.bias.data.fill_(0)
+
+ layer.state_dict()['running_mean'].copy_(torch.from_numpy(_weights_dict[name]['mean']))
+ layer.state_dict()['running_var'].copy_(torch.from_numpy(_weights_dict[name]['var']))
+ return layer
+
+ @staticmethod
+ def __dense(name, **kwargs):
+ layer = nn.Linear(**kwargs)
+ layer.state_dict()['weight'].copy_(torch.from_numpy(_weights_dict[name]['weights']))
+ if 'bias' in _weights_dict[name]:
+ layer.state_dict()['bias'].copy_(torch.from_numpy(_weights_dict[name]['bias']))
+ return layer
+
diff --git a/face_landmark/MobileFaceNet.py b/face_landmark/MobileFaceNet.py
new file mode 100644
index 0000000..76ddee2
--- /dev/null
+++ b/face_landmark/MobileFaceNet.py
@@ -0,0 +1,123 @@
+from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, ReLU, Sigmoid, Dropout2d, Dropout, AvgPool2d, MaxPool2d, AdaptiveAvgPool2d, Sequential, Module, Parameter
+import torch.nn.functional as F
+import torch
+import torch.nn as nn
+from collections import namedtuple
+import math
+import pdb
+
+################################## Original Arcface Model #############################################################
+
+class Flatten(Module):
+ def forward(self, input):
+ return input.view(input.size(0), -1)
+
+################################## MobileFaceNet #############################################################
+
+class Conv_block(Module):
+ def __init__(self, in_c, out_c, kernel=(1, 1), stride=(1, 1), padding=(0, 0), groups=1):
+ super(Conv_block, self).__init__()
+ self.conv = Conv2d(in_c, out_channels=out_c, kernel_size=kernel, groups=groups, stride=stride, padding=padding, bias=False)
+ self.bn = BatchNorm2d(out_c)
+ self.relu = ReLU(out_c)
+ def forward(self, x):
+ x = self.conv(x)
+ x = self.bn(x)
+ x = self.relu(x)
+ return x
+
+class Linear_block(Module):
+ def __init__(self, in_c, out_c, kernel=(1, 1), stride=(1, 1), padding=(0, 0), groups=1):
+ super(Linear_block, self).__init__()
+ self.conv = Conv2d(in_c, out_channels=out_c, kernel_size=kernel, groups=groups, stride=stride, padding=padding, bias=False)
+ self.bn = BatchNorm2d(out_c)
+ def forward(self, x):
+ x = self.conv(x)
+ x = self.bn(x)
+ return x
+
+class Depth_Wise(Module):
+ def __init__(self, in_c, out_c, residual = False, kernel=(3, 3), stride=(2, 2), padding=(1, 1), groups=1):
+ super(Depth_Wise, self).__init__()
+ self.conv = Conv_block(in_c, out_c=groups, kernel=(1, 1), padding=(0, 0), stride=(1, 1))
+ self.conv_dw = Conv_block(groups, groups, groups=groups, kernel=kernel, padding=padding, stride=stride)
+ self.project = Linear_block(groups, out_c, kernel=(1, 1), padding=(0, 0), stride=(1, 1))
+ self.residual = residual
+ def forward(self, x):
+ if self.residual:
+ short_cut = x
+ x = self.conv(x)
+ x = self.conv_dw(x)
+ x = self.project(x)
+ if self.residual:
+ output = short_cut + x
+ else:
+ output = x
+ return output
+
+class Residual(Module):
+ def __init__(self, c, num_block, groups, kernel=(3, 3), stride=(1, 1), padding=(1, 1)):
+ super(Residual, self).__init__()
+ modules = []
+ for _ in range(num_block):
+ modules.append(Depth_Wise(c, c, residual=True, kernel=kernel, padding=padding, stride=stride, groups=groups))
+ self.model = Sequential(*modules)
+ def forward(self, x):
+ return self.model(x)
+
+class GDC(Module):
+ def __init__(self, embedding_size):
+ super(GDC, self).__init__()
+ self.conv_6_dw = Linear_block(512, 512, groups=512, kernel=(4,4), stride=(1, 1), padding=(0, 0))
+ self.linear = Linear(512, embedding_size, bias=True)
+ self.bn = BatchNorm1d(embedding_size)
+
+ def forward(self, x):
+ x = self.conv_6_dw(x)
+ x = torch.flatten(x, 1)
+ x = self.linear(x)
+ x = self.bn(x)
+ return x
+
+class MobileFaceNet(Module):
+ def __init__(self, input_size, embedding_size = 512):
+ super(MobileFaceNet, self).__init__()
+ self.conv1 = Conv_block(1, 32, kernel=(3, 3), stride=(2, 2), padding=(1, 1))
+ self.conv2_dw = Conv_block(32, 32, kernel=(3, 3), stride=(1, 1), padding=(1, 1), groups=32)
+ self.conv_23 = Depth_Wise(32, 32, kernel=(3, 3), stride=(2, 2), padding=(1, 1), groups=64)
+ self.conv_3 = Residual(32, num_block=3, groups=64, kernel=(3, 3), stride=(1, 1), padding=(1, 1))
+ self.conv_34 = Depth_Wise(32, 64, kernel=(3, 3), stride=(2, 2), padding=(1, 1), groups=128)
+ self.conv_4 = Residual(64, num_block=4, groups=128, kernel=(3, 3), stride=(1, 1), padding=(1, 1))
+ self.conv_45 = Depth_Wise(64, 64, kernel=(3, 3), stride=(2, 2), padding=(1, 1), groups=256)
+ self.conv_5 = Residual(64, num_block=2, groups=128, kernel=(3, 3), stride=(1, 1), padding=(1, 1))
+ self.conv_6_sep = Conv_block(64, 512, kernel=(1, 1), stride=(1, 1), padding=(0, 0))
+ self.output_layer = GDC(embedding_size)
+ self._initialize_weights()
+
+ def _initialize_weights(self):
+ for m in self.modules():
+ if isinstance(m, nn.Conv2d):
+ nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
+ if m.bias is not None:
+ m.bias.data.zero_()
+ elif isinstance(m, nn.BatchNorm2d):
+ m.weight.data.fill_(1)
+ m.bias.data.zero_()
+ elif isinstance(m, nn.Linear):
+ nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
+ if m.bias is not None:
+ m.bias.data.zero_()
+
+
+ def forward(self, x):
+ out = self.conv1(x)
+ out = self.conv2_dw(out)
+ out = self.conv_23(out)
+ out = self.conv_3(out)
+ out = self.conv_34(out)
+ out = self.conv_4(out)
+ out = self.conv_45(out)
+ out = self.conv_5(out)
+ conv_features = self.conv_6_sep(out)
+ out = self.output_layer(conv_features)
+ return out
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000..f8e67a9
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,6 @@
+numpy==1.26.4
+opencv-python==3.4.13.47
+pillow==10.4.0
+torch==2.4.1
+torchaudio==2.4.1
+torchvision==0.19.1
\ No newline at end of file
diff --git a/run.py b/run.py
new file mode 100644
index 0000000..bfd6ee0
--- /dev/null
+++ b/run.py
@@ -0,0 +1,73 @@
+
+import argparse
+import cv2
+import torch
+import numpy as np
+import ctypes
+import os.path
+import time
+
+from face_detect.detect_imgs import get_face_boundingbox
+from face_landmark.GetLandmark import get_face_landmark
+from face_feature.GetFeature import get_face_feature
+from face_pose.GetPose import get_face_pose
+
+def GetImageInfo(image, faceMaxCount):
+ gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
+ ### Detection
+ start_time = time.time() * 1000
+ boxes, scores = get_face_boundingbox(image)
+ boxes = boxes[:faceMaxCount]
+ scores = scores[:faceMaxCount]
+ count = len(boxes)
+ bboxes = []
+ bscores = []
+ for idx in range(count):
+ bboxes.append(boxes[idx].data.numpy())
+ bscores.append(scores[idx].data.numpy())
+
+ ### Landmark
+ start_time = time.time() * 1000
+ landmarks = [] ### np.zeros((count, 136), dtype=np.float32)
+ for idx in range(count):
+ landmarks.append(get_face_landmark(gray_image, boxes[idx]).data.numpy())
+
+ ### Pose
+ poses = []
+ for idx in range(count):
+ poses.append(get_face_pose(boxes[idx], landmarks[idx]))
+
+ ### Feature
+ start_time = time.time() * 1000
+ features = []
+ alignimgs = []
+ for idx in range(count):
+ alignimg, feature = get_face_feature(image, landmarks[idx])
+ features.append(feature)
+ alignimgs.append(alignimg)
+ # print("Feature extraction time = %s ms" % (time.time() * 1000 - start_time))
+
+ return count, bboxes, bscores, landmarks, alignimgs, features
+
+def get_similarity(feat1, feat2):
+ return (np.sum(feat1 * feat2) + 1) * 50
+
+if __name__ == '__main__':
+ threshold = 75
+ test_directory = 'test'
+
+ efn = os.getcwd() + "/test/1.jpg"
+ img = cv2.imread(efn, cv2.IMREAD_COLOR)
+ count, boxes, scores, landmarks, alignimgs, features1 = GetImageInfo(img, 5)
+
+ vfn = os.getcwd() + "/test/2.png"
+ img = cv2.imread(vfn, cv2.IMREAD_COLOR)
+ count, boxes, scores, landmarks, alignimgs, features2 = GetImageInfo(img, 5)
+
+ score = get_similarity(features1[0], features2[0])
+ print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
+ print('score = ', score)
+ if score > threshold:
+ print('same person')
+ else:
+ print('different person')
diff --git a/test/1.jpg b/test/1.jpg
new file mode 100644
index 0000000..6e30c18
Binary files /dev/null and b/test/1.jpg differ
diff --git a/test/2.png b/test/2.png
new file mode 100644
index 0000000..9a1e719
Binary files /dev/null and b/test/2.png differ