π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(contrib): feed YuNet and DexiNed BGR as trained; DexiNed backward; FaceDetectorResult row check (#6042)
Dmytro Mishkin6cd8a54b06a7
diff --git a/changelog.d/6042.breaking.md b/changelog.d/6042.breaking.mdnew file mode 100644index 000000000..ef9941d0c--- /dev/null+++ b/changelog.d/6042.breaking.md@@ -0,0 +1 @@+In the `EdgeDetector` that `EdgeDetectorBuilder.build("dexined")` returns, `model[0]` is now `nn.Sequential(RgbToBgr(), Normalize(...))`, and the normalisation is `model[0][1]`, with the BGR mean `[103.939, 116.779, 123.68] / 255`. `model[0]` was the `Normalize` module itself, with the ImageNet RGB mean `[0.485, 0.456, 0.406]`, so code that reads `model[0].mean` or `model[0].std` now raises `AttributeError`; read `model[0][1].mean` and `model[0][1].std` instead. DexiNed stays at `model[1]`, so a saved `EdgeDetector` state dict keeps its `model.1.*` keys.diff --git a/changelog.d/6042.fixed.md b/changelog.d/6042.fixed.mdnew file mode 100644index 000000000..63a7b91f1--- /dev/null+++ b/changelog.d/6042.fixed.md@@ -0,0 +1 @@+`FaceDetector` flips its input from RGB to BGR before YuNet, whose weights were trained on BGR images. It fed RGB, which found far fewer faces: run on the docs figure `yunet.jpg` as rendered before this change (421Γ1185, input and output panels together), the detector now returns 600 detections instead of 221, and 225 instead of 50 above a score of 0.6. The re-rendered figure's title reports 320 faces where it reported 228. The input stays RGB in [0, 255]; the bare `YuNet` takes BGR in [0, 255]. A caller that already passed BGR, for example a `cv2.imread` array, must now pass RGB, since the flip happens inside. An input that is not `(*, 3, H, W)`, such as a 1- or 4-channel or a channels-last image, raises a `ValueError` naming that shape from the flip; it raised a `RuntimeError` from inside YuNet. `EdgeDetectorBuilder` feeds DexiNed BGR in [0, 255] minus the BGR mean `[103.939, 116.779, 123.68]`, the input it was trained on, instead of RGB minus the ImageNet RGB mean; on two street photos this changed 8β11 % of the `p > 0.5` edge decisions. The input stays RGB in [0, 1]. `DexiNed` (`kornia.models.dexined` and `kornia.filters.dexined`) no longer raises a `RuntimeError` about an in-place operation in backward; its forward output is unchanged. `FaceDetectorResult` checks the last dimension of its data, so `(15,)` and `(N, 15)` are accepted and a row of fewer than 15 values raises `ValueError`. It checked the first dimension, so a `(3, 15)` tensor raised and a `(20, 14)` one was accepted until `.score` raised `IndexError`.diff --git a/docs/export_support/cases_models.py b/docs/export_support/cases_models.pyindex c69a08ad2..fd9da1586 100644--- a/docs/export_support/cases_models.py+++ b/docs/export_support/cases_models.py@@ -1160,9 +1160,7 @@ A(-1,),[torch.rand(15) * 60],- note="property accessors on a (15,) detection vector; __init__ requires len(data) >= 15 "- "(message says 14) so a (N,15) "- "batch with N<15 is rejected",+ note="property accessors on a (15,) detection vector; __init__ requires a last dimension of at least 15",))A(case("contrib.FaceKeypoint", "contrib.wrappers", None, [], skip="enum"))@@ -1175,8 +1173,8 @@ A(reuse(edge, _e_ed),lambda m: m,[torch.rand(1, 3, 48, 80) * 255],- note="Normalize -> DexiNed -> Sigmoid with ResizePreProcessor(64,64) and ResizePostProcessor (numpy tolist); "- "image_size=64 baked",+ note="RgbToBgr + Normalize -> DexiNed -> Sigmoid with ResizePreProcessor(64,64) and ResizePostProcessor "+ "(numpy tolist); image_size=64 baked",tags=("model", "pretrained"),))@@ -1187,7 +1185,7 @@ A(reuse(edge, _e_ed),lambda m: m.model,[torch.rand(1, 3, 64, 64)],- note="core nn.Sequential(Normalize, DexiNed, Sigmoid) without pre/post processors",+ note="core nn.Sequential(nn.Sequential(RgbToBgr, Normalize), DexiNed, Sigmoid) without pre/post processors",tags=("model", "pretrained"),))diff --git a/docs/source/_data/export_support.json b/docs/source/_data/export_support.jsonindex 704e0ca07..c17d62ced 100644--- a/docs/source/_data/export_support.json+++ b/docs/source/_data/export_support.json@@ -21869,7 +21869,7 @@"export_detail": "","graph_breaks": 0,"name": "contrib.FaceDetectorResult",- "note": "property accessors on a (15,) detection vector; __init__ requires len(data) >= 15 (message says 14) so a (N,15) batch with N<15 is rejected",+ "note": "property accessors on a (15,) detection vector; __init__ requires a last dimension of at least 15","onnx": "ok","onnx_detail": "","operator": "FaceDetectorResult",@@ -21903,7 +21903,7 @@"export_detail": "RuntimeError : .numpy() is not supported for tensor subclasses.","graph_breaks": 0,"name": "contrib.EdgeDetectorBuilder.build[dexined,image_size=64]",- "note": "Normalize -> DexiNed -> Sigmoid with ResizePreProcessor(64,64) and ResizePostProcessor (numpy tolist); image_size=64 baked | to_onnx(save=False) OK (134.07 MB, ['ai.onnx:18'], in [['input', ['s34', 3, 352, 352]]], out [['output', [1, 1, 64, 64]]])",+ "note": "RgbToBgr + Normalize -> DexiNed -> Sigmoid with ResizePreProcessor(64,64) and ResizePostProcessor (numpy tolist); image_size=64 baked | to_onnx(save=False) OK (134.07 MB, ['ai.onnx:18'], in [['input', ['s34', 3, 352, 352]]], out [['output', [1, 1, 64, 64]]])","onnx": "mismatch","onnx_detail": "runs, but the result differs from eager: out0: shape (1, 1, 48, 80) vs (1, 1, 64, 64)","operator": "EdgeDetectorBuilder.build",@@ -21920,7 +21920,7 @@"export_detail": "","graph_breaks": 0,"name": "contrib.EdgeDetector.model",- "note": "core nn.Sequential(Normalize, DexiNed, Sigmoid) without pre/post processors",+ "note": "core nn.Sequential(nn.Sequential(RgbToBgr, Normalize), DexiNed, Sigmoid) without pre/post processors","onnx": "ok","onnx_detail": "","operator": "EdgeDetector.model",diff --git a/docs/source/_static/img/models/dexined.jpg b/docs/source/_static/img/models/dexined.jpgindex f7d145861..8bfb9c23b 100644Binary files a/docs/source/_static/img/models/dexined.jpg and b/docs/source/_static/img/models/dexined.jpg differdiff --git a/docs/source/_static/img/models/yunet.jpg b/docs/source/_static/img/models/yunet.jpgindex 31650550b..fbad6d388 100644Binary files a/docs/source/_static/img/models/yunet.jpg and b/docs/source/_static/img/models/yunet.jpg differdiff --git a/docs/source/applications/face_detection.rst b/docs/source/applications/face_detection.rstindex db21aed45..4386e1966 100644--- a/docs/source/applications/face_detection.rst+++ b/docs/source/applications/face_detection.rst@@ -28,7 +28,8 @@ Using our API you can easily detect faces in images as shown below:# select the devicedevice = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")- # load the image as a (1, 3, H, W) float tensor in [0, 255], the range YuNet expects+ # load the image as a (1, 3, H, W) RGB float tensor in [0, 255], the range FaceDetector expects;+ # it flips the channels to the BGR order YuNet was trained onimg = K.io.load_image("image.jpg", ImageLoadType.RGB32, device=device)[None] * 255.0# create the detector and find the facesdiff --git a/docs/source/models/dexined.rst b/docs/source/models/dexined.rstindex 2352cb03d..5bba5cb4f 100644--- a/docs/source/models/dexined.rst+++ b/docs/source/models/dexined.rst@@ -24,7 +24,7 @@ Run itfrom kornia.contrib.edge_detection import EdgeDetectorBuilderfrom kornia.io import load_image- image = load_image("girona.png")[None] # (1, 3, H, W) float in [0, 1]+ image = load_image("girona.png")[None] # (1, 3, H, W) RGB float in [0, 1]detector = EdgeDetectorBuilder.build("dexined", pretrained=True, image_size=352) # runs the net at 352 pxwith torch.no_grad():@@ -37,9 +37,10 @@ Run itThe input image and its DexiNed edge probability map (dark = edge).The detector accepts a batch tensor or a list of ``(3, H, W)`` images of different sizes and returns one edge map-per image. To use the bare network, :class:`~kornia.models.dexined.DexiNed` takes a ``(B, 3, H, W)`` input scaled to-``[0, 255]`` and mean-subtracted and returns the fused edge logits; ``EdgeDetectorBuilder`` also exposes-``to_onnx()`` for export.+per image. To use the bare network, :class:`~kornia.models.dexined.DexiNed` takes a ``(B, 3, H, W)`` BGR input scaled+to ``[0, 255]`` minus the BGR mean ``[103.939, 116.779, 123.68]``, the input it was trained on, and returns the fused+edge logits; the detector that ``EdgeDetectorBuilder`` builds converts an RGB image in ``[0, 1]`` to that input and+exposes ``to_onnx()`` for export.Paper-----diff --git a/docs/source/models/yunet.rst b/docs/source/models/yunet.rstindex bd2c876f5..89e8a6b14 100644--- a/docs/source/models/yunet.rst+++ b/docs/source/models/yunet.rst@@ -12,8 +12,10 @@ YuNetYuNet is a millisecond-level face detector that predicts a box, a confidence and five facial landmarks (eyes, nose,mouth corners) per face. Kornia exposes it as :class:`~kornia.contrib.FaceDetector`, which takes a ``(B, 3, H, W)``-image with pixel values in ``[0, 255]`` and returns one ``(N, 15)`` tensor per image; wrap each row in-:class:`~kornia.contrib.FaceDetectorResult` to read the fields by name.+RGB image with pixel values in ``[0, 255]`` and returns one ``(N, 15)`` tensor per image; wrap each row in+:class:`~kornia.contrib.FaceDetectorResult` to read the fields by name. The pretrained YuNet was trained on BGR images+in ``[0, 255]``, so ``FaceDetector`` flips the channels before the network; the bare :class:`~kornia.models.yunet.YuNet`+takes that BGR input directly.Run it------@@ -23,7 +25,7 @@ Run itfrom kornia.io import load_imagefrom kornia.contrib import FaceDetector, FaceDetectorResult, FaceKeypoint- image = load_image("crowd.jpg")[None] * 255.0 # (1, 3, H, W); YuNet expects pixel values in [0, 255]+ image = load_image("crowd.jpg")[None] * 255.0 # (1, 3, H, W) RGB; FaceDetector expects pixel values in [0, 255]detector = FaceDetector() # downloads the YuNet weights when constructedfaces = [FaceDetectorResult(f) for f in detector(image)[0]] # one result per detected facediff --git a/kornia/contrib/edge_detection.py b/kornia/contrib/edge_detection.pyindex feb475823..91665a91e 100644--- a/kornia/contrib/edge_detection.py+++ b/kornia/contrib/edge_detection.py@@ -23,6 +23,7 @@ import torchfrom torch import nnfrom kornia.color.gray import grayscale_to_rgb+from kornia.color.rgb import RgbToBgrfrom kornia.core.external import PILImage as Imagefrom kornia.core.external import onnxfrom kornia.core.mixin.onnx import ONNXExportMixin@@ -38,6 +39,8 @@ class EdgeDetector(ModelBase, ONNXExportMixin):"""EdgeDetector is a module that wraps an edge detection model.This is a high-level API that wraps edge detection models like :py:class:`kornia.models.DexiNed`.+ :py:class:`~kornia.contrib.edge_detection.EdgeDetectorBuilder` builds one with the input conversion, the network+ and the sigmoid in ``model``.Args:model: The edge detection model.@@ -46,12 +49,9 @@ class EdgeDetector(ModelBase, ONNXExportMixin):name: Optional name for the detector.Example:- >>> from kornia.models.dexined import DexiNed- >>> from kornia.models.processors import ResizePreProcessor, ResizePostProcessor- >>> model = DexiNed(pretrained=True)- >>> detector = EdgeDetector(model, ResizePreProcessor(352, 352), ResizePostProcessor())- >>> img = torch.rand(1, 3, 320, 320)- >>> out = detector(img)+ >>> detector = EdgeDetectorBuilder.build("dexined", pretrained=True, image_size=352)+ >>> img = torch.rand(1, 3, 320, 320) # RGB in [0, 1]+ >>> out = detector(img) # a list with one (1, 1, 320, 320) edge probability map per image"""@@ -105,10 +105,14 @@ class EdgeDetector(ModelBase, ONNXExportMixin):Args:images: If list of RGB images. Each image is a torch.Tensor with shape :math:`(3, H, W)`.- If torch.Tensor, a torch.Tensor with shape :math:`(B, 3, H, W)`.+ If torch.Tensor, a torch.Tensor with shape :math:`(B, 3, H, W)`. For a detector from+ :py:class:`~kornia.contrib.edge_detection.EdgeDetectorBuilder`, the pixel values are in+ :math:`[0, 1]`.Returns:- output torch.Tensor.+ A list with one output of shape :math:`(1, 1, H, W)` per input image, resized back to that image's size.+ For a detector from :py:class:`~kornia.contrib.edge_detection.EdgeDetectorBuilder`, it holds edge+ probabilities in :math:`[0, 1]`."""images, image_sizes = self.pre_processor(images)@@ -220,6 +224,10 @@ class EdgeDetectorBuilder:def build(model_name: str = "dexined", pretrained: bool = True, image_size: int = 352) -> EdgeDetector:"""Build an edge detection model.+ The detector takes RGB images in :math:`[0, 1]`. For ``"dexined"`` it flips them to BGR, scales them to+ :math:`[0, 255]` and subtracts the BGR mean ``[103.939, 116.779, 123.68]``, the input the pretrained DexiNed+ was trained on (xavysp/DexiNed@d944b70), then applies a sigmoid to the network's logits.+Args:model_name: Name of the model to build. Currently only "dexined" is supported.pretrained: If True, loads pretrained weights.@@ -235,9 +243,12 @@ class EdgeDetectorBuilder:"""if model_name.lower() == "dexined":- # Normalize then scale to [0, 255]- norm = Normalize(mean=torch.tensor([[0.485, 0.456, 0.406]]), std=torch.tensor([[1.0 / 255.0] * 3]))- model = nn.Sequential(norm, DexiNed(pretrained=pretrained), nn.Sigmoid())+ # RGB in [0, 1] -> 255 * BGR - mean_bgr, with mean_bgr in B, G, R order (xavysp/DexiNed@d944b70+ # main.py:319-320). Both steps share slot 0, so DexiNed stays at ``model[1]`` and the state-dict keys stay+ # ``model.1.*``.+ mean_bgr = torch.tensor([[103.939, 116.779, 123.68]])+ to_bgr = nn.Sequential(RgbToBgr(), Normalize(mean=mean_bgr / 255.0, std=torch.tensor([[1.0 / 255.0] * 3])))+ model = nn.Sequential(to_bgr, DexiNed(pretrained=pretrained), nn.Sigmoid())else:raise ValueError(f"Model {model_name} not found. Please choose from 'dexined'.")diff --git a/kornia/contrib/face_detection.py b/kornia/contrib/face_detection.pyindex 83ed4e28a..149256faf 100644--- a/kornia/contrib/face_detection.py+++ b/kornia/contrib/face_detection.py@@ -21,6 +21,7 @@ from typing import Dict, List, Optionalimport torchfrom torch import nn+from kornia.color.rgb import rgb_to_bgrfrom kornia.geometry.bbox import nms as nms_korniafrom kornia.models.yunet import YuNetfrom kornia.models.yunet.processors import PriorBox@@ -46,13 +47,15 @@ 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,)`.+ data: the detections returned by :py:class:`kornia.contrib.FaceDetector`, one row of 15 values per face with+ shape :math:`(15,)` or :math:`(N, 15)`: the box ``xmin, ymin, xmax, ymax``, five ``(x, y)`` landmarks+ (see :py:class:`kornia.contrib.FaceKeypoint`) and the score."""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}.")+ if data.shape[-1] < 15:+ raise ValueError(f"Result must come as a row of 15 values in its last dimension. Got: {data.shape}.")self._data = datadef to(self, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None) -> "FaceDetectorResult":@@ -147,6 +150,9 @@ class FaceDetector(nn.Module):This is a high-level API that wraps the :py:class:`kornia.models.YuNet` model for face detection.By default, it uses the method described in :cite:`facedetect-yu`.+ The input is an RGB image with pixel values in :math:`[0, 255]`, not :math:`[0, 1]`. The detector flips it to BGR+ before YuNet, whose pretrained weights were trained on BGR images in :math:`[0, 255]`.+Args:top_k: the maximum number of detections to return before the nms.confidence_threshold: the threshold used to discard detections.@@ -157,7 +163,7 @@ class FaceDetector(nn.Module):A list of B tensors with shape :math:`(N,15)` to be used with :py:class:`kornia.contrib.FaceDetectorResult`.Example:- >>> img = torch.rand(1, 3, 320, 320)+ >>> img = torch.rand(1, 3, 320, 320) * 255 # RGB in [0, 255]>>> detect = FaceDetector()>>> res = detect(img)@@ -189,17 +195,19 @@ class FaceDetector(nn.Module):"""Preprocess input images before feeding them to YuNet.Args:- image: Batch of RGB images with shape :math:`(B, 3, H, W)`, where:+ image: Batch of RGB images with pixel values in :math:`[0, 255]` and shape :math:`(B, 3, H, W)`, where:- ``B`` is batch size,- ``3`` is the RGB channel dimension,- ``H`` is image height,- ``W`` is image width.Returns:- The preprocessed image tensor. The current implementation returns the- input unchanged and acts as an extension point for custom pipelines.+ The same images in BGR channel order, still in :math:`[0, 255]`: the input YuNet was trained on.++ Raises:+ ValueError: If the image is not of shape :math:`(*, 3, H, W)`."""- return image+ return rgb_to_bgr(image)def postprocess(self, data: Dict[str, torch.Tensor], height: int, width: int) -> List[torch.Tensor]:"""Decode model outputs into filtered face detections.@@ -262,7 +270,7 @@ class FaceDetector(nn.Module):r"""Detect faces in a given batch of images.Args:- image: batch of images :math:`(B,3,H,W)`+ image: batch of RGB images with pixel values in :math:`[0, 255]` and shape :math:`(B,3,H,W)`.Return:List[torch.Tensor]: list with the boxes found on each image. :math:`Bx(N,15)`.diff --git a/kornia/filters/dexined.py b/kornia/filters/dexined.pyindex ab443829e..0c1e4c4a9 100644--- a/kornia/filters/dexined.py+++ b/kornia/filters/dexined.py@@ -110,7 +110,8 @@ class _DenseLayer(nn.Sequential):super().__init__(OrderedDict([- ("relu1", nn.ReLU(inplace=True)),+ # Out of place: a dense block's input is also read by a side branch, which saved it for backward.+ ("relu1", nn.ReLU()),("conv1", nn.Conv2d(input_features, out_features, kernel_size=3, stride=1, padding=2, bias=True)),("norm1", nn.BatchNorm2d(out_features)),("relu2", nn.ReLU(inplace=True)),@@ -301,9 +302,12 @@ class DoubleConvBlock(nn.Sequential):class DexiNed(nn.Module):r"""Definition of the DXtrem network from :cite:`xsoria2020dexined`.+ The input is a BGR image with pixel values in :math:`[0, 255]` minus the BGR mean ``[103.939, 116.779, 123.68]``:+ the pretrained weights were trained on images read with ``cv2.imread`` and shifted by that mean+ (xavysp/DexiNed@d944b70).+Return:- A list of torch.Tensor with the intermediate features which the last element- is the edges map with shape :math:`(B,1,H,W)`.+ The fused edge logits, one tensor with shape :math:`(B,1,H,W)`.Example:>>> img = torch.rand(1, 3, 320, 320)@@ -387,13 +391,12 @@ class DexiNed(nn.Module):produces a feature map at a different semantic depth and spatial scale;the corresponding side branch upsamples it back to the original imageresolution. The returned list is later concatenated and fused by- ``CoFusion``.+ a 1x1 convolution (``block_cat``).Args:- x: Input image tensor with shape :math:`(B, 3, H, W)`, where- :math:`B` is the batch size, ``3`` is the RGB channel count,- :math:`H` is the image height, and :math:`W` is the image- width.+ x: Input BGR image tensor in :math:`[0, 255]` minus the BGR mean ``[103.939, 116.779, 123.68]``, with+ shape :math:`(B, 3, H, W)`, where :math:`B` is the batch size, :math:`H` is the image height, and+ :math:`W` is the image width.Returns:List of six tensors, each aligned to the input spatial size. Every@@ -446,7 +449,7 @@ class DexiNed(nn.Module):return [out_1, out_2, out_3, out_4, out_5, out_6]def forward(self, x: torch.Tensor) -> torch.Tensor:- """Predict a fused edge map from an RGB image batch.+ """Predict a fused edge map from a BGR image batch.The forward pass collects six multi-scale side outputs, concatenatesthem along the channel dimension, and applies the fusion block to@@ -454,14 +457,13 @@ class DexiNed(nn.Module):and deeper semantic boundary information in the prediction.Args:- x: Input image tensor with shape :math:`(B, 3, H, W)`, where- :math:`B` is the batch size, ``3`` is the RGB channel count,- :math:`H` is the image height, and :math:`W` is the image- width.+ x: Input BGR image tensor in :math:`[0, 255]` minus the BGR mean ``[103.939, 116.779, 123.68]``, with+ shape :math:`(B, 3, H, W)`, where :math:`B` is the batch size, :math:`H` is the image height, and+ :math:`W` is the image width.Returns:Tensor with shape :math:`(B, 1, H, W)` containing the fused edge- probability-style response for each image in the batch.+ logits for each image in the batch."""features = self.get_features(x)diff --git a/kornia/models/dexined.py b/kornia/models/dexined.pyindex dab192ab8..fe62e0a8c 100644--- a/kornia/models/dexined.py+++ b/kornia/models/dexined.py@@ -88,7 +88,8 @@ class _DenseLayer(nn.Sequential):super().__init__(OrderedDict([- ("relu1", nn.ReLU(inplace=True)),+ # Out of place: a dense block's input is also read by a side branch, which saved it for backward.+ ("relu1", nn.ReLU()),("conv1", nn.Conv2d(input_features, out_features, kernel_size=3, stride=1, padding=2, bias=True)),("norm1", nn.BatchNorm2d(out_features)),("relu2", nn.ReLU(inplace=True)),@@ -190,9 +191,13 @@ class DoubleConvBlock(nn.Sequential):class DexiNed(ONNXExportMixin, nn.Module):r"""Definition of the DXtrem network from :cite:`xsoria2020dexined`.+ The input is a BGR image with pixel values in :math:`[0, 255]` minus the BGR mean ``[103.939, 116.779, 123.68]``:+ the pretrained weights were trained on images read with ``cv2.imread`` and shifted by that mean+ (xavysp/DexiNed@d944b70). The detector that :py:class:`~kornia.contrib.edge_detection.EdgeDetectorBuilder` builds+ converts an RGB image in :math:`[0, 1]` to this input and applies a sigmoid to the output.+Return:- A list of tensor with the intermediate features which the last element- is the edges map with shape :math:`(B,1,H,W)`.+ The fused edge logits, one tensor with shape :math:`(B,1,H,W)`.Example:>>> img = torch.rand(1, 3, 320, 320)@@ -269,8 +274,8 @@ class DexiNed(ONNXExportMixin, nn.Module):"""Compute the six multi-scale DexiNed side-output edge maps.Args:- x: Input RGB image tensor with shape :math:`(B, 3, H, W)`, where- :math:`B` is batch size, :math:`H` is height, and :math:`W` is+ x: Input BGR image tensor in :math:`[0, 255]` minus the BGR mean ``[103.939, 116.779, 123.68]``, with+ shape :math:`(B, 3, H, W)`, where :math:`B` is batch size, :math:`H` is height, and :math:`W` iswidth.Returns:@@ -322,14 +327,15 @@ class DexiNed(ONNXExportMixin, nn.Module):return [out_1, out_2, out_3, out_4, out_5, out_6]def forward(self, x: torch.Tensor) -> torch.Tensor:- """Predict a fused edge map from an RGB image batch.+ """Predict a fused edge map from a BGR image batch.Args:- x: Input RGB image tensor with shape :math:`(B, 3, H, W)`.+ x: Input BGR image tensor in :math:`[0, 255]` minus the BGR mean ``[103.939, 116.779, 123.68]``, with+ shape :math:`(B, 3, H, W)`.Returns:Tensor with shape :math:`(B, 1, H, W)` containing the fused DexiNed- edge response.+ edge logits."""features = self.get_features(x)diff --git a/kornia/models/yunet/model.py b/kornia/models/yunet/model.pyindex a1515fe72..756b0a3da 100644--- a/kornia/models/yunet/model.py+++ b/kornia/models/yunet/model.py@@ -64,6 +64,11 @@ class YuNet(nn.Module):This is the underlying CNN model used by :py:class:`kornia.contrib.FaceDetector` for face detection.The model architecture is based on the method described in :cite:`facedetect-yu`.+ The input is a BGR image with pixel values in :math:`[0, 255]`, with no mean or standard deviation applied: the+ pretrained weights were trained on such images (ShiqiYu/libfacedetection.train@74f3aa7 ``src/data.py:76, 90``)+ and evaluated on images read with ``cv2.imread`` (``tasks/task1/datasets.py:53``, ``detect.py:100-106``).+ :py:class:`kornia.contrib.FaceDetector` takes RGB in :math:`[0, 255]` and flips it to BGR before this model.+Args:phase: the phase of the model, either "train" or "test".pretrained: if True, loads pretrained weights from the official repository and returns the model in@@ -71,7 +76,7 @@ class YuNet(nn.Module):Example:>>> model = YuNet("test", pretrained=True)- >>> img = torch.rand(1, 3, 320, 320)+ >>> img = torch.rand(1, 3, 320, 320) * 255 # BGR in [0, 255]>>> out = model(img)"""diff --git a/kornia/models/yunet/processors.py b/kornia/models/yunet/processors.pyindex 58e99a519..237790be2 100644--- a/kornia/models/yunet/processors.py+++ b/kornia/models/yunet/processors.py@@ -28,12 +28,14 @@ def decode(loc: torch.Tensor, priors: torch.Tensor, variances: List[float]) -> t"""Decode locations from predictions using priors to undo the encoding for offset regression at train time.Args:- loc: location predictions for loc layers. Shape: [num_priors,4].+ loc: location predictions for loc layers: the box offsets and five landmark offsets.+ Shape: [num_priors,14].priors: Prior boxes in center-offset form. Shape: [num_priors,4].variances: (list[float]) Variances of priorboxes.Return:- torch.Tensor containing decoded bounding box predictions.+ torch.Tensor containing the decoded box ``xmin, ymin, xmax, ymax`` and the five ``(x, y)`` landmarks, in the+ normalized coordinates of the priors. Shape: [num_priors,14]."""boxes = torch.cat(diff --git a/tests/contrib/test_edge_detector.py b/tests/contrib/test_edge_detector.pyindex 539d1dec7..927b67434 100644--- a/tests/contrib/test_edge_detector.py+++ b/tests/contrib/test_edge_detector.py@@ -19,11 +19,69 @@ import pytestimport torchimport kornia+from kornia.contrib.edge_detection import EdgeDetectorBuilder+from kornia.models.dexined import DexiNedfrom testing.base import BaseTesterclass TestEdgeDetector(BaseTester):+ def test_builder_feeds_dexined_bgr_minus_bgr_mean(self, device, dtype):+ # DexiNed was trained on ``cv2.imread`` images (BGR, 0-255) minus ``mean_bgr``: xavysp/DexiNed@d944b70+ # datasets.py:255, 300, with ``--mean_pixel_values`` [103.939, 116.779, 123.68] in B, G, R order+ # (main.py:319-320).+ # A 64 px network input keeps the random DexiNed fast in half precision on the CPU.+ det = EdgeDetectorBuilder.build(pretrained=False, image_size=64).to(device, dtype)+ # DexiNed stays at ``model[1]``, so the state-dict keys of a saved ``EdgeDetector`` stay ``model.1.*``.+ assert isinstance(det.model[1], DexiNed)+ dexined = next(m for m in det.model.modules() if isinstance(m, DexiNed))++ captured = {}++ def capture(name):+ def hook(module, args):+ captured[name] = args[0].clone()++ return hook++ handles = [+ det.model.register_forward_pre_hook(capture("seq_in")),+ dexined.register_forward_pre_hook(capture("dexined_in")),+ ]+ try:+ det(torch.rand(1, 3, 64, 96, device=device, dtype=dtype))+ finally:+ for handle in handles:+ handle.remove()++ # Compared in float64 on the CPU (MPS has no float64).+ seq_in = captured["seq_in"].cpu().double() # the resized RGB image in [0, 1]+ mean_bgr = torch.tensor([103.939, 116.779, 123.68], dtype=torch.float64).view(1, 3, 1, 1)+ expected = 255 * seq_in.flip(1) - mean_bgr+ # Normalize computes ``(x - m / 255) / (1 / 255)`` in ``dtype`` from float32 statistics: about four roundings,+ # each up to half an ulp of the coarser of ``dtype`` and float32 on the 0-255 scale, so 4 * 255 * eps bounds+ # the error (bfloat16: 8.0, below the 19.7 between the R and B means that a mean in the wrong order leaves).+ atol = 4 * 255 * max(torch.finfo(dtype).eps, torch.finfo(torch.float32).eps)+ self.assert_close(captured["dexined_in"].cpu().double(), expected, rtol=0.0, atol=atol)++ @pytest.mark.device_agnostic+ def test_edge_detector_onnx_matches_eager(self):+ pytest.importorskip("onnx")+ ort = pytest.importorskip("onnxruntime")+ pytest.importorskip("onnxscript")++ det = EdgeDetectorBuilder.build(pretrained=False)+ # ``image_size=None`` exports ``det.model`` (the BGR step, DexiNed and the sigmoid) with a dynamic batch,+ # height and width.+ op = det.to_onnx(image_size=None, include_pre_and_post_processor=False, save=False)+ session = ort.InferenceSession(op.SerializeToString(), providers=["CPUExecutionProvider"])++ img = torch.rand(2, 3, 64, 96)+ exported = torch.from_numpy(session.run(None, {session.get_inputs()[0].name: img.numpy()})[0])+ with torch.no_grad():+ eager = det.model(img)+ self.assert_close(exported, eager, rtol=0.0, atol=1e-4)+@pytest.mark.slowdef test_smoke(self, device, dtype):img = torch.rand(2, 3, 64, 64, device=device, dtype=dtype)diff --git a/tests/contrib/test_face_detection.py b/tests/contrib/test_face_detection.pyindex a28b39c42..b0342224f 100644--- a/tests/contrib/test_face_detection.py+++ b/tests/contrib/test_face_detection.py@@ -121,9 +121,40 @@ class TestFaceDetection(BaseTester):def test_exception(self, face_detector, device, dtype):img = torch.rand(1, 4, 320, 320, device=device, dtype=dtype)- with pytest.raises(RuntimeError):+ with pytest.raises(ValueError, match=r"\(\*, 3, H, W\)"):face_detector(img)+ def test_preprocess_checks_the_channels(self, face_detector, device, dtype):+ # ``preprocess`` flips RGB to BGR with ``rgb_to_bgr``, which checks for ``(*, 3, H, W)``. A plain ``flip(-3)``+ # would accept these and leave the error to YuNet, or flip the height of a channels-last image.+ for shape in ((1, 4, 64, 96), (1, 1, 64, 96), (1, 64, 96, 3)):+ with pytest.raises(ValueError, match=r"\(\*, 3, H, W\)"):+ face_detector.preprocess(torch.rand(*shape, device=device, dtype=dtype) * 255)++ def test_yunet_receives_bgr_0_255(self, face_detector, device, dtype):+ # The YuNet weights were trained on BGR, float 0-255, with no mean or std: the DALI loader converts to BGR and+ # resizes to float (ShiqiYu/libfacedetection.train@74f3aa7 src/data.py:76, 90), and evaluation reads+ # ``cv2.imread`` images (tasks/task1/datasets.py:53, detect.py:100-106).+ # ``FaceDetector`` takes RGB in [0, 255] and only flips the channels.+ captured = []+ handle = face_detector.model.register_forward_pre_hook(lambda module, args: captured.append(args[0].clone()))+ img = torch.rand(1, 3, 64, 96, device=device, dtype=dtype) * 255+ try:+ face_detector(img)+ finally:+ handle.remove()++ assert len(captured) == 1+ assert torch.equal(captured[0], img.flip(-3))+ assert torch.equal(face_detector.preprocess(img), img.flip(-3))++ def test_result_checks_the_last_dimension(self, device, dtype):+ # A row holds 15 values: the box (4), five (x, y) landmarks (10) and the score (1).+ kornia.contrib.FaceDetectorResult(torch.rand(15, device=device, dtype=dtype))+ kornia.contrib.FaceDetectorResult(torch.rand(3, 15, device=device, dtype=dtype))+ with pytest.raises(ValueError, match="15"):+ kornia.contrib.FaceDetectorResult(torch.rand(20, 14, device=device, dtype=dtype))+@pytest.mark.slowdef test_dynamo(self, face_detector, device, dtype, torch_optimizer):torch.manual_seed(44)diff --git a/tests/models/test_dexined.py b/tests/models/test_dexined.pyindex 2f9ce23be..ef701a81e 100644--- a/tests/models/test_dexined.py+++ b/tests/models/test_dexined.py@@ -56,6 +56,34 @@ class TestDexiNed(BaseTester):out = model(img)self.assert_close(out, expect, atol=1e-3, rtol=1e-2)+ @pytest.mark.parametrize("cls", [DexiNed, FilterDexiNed], ids=["models", "filters"])+ def test_backward(self, cls, device, dtype):+ net = cls(pretrained=False).to(device, dtype)+ # The in-place error does not depend on the size. At 24x36 the smallest training-mode BatchNorm maps are 2x3.+ # 16x24 reaches 1x2, where BatchNorm normalises two values and the float16 input gradient overflows for some+ # seeds; 8x12 reaches 1x1, which raises.+ img = torch.rand(1, 3, 24, 36, device=device, dtype=dtype, requires_grad=True)+ net(img).sum().backward()+ assert img.grad is not None+ assert torch.isfinite(img.grad).all()++ # Evaluation mode with frozen weights: the gradient with respect to the input only.+ net.eval().requires_grad_(False)+ img = torch.rand(1, 3, 24, 36, device=device, dtype=dtype, requires_grad=True)+ net(img).sum().backward()+ assert img.grad is not None+ assert torch.isfinite(img.grad).all()++ @pytest.mark.slow+ @pytest.mark.parametrize("cls", [DexiNed, FilterDexiNed], ids=["models", "filters"])+ def test_gradcheck(self, cls, device):+ # A full gradcheck: fast mode checks one random projection of the Jacobian and passes a dense layer whose input+ # is detached from the graph. 8x12 keeps it to about 16 s per class; in evaluation mode BatchNorm accepts the+ # 1x1 deepest maps.+ net = cls(pretrained=False).to(device, torch.float64).eval()+ img = torch.rand(1, 3, 8, 12, device=device, dtype=torch.float64)+ self.gradcheck(net, (img,), fast_mode=False)+@pytest.mark.skip(reason="DexiNed do not compile with dynamo.")def test_dynamo(self, device, dtype, torch_optimizer): ...