Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

add face detection API (#1469)

Edgar Ribaf1eaad9abd7f
diff --git a/docs/source/applications/face_detection.rst b/docs/source/applications/face_detection.rst
new file mode 100644
index 000000000..471625f90
--- /dev/null
+++ b/docs/source/applications/face_detection.rst
@@ -0,0 +1,24 @@
+Face Detection
+==============
+
+.. image:: https://github.com/ShiqiYu/libfacedetection/raw/master/images/cnnresult.png
+ :align: right
+ :width: 20%
+
+Face detection is the task of detecting faces in a photo or video (and distinguishing them from other objects).
+We provide the :py:class:`kornia.contrib.FaceDetector` to perform multi-face detection in real-time uding the
+`YuNet` model.
+
+Learn more: `https://paperswithcode.com/task/face-detection <https://paperswithcode.com/task/face-detection>`_
+
+.. youtube:: hzQroGp5FSQ
+
+Using our API you easily detect faces in images as shown below:
+
+.. literalinclude:: ../../../examples/face_detection/main.py
+ :language: python
+ :lines: 36-53
+
+Check the full examples `here <https://github.com/kornia/kornia/tree/master/examples/face_detection/main.py>`_
+
+For a real-time example using the camera check this other `example <https://github.com/kornia/kornia/tree/master/examples/face_detection/main_video.py>`_
diff --git a/docs/source/applications/video_deblur.rst b/docs/source/applications/video_deblur.rst
deleted file mode 100644
index 42e0d4a2f..000000000
--- a/docs/source/applications/video_deblur.rst
+++ /dev/null
@@ -1,9 +0,0 @@
-Video Deblurring
-================
-
-High level API for Video Deblurring is **COMING SOON** !!
-
-
-.. hint::
-
- In the meantime explore this: :py:class:~kornia.feature.DeFMO`
diff --git a/docs/source/contrib.rst b/docs/source/contrib.rst
index f3966d37b..61f5643f5 100644
--- a/docs/source/contrib.rst
+++ b/docs/source/contrib.rst
@@ -3,6 +3,19 @@ kornia.contrib
.. currentmodule:: kornia.contrib
+Face Detection
+--------------
+
+.. autoclass:: FaceDetector
+
+.. autoclass:: FaceKeypoint
+ :members:
+ :undoc-members:
+
+.. autoclass:: FaceDetectorResult
+ :members:
+ :undoc-members:
+
Image Segmentation
------------------
diff --git a/docs/source/geometry.bbox.rst b/docs/source/geometry.bbox.rst
index bb90fa8fc..32790e789 100644
--- a/docs/source/geometry.bbox.rst
+++ b/docs/source/geometry.bbox.rst
@@ -1,5 +1,5 @@
kornia.geometry.bbox
-==========================
+====================
Module with useful functionalities for 2D and 3D bounding boxes manipulation.
diff --git a/docs/source/geometry.boxes.rst b/docs/source/geometry.boxes.rst
index a9dd4ad94..841c060fd 100644
--- a/docs/source/geometry.boxes.rst
+++ b/docs/source/geometry.boxes.rst
@@ -1,5 +1,5 @@
kornia.geometry.boxes
-=======================
+=====================
Module with useful functionalities for 2D and 3D bounding boxes manipulation.
diff --git a/docs/source/index.rst b/docs/source/index.rst
index 999e5a82d..1068b52df 100644
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@ -54,18 +54,19 @@ Join the community
:hidden:
applications/intro
+ applications/face_detection
applications/image_augmentations
applications/image_classification
applications/image_matching
applications/image_stitching
applications/image_registration
applications/semantic_segmentation
- applications/video_deblur
.. toctree::
:caption: KORNIA MODELS
:hidden:
+ models/yunet
models/vit
models/vit_mobile
models/loftr
diff --git a/docs/source/models/yunet.rst b/docs/source/models/yunet.rst
new file mode 100644
index 000000000..b8092436e
--- /dev/null
+++ b/docs/source/models/yunet.rst
@@ -0,0 +1,20 @@
+YuNet (face_detection)
+......................
+
+.. card::
+ :link: https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=9429909
+
+ **A Systematic IoU-Related Method: Beyond Simplified Regression for Better Localization**
+ ^^^
+ **Abstract:** Four-variable-independent-regression localization losses, such as Smooth- l 1 Loss, are used by default in modern detectors. Nevertheless, this kind of loss is oversimplified so that it is inconsistent with the final evaluation metric, intersection over union (IoU). Directly employing the standard IoU is also not infeasible, since the constant-zero plateau in the case of non-overlapping boxes and the non-zero gradient at the minimum may make it not trainable. Accordingly, we propose a systematic method to address these problems. Firstly, we propose a new metric, the extended IoU (EIoU), which is well-defined when two boxes are not overlapping and reduced to the standard IoU when overlapping. Secondly, we present the convexification technique (CT) to construct a loss on the basis of EIoU, which can guarantee the gradient at the minimum to be zero. Thirdly, we propose a steady optimization technique (SOT) to make the fractional EIoU loss approaching the minimum more steadily and smoothly. Fourthly, to fully exploit the capability of the EIoU based loss, we introduce an interrelated IoU-predicting head to further boost localization accuracy. With the proposed contributions, the new method incorporated into Faster R-CNN with ResNet50+FPN as the backbone yields 4.2 mAP gain on VOC2007 and 2.3 mAP gain on COCO2017 over the baseline Smooth- l 1 Loss, at almost no training and inferencing computational cost. Specifically, the stricter the metric is, the more notable the gain is, improving 8.2 mAP on VOC2007 and 5.4 mAP on COCO2017 at metric AP.
+
+ **Tasks:** Face Detection
+
+ **Datasets:** WIDER Face
+
+ **Journal:** IEEE Transactions on Image Processing 2021
+
+ **Licence:** Apache-2.0
+
+ +++
+ **Authors:** Hanyang Peng and Shiqi Yu
diff --git a/docs/source/references.bib b/docs/source/references.bib
index 206347b0c..55f7d23d5 100644
--- a/docs/source/references.bib
+++ b/docs/source/references.bib
@@ -144,3 +144,10 @@
pages = {141–154},
numpages = {14}
}
+
+@article{facedetect-yu,
+ author={Yuantao Feng and Shiqi Yu and Hanyang Peng and Yan-ran Li and Jianguo Zhang},
+ title={Detect Faces Efficiently: A Survey and Evaluations},
+ journal={IEEE Transactions on Biometrics, Behavior, and Identity Science},
+ year={2021}
+ }
diff --git a/kornia/color/raw.py b/kornia/color/raw.py
index a55a98de9..a273ab5c5 100644
--- a/kornia/color/raw.py
+++ b/kornia/color/raw.py
@@ -5,7 +5,7 @@ import torch.nn as nn
class CFA(Enum):
- r"""Defines the configuration of the color filter array.
+ r"""Define the configuration of the color filter array.
So far only bayer images is supported and the enum sets the pixel order for bayer. Note that this can change due
to things like rotations and cropping of images. Take care if including the translations in pipeline.
diff --git a/kornia/contrib/__init__.py b/kornia/contrib/__init__.py
index a0cd948d4..a532e8efc 100644
--- a/kornia/contrib/__init__.py
+++ b/kornia/contrib/__init__.py
@@ -1,6 +1,7 @@
from .classification import ClassificationHead
from .connected_components import connected_components
from .extract_patches import combine_tensor_patches, CombineTensorPatches, extract_tensor_patches, ExtractTensorPatches
+from .face_detection import *
from .histogram_matching import histogram_matching, interp
from .image_stitching import ImageStitcher
from .lambda_module import Lambda
diff --git a/kornia/contrib/face_detection.py b/kornia/contrib/face_detection.py
new file mode 100644
index 000000000..79110116e
--- /dev/null
+++ b/kornia/contrib/face_detection.py
@@ -0,0 +1,414 @@
+# based on: https://github.com/ShiqiYu/libfacedetection.train/blob/74f3aa77c63234dd954d21286e9a60703b8d0868/tasks/task1/yufacedetectnet.py # noqa
+import math
+from enum import Enum
+from typing import Callable, Dict, List, Optional, Tuple
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from kornia.geometry.bbox import nms as nms_kornia
+
+__all__ = [
+ "FaceDetector",
+ "FaceDetectorResult",
+ "FaceKeypoint",
+]
+
+
+url: str = "https://github.com/ShiqiYu/libfacedetection.train/raw/master/tasks/task1/weights/yunet_final.pth"
+
+
+class FaceKeypoint(Enum):
+ r"""Define the keypoints detected in a face.
+
+ The left/right convention is based on the screen viewer.
+ """
+ EYE_LEFT = 0
+ EYE_RIGHT = 1
+ NOSE = 2
+ MOUTH_LEFT = 3
+ MOUTH_RIGHT = 4
+
+
+class FaceDetectorResult:
+ r"""Encapsulate the results obtained by the :py:class:`kornia.contrib.FaceDetector`.
+
+ Args:
+ data: the encoded results coming from the feature detector with shape :math:`(14,)`.
+
+ """
+ def __init__(self, data: torch.Tensor) -> None:
+ if len(data) < 15:
+ raise ValueError(f"Result must comes as vector of size(14). Got: {data.shape}.")
+ self._data = data
+
+ def to(self, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None) -> "FaceDetectorResult":
+ """Like :func:`torch.nn.Module.to()` method."""
+ self._data = self._data.to(device=device, dtype=dtype)
+ return self
+
+ @property
+ def xmin(self) -> torch.Tensor:
+ """The bounding box top-left x-coordinate."""
+ return self._data[..., 0]
+
+ @property
+ def ymin(self) -> torch.Tensor:
+ """The bounding box top-left y-coordinate."""
+ return self._data[..., 1]
+
+ @property
+ def xmax(self) -> torch.Tensor:
+ """The bounding box bottom-right x-coordinate."""
+ return self._data[..., 2]
+
+ @property
+ def ymax(self) -> torch.Tensor:
+ """The bounding box bottom-right y-coordinate."""
+ return self._data[..., 3]
+
+ def get_keypoint(self, keypoint: FaceKeypoint) -> torch.Tensor:
+ """The [x y] position of a given facial keypoint.
+
+ Args:
+ keypoint: the keypoint type to return the position.
+ """
+ if keypoint == FaceKeypoint.EYE_LEFT:
+ out = self._data[..., (4, 5)]
+ elif keypoint == FaceKeypoint.EYE_RIGHT:
+ out = self._data[..., (6, 7)]
+ elif keypoint == FaceKeypoint.NOSE:
+ out = self._data[..., (8, 9)]
+ elif keypoint == FaceKeypoint.MOUTH_LEFT:
+ out = self._data[..., (10, 11)]
+ elif keypoint == FaceKeypoint.MOUTH_RIGHT:
+ out = self._data[..., (12, 13)]
+ else:
+ raise ValueError(f"Not valid keypoint type. Got: {keypoint}.")
+ return out
+
+ @property
+ def score(self) -> torch.Tensor:
+ """The detection score."""
+ return self._data[..., 14]
+
+ @property
+ def width(self) -> torch.Tensor:
+ """The bounding box width."""
+ return self.xmax - self.xmin
+
+ @property
+ def height(self) -> torch.Tensor:
+ """The bounding box height."""
+ return self.ymax - self.ymin
+
+ @property
+ def top_left(self) -> torch.Tensor:
+ """The [x y] position of the top-left coordinate of the bounding box."""
+ return self._data[..., (0, 1)]
+
+ @property
+ def top_right(self) -> torch.Tensor:
+ """The [x y] position of the top-left coordinate of the bounding box."""
+ out = self.top_left
+ out[..., 0] += self.width
+ return out
+
+ @property
+ def bottom_right(self) -> torch.Tensor:
+ """The [x y] position of the bottom-right coordinate of the bounding box."""
+ return self._data[..., (2, 3)]
+
+ @property
+ def bottom_left(self) -> torch.Tensor:
+ """The [x y] position of the top-left coordinate of the bounding box."""
+ out = self.top_left
+ out[..., 1] += self.height
+ return out
+
+
+class FaceDetector(nn.Module):
+ r"""Detect faces in a given image using a CNN.
+
+ By default, it uses the method described in :cite:`facedetect-yu`.
+
+ Args:
+ top_k: the maximum number of detections to return before the nms.
+ confidence_threshold: the threshold used to discard detections.
+ nms_threshold: the threshold used by the nms for iou.
+ keep_top_k: the maximum number of detections to return after the nms.
+
+ Return:
+ A tensor of shape :math:`(N,15)` to be used with :py:class:`kornia.contrib.FaceDetectorResult`.
+
+ Example:
+ >>> img = torch.rand(1, 3, 320, 320)
+ >>> detect = FaceDetector()
+ >>> res = detect(img)
+ """
+ def __init__(self,
+ top_k: int = 5000,
+ confidence_threshold: float = 0.3,
+ nms_threshold: float = 0.3,
+ keep_top_k: int = 750) -> None:
+ super().__init__()
+ self.top_k = top_k
+ self.confidence_threshold = confidence_threshold
+ self.nms_threshold = nms_threshold
+ self.keep_top_k = keep_top_k
+ self.config = {
+ 'name': 'YuFaceDetectNet',
+ 'min_sizes': [[10, 16, 24], [32, 48], [64, 96], [128, 192, 256]],
+ 'steps': [8, 16, 32, 64],
+ 'variance': [0.1, 0.2],
+ 'clip': False,
+ }
+ self.min_sizes: List[List[int]] = [[10, 16, 24], [32, 48], [64, 96], [128, 192, 256]]
+ self.steps: List[int] = [8, 16, 32, 64]
+ self.variance: List[float] = [0.1, 0.2]
+ self.clip: bool = False
+ self.model = YuFaceDetectNet('test', pretrained=True)
+ self.nms: Callable = nms_kornia
+
+ def preprocess(self, image: torch.Tensor) -> torch.Tensor:
+ return image
+
+ def postprocess(self, data: Dict[str, torch.Tensor], height: int, width: int) -> torch.Tensor:
+ loc, conf, iou = data['loc'], data['conf'], data['iou']
+
+ scale = torch.tensor([
+ width, height, width, height,
+ width, height, width, height,
+ width, height, width, height,
+ width, height,
+ ], device=loc.device, dtype=loc.dtype) # 14
+
+ priors = _PriorBox(self.min_sizes, self.steps, self.clip, image_size=(height, width))
+ priors = priors.to(loc.device, loc.dtype)
+
+ boxes = _decode(loc, priors(), self.variance) # Nx14
+ boxes = boxes * scale
+
+ # clamp here for the compatibility for ONNX
+ cls_scores, iou_scores = conf[:, 1], iou[:, 0]
+ scores = (cls_scores * iou_scores.clamp(0., 1.)).sqrt()
+
+ # ignore low scores
+ inds = (scores > self.confidence_threshold)
+ boxes, scores = boxes[inds], scores[inds]
+
+ # keep top-K before NMS
+ order = scores.sort(descending=True)[1][:self.top_k]
+ boxes, scores = boxes[order], scores[order]
+
+ # performd NMS
+ # NOTE: nms need to be revise since does not export well to onnx
+ dets = torch.cat((boxes, scores[:, None]), dim=-1) # Nx15
+ keep = self.nms(boxes[:, :4], scores, self.nms_threshold)
+ if len(keep) > 0:
+ dets = dets[keep, :]
+
+ # keep top-K faster NMS
+ return dets[:self.keep_top_k]
+
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
+ img = self.preprocess(image)
+ out = self.model(img)
+ return self.postprocess(out, img.shape[-2], img.shape[-1])
+
+
+# utils for the network
+
+class ConvDPUnit(nn.Sequential):
+ def __init__(self, in_channels, out_channels, withBNRelu=True):
+ super().__init__()
+ self.add_module("conv1", nn.Conv2d(in_channels, out_channels, 1, 1, 0, bias=True, groups=1))
+ self.add_module("conv2", nn.Conv2d(out_channels, out_channels, 3, 1, 1, bias=True, groups=out_channels))
+ if withBNRelu:
+ self.add_module("bn", nn.BatchNorm2d(out_channels))
+ self.add_module("relu", nn.ReLU(inplace=True))
+
+
+class Conv_head(nn.Sequential):
+ def __init__(self, in_channels: int, mid_channels: int, out_channels: int) -> None:
+ super().__init__()
+ self.add_module("conv1", nn.Conv2d(in_channels, mid_channels, 3, 2, 1, bias=True, groups=1))
+ self.add_module("bn1", nn.BatchNorm2d(mid_channels))
+ self.add_module("relu", nn.ReLU(inplace=True))
+ self.add_module("conv2", ConvDPUnit(mid_channels, out_channels))
+
+
+class Conv4layerBlock(nn.Sequential):
+ def __init__(self, in_channels: int, out_channels: int, withBNRelu: bool = True) -> None:
+ super().__init__()
+ self.add_module("conv1", ConvDPUnit(in_channels, in_channels, True))
+ self.add_module("conv2", ConvDPUnit(in_channels, out_channels, withBNRelu))
+
+
+class YuFaceDetectNet(nn.Module):
+ def __init__(self, phase, pretrained: bool):
+ super().__init__()
+ self.phase = phase
+ self.num_classes = 2
+
+ self.model0 = Conv_head(3, 16, 16)
+ self.model1 = Conv4layerBlock(16, 64)
+ self.model2 = Conv4layerBlock(64, 64)
+ self.model3 = Conv4layerBlock(64, 64)
+ self.model4 = Conv4layerBlock(64, 64)
+ self.model5 = Conv4layerBlock(64, 64)
+ self.model6 = Conv4layerBlock(64, 64)
+
+ self.head = nn.Sequential(
+ Conv4layerBlock(64, 3 * (14 + 2 + 1), False),
+ Conv4layerBlock(64, 2 * (14 + 2 + 1), False),
+ Conv4layerBlock(64, 2 * (14 + 2 + 1), False),
+ Conv4layerBlock(64, 3 * (14 + 2 + 1), False),
+ )
+
+ if self.phase == 'train':
+ for m in self.modules():
+ if isinstance(m, nn.Conv2d):
+ if m.bias is not None:
+ nn.init.xavier_normal_(m.weight.data)
+ m.bias.data.fill_(0.02)
+ else:
+ m.weight.data.normal_(0, 0.01)
+ elif isinstance(m, nn.BatchNorm2d):
+ m.weight.data.fill_(1)
+ m.bias.data.zero_()
+
+ # use torch.hub to load pretrained model
+ if pretrained:
+ pretrained_dict = torch.hub.load_state_dict_from_url(
+ url, map_location=lambda storage, loc: storage
+ )
+ self.load_state_dict(pretrained_dict, strict=True)
+ self.eval()
+
+ def forward(self, x: torch.Tensor) -> Dict[str, torch.Tensor]:
+ detection_sources, head_list = [], []
+
+ x = self.model0(x)
+ x = F.max_pool2d(x, 2)
+ x = self.model1(x)
+ x = self.model2(x)
+ x = F.max_pool2d(x, 2)
+ x = self.model3(x)
+ detection_sources.append(x)
+
+ x = F.max_pool2d(x, 2)
+ x = self.model4(x)
+ detection_sources.append(x)
+
+ x = F.max_pool2d(x, 2)
+ x = self.model5(x)
+ detection_sources.append(x)
+
+ x = F.max_pool2d(x, 2)
+ x = self.model6(x)
+ detection_sources.append(x)
+
+ for i, h in enumerate(self.head):
+ x_tmp = h(detection_sources[i])
+ head_list.append(x_tmp.permute(0, 2, 3, 1).contiguous())
+
+ head_data = torch.cat([o.view(o.size(0), -1) for o in head_list], 1)
+ head_data = head_data.view(head_data.size(0), -1, 17)
+
+ loc_data, conf_data, iou_data = head_data.split((14, 2, 1), dim=-1)
+
+ if self.phase == "test":
+ loc_data = loc_data.view(-1, 14)
+ conf_data = torch.softmax(conf_data.view(-1, self.num_classes), dim=-1)
+ iou_data = iou_data.view(-1, 1)
+ else:
+ loc_data = loc_data.view(loc_data.size(0), -1, 14)
+ conf_data = conf_data.view(conf_data.size(0), -1, self.num_classes)
+ iou_data = iou_data.view(iou_data.size(0), -1, 1)
+
+ return {"loc": loc_data, "conf": conf_data, "iou": iou_data}
+
+
+# utils for post-processing
+
+
+# Adapted from https://github.com/Hakuyume/chainer-ssd
+def _decode(loc: torch.Tensor, priors: torch.Tensor, variances: List[float]) -> torch.Tensor:
+ """Decode locations from predictions using priors to undo the encoding we did for offset regression at train
+ time.
+
+ Args:
+ loc:location predictions for loc layers. Shape: [num_priors,4].
+ priors: Prior boxes in center-offset form. Shape: [num_priors,4].
+ variances: (list[float]) Variances of priorboxes.
+
+ Return:
+ Tensor containing decoded bounding box predictions.
+ """
+ boxes = torch.cat((
+ priors[:, 0:2] + loc[:, 0:2] * variances[0] * priors[:, 2:4],
+ priors[:, 2:4] * torch.exp(loc[:, 2:4] * variances[1]),
+ priors[:, 0:2] + loc[:, 4:6] * variances[0] * priors[:, 2:4],
+ priors[:, 0:2] + loc[:, 6:8] * variances[0] * priors[:, 2:4],
+ priors[:, 0:2] + loc[:, 8:10] * variances[0] * priors[:, 2:4],
+ priors[:, 0:2] + loc[:, 10:12] * variances[0] * priors[:, 2:4],
+ priors[:, 0:2] + loc[:, 12:14] * variances[0] * priors[:, 2:4]), 1)
+ # prepare final output
+ tmp = boxes[:, 0:2] - boxes[:, 2:4] / 2
+ return torch.cat((tmp, boxes[:, 2:4] + tmp, boxes[:, 4:]), dim=-1)
+
+
+class _PriorBox:
+ def __init__(self, min_sizes: List[List[int]], steps: List[int], clip: bool, image_size: Tuple[int, int]) -> None:
+ self.min_sizes = min_sizes
+ self.steps = steps
+ self.clip = clip
+ self.image_size = image_size
+
+ self.device: torch.device = torch.device('cpu')
+ self.dtype: torch.dtype = torch.float32
+
+ for i in range(4):
+ if(self.steps[i] != math.pow(2, (i + 3))):
+ raise ValueError("steps must be [8,16,32,64]")
+
+ self.feature_map_2th = [int(int((self.image_size[0] + 1) / 2) / 2),
+ int(int((self.image_size[1] + 1) / 2) / 2)]
+ self.feature_map_3th = [int(self.feature_map_2th[0] / 2),
+ int(self.feature_map_2th[1] / 2)]
+ self.feature_map_4th = [int(self.feature_map_3th[0] / 2),
+ int(self.feature_map_3th[1] / 2)]
+ self.feature_map_5th = [int(self.feature_map_4th[0] / 2),
+ int(self.feature_map_4th[1] / 2)]
+ self.feature_map_6th = [int(self.feature_map_5th[0] / 2),
+ int(self.feature_map_5th[1] / 2)]
+
+ self.feature_maps = [self.feature_map_3th, self.feature_map_4th,
+ self.feature_map_5th, self.feature_map_6th]
+
+ def to(self, device: torch.device, dtype: torch.dtype) -> '_PriorBox':
+ self.device = device
+ self.dtype = dtype
+ return self
+
+ def __call__(self) -> torch.Tensor:
+ anchors: List[float] = []
+ for k, f in enumerate(self.feature_maps):
+ min_sizes: List[int] = self.min_sizes[k]
+ # NOTE: the nested loop it's to make torchscript happy
+ for i in range(f[0]):
+ for j in range(f[1]):
+ for min_size in min_sizes:
+ s_kx = min_size / self.image_size[1]
+ s_ky = min_size / self.image_size[0]
+
+ cx = (j + 0.5) * self.steps[k] / self.image_size[1]
+ cy = (i + 0.5) * self.steps[k] / self.image_size[0]
+ anchors += [cx, cy, s_kx, s_ky]
+ # back to torch land
+ output = torch.tensor(anchors, device=self.device, dtype=self.dtype).view(-1, 4)
+ if self.clip:
+ output = output.clamp(max=1, min=0)
+ return output
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index 74249bd4d..65f570ea8 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -14,6 +14,7 @@ __all__ = [
"bbox_generator",
"bbox_generator3d",
"transform_bbox",
+ "nms",
]
@@ -465,3 +466,61 @@ def transform_bbox(trans_mat: torch.Tensor, boxes: torch.Tensor, mode: str = "xy
transformed_boxes[..., 3] = transformed_boxes[..., 3] - transformed_boxes[..., 1]
return transformed_boxes
+
+
+def nms(boxes: torch.Tensor, scores: torch.Tensor, iou_threshold: float) -> torch.Tensor:
+ """Perform non-maxima suppression (NMS) on a given tensor of bounding boxes according to the intersection-over-
+ union (IoU).
+
+ Args:
+ boxes: tensor containing the encoded bounding boxes with the shape :math:`(N, (x_1, y_1, x_2, y_2))`.
+ scores: tensor containing the scores associated to each bounding box with shape :math:`(N,)`.
+ iou_threshold: the throshold to discard the overlapping boxes.
+
+ Return:
+ A tensor mask with the indices to keep from the input set of boxes and scores.
+
+ Example:
+ >>> boxes = torch.tensor([
+ ... [10., 10., 20., 20.],
+ ... [15., 5., 15., 25.],
+ ... [100., 100., 200., 200.],
+ ... [100., 100., 200., 200.]])
+ >>> scores = torch.tensor([0.9, 0.8, 0.7, 0.9])
+ >>> nms(boxes, scores, iou_threshold=0.8)
+ tensor([0, 3, 1])
+ """
+ if len(boxes.shape) != 2 and boxes.shape[-1] != 4:
+ raise ValueError(f"boxes expected as Nx4. Got: {boxes.shape}.")
+
+ if len(scores.shape) != 1:
+ raise ValueError(f"scores expected as N. Got: {scores.shape}.")
+
+ if boxes.shape[0] != scores.shape[0]:
+ raise ValueError(f"boxes and scores mus have same shape. Got: {boxes.shape, scores.shape}.")
+
+ x1, y1, x2, y2 = boxes.unbind(-1)
+ areas = (x2 - x1) * (y2 - y1)
+
+ _, order = scores.sort(descending=True)
+
+ keep = []
+ while order.shape[0] > 0:
+ i = order[0]
+ keep.append(i)
+ xx1 = torch.max(x1[i], x1[order[1:]])
+ yy1 = torch.max(y1[i], y1[order[1:]])
+ xx2 = torch.min(x2[i], x2[order[1:]])
+ yy2 = torch.min(y2[i], y2[order[1:]])
+
+ w = torch.clamp(xx2 - xx1, min=0.)
+ h = torch.clamp(yy2 - yy1, min=0.)
+ inter = w * h
+ ovr = inter / (areas[i] + areas[order[1:]] - inter)
+
+ inds = torch.where(ovr <= iou_threshold)[0]
+ order = order[inds + 1]
+
+ if len(keep) > 0:
+ return torch.stack(keep)
+ return torch.tensor(keep)
diff --git a/test/geometry/test_bbox.py b/test/geometry/test_bbox.py
index c0e0319ea..a28f2cf7c 100644
--- a/test/geometry/test_bbox.py
+++ b/test/geometry/test_bbox.py
@@ -4,7 +4,14 @@ from torch.testing import assert_allclose
import kornia
import kornia.testing as utils
-from kornia.geometry.bbox import infer_bbox_shape, infer_bbox_shape3d, transform_bbox, validate_bbox, validate_bbox3d
+from kornia.geometry.bbox import (
+ infer_bbox_shape,
+ infer_bbox_shape3d,
+ nms,
+ transform_bbox,
+ validate_bbox,
+ validate_bbox3d,
+)
class TestBbox2D:
@@ -242,3 +249,17 @@ class TestBbox3D:
actual = op_script(boxes)
expected = op(boxes)
assert_allclose(actual, expected)
+
+
+class TestNMS:
+ def test_smoke(self, device, dtype):
+ boxes = torch.tensor([
+ [10., 10., 20., 20.],
+ [15., 5., 15., 25.],
+ [100., 100., 200., 200.],
+ [100., 100., 200., 200.],
+ ], device=device, dtype=dtype)
+ scores = torch.tensor([0.9, 0.8, 0.7, 0.9], device=device, dtype=dtype)
+ expected = torch.tensor([0, 3, 1], device=device, dtype=torch.long)
+ actual = nms(boxes, scores, iou_threshold=0.8)
+ assert_allclose(actual, expected)
diff --git a/test/test_contrib.py b/test/test_contrib.py
index 0b5519064..b90b0ccc5 100644
--- a/test/test_contrib.py
+++ b/test/test_contrib.py
@@ -6,6 +6,7 @@ from torch.autograd import gradcheck
import kornia
import kornia.testing as utils # test utils
+from kornia.contrib.face_detection import FaceKeypoint
from kornia.testing import assert_close
from packaging import version
@@ -401,3 +402,47 @@ class TestHistMatch:
src = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
dst = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
assert gradcheck(kornia.contrib.histogram_matching, (src, dst,), raise_exception=True)
+
+
+class TestFaceDetection:
+ def test_smoke(self, device, dtype):
+ assert kornia.contrib.FaceDetector().to(device, dtype) is not None
+
+ def test_valid(self, device, dtype):
+ torch.manual_seed(44)
+ img = torch.rand(1, 3, 320, 320, device=device, dtype=dtype)
+ face_detection = kornia.contrib.FaceDetector().to(device, dtype)
+ dets = face_detection(img)
+ assert len(dets) == 1
+
+ def test_jit(self, device, dtype):
+ op = kornia.contrib.FaceDetector().to(device, dtype)
+ op_jit = torch.jit.script(op)
+ assert op_jit is not None
+
+ def test_results(self, device, dtype):
+ data = torch.tensor([
+ 0., 0., 100., 200., 10., 10., 20., 10., 10., 50., 100., 50., 150., 10., 0.99,
+ ], device=device, dtype=dtype)
+ res = kornia.contrib.FaceDetectorResult(data)
+ assert res.xmin == 0.
+ assert res.ymin == 0.
+ assert res.xmax == 100.
+ assert res.ymax == 200.
+ assert res.score == 0.99
+ assert res.width == 100.
+ assert res.height == 200.
+ assert res.top_left.tolist() == [0., 0.]
+ assert res.top_right.tolist() == [100., 0.]
+ assert res.bottom_right.tolist() == [100., 200.]
+ assert res.bottom_left.tolist() == [0., 200.]
+ assert res.get_keypoint(FaceKeypoint.EYE_LEFT).tolist() == [10., 10.]
+ assert res.get_keypoint(FaceKeypoint.EYE_RIGHT).tolist() == [20., 10.]
+ assert res.get_keypoint(FaceKeypoint.NOSE).tolist() == [10., 50.]
+ assert res.get_keypoint(FaceKeypoint.MOUTH_LEFT).tolist() == [100., 50.]
+ assert res.get_keypoint(FaceKeypoint.MOUTH_RIGHT).tolist() == [150., 10.]
+
+ def test_results_raise(self, device, dtype):
+ data = torch.zeros(14, device=device, dtype=dtype)
+ with pytest.raises(ValueError):
+ _ = kornia.contrib.FaceDetectorResult(data)