Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

perf(color): subsample yuv420 chroma with avg_pool2d (#4548)

Dipak Chaudhari1ecf9a18bd88
diff --git a/changelog.d/4548.fixed.md b/changelog.d/4548.fixed.md
new file mode 100644
index 000000000..0da35a8e8
--- /dev/null
+++ b/changelog.d/4548.fixed.md
@@ -0,0 +1 @@
+`kornia.color.rgb_to_yuv420` subsamples chroma with `avg_pool2d` instead of a mean over two unfolded window dimensions: same values, several times faster on CPU and MPS.
diff --git a/kornia/color/yuv.py b/kornia/color/yuv.py
index bb7166d9c..df936c6c0 100644
--- a/kornia/color/yuv.py
+++ b/kornia/color/yuv.py
@@ -20,6 +20,7 @@ from __future__ import annotations
from typing import ClassVar
import torch
+import torch.nn.functional as F
from torch import nn
from kornia.color.utils import _apply_linear_transformation
@@ -101,10 +102,17 @@ def rgb_to_yuv420(image: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
yuvimage = rgb_to_yuv(image)
- return (
- yuvimage[..., :1, :, :],
- yuvimage[..., 1:3, :, :].unfold(-2, 2, 2).unfold(-2, 2, 2).mean((-1, -2)),
- )
+ # A 2x2 box mean. avg_pool2d computes it directly; a mean over two unfolded window
+ # dims gives the same values but is several times slower, most of all on MPS.
+ uv = yuvimage[..., 1:3, :, :]
+ leading = list(uv.shape[:-3])
+ batch = 1
+ for size in leading:
+ batch *= size
+ height, width = uv.shape[-2], uv.shape[-1]
+ uv = F.avg_pool2d(uv.reshape([batch, 2, height, width]), 2)
+
+ return yuvimage[..., :1, :, :], uv.reshape(leading + [2, height // 2, width // 2])
def rgb_to_yuv422(image: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
diff --git a/tests/color/test_yuv.py b/tests/color/test_yuv.py
index 1d4a2b621..935b9f6b2 100644
--- a/tests/color/test_yuv.py
+++ b/tests/color/test_yuv.py
@@ -394,7 +394,7 @@ class TestRgbToYuv420(BaseTester):
# Four different colours inside each 2x2 cell, and two cells that must not be mixed, so
# the chroma of a cell pins the whole box average rather than any one of its pixels. The
# expected chroma is averaged with an explicit reshape, which does not share the
- # library's ``unfold`` grouping, so a wrong axis, stride or cell boundary shows up here.
+ # library's pooling, so a wrong axis, stride or cell boundary shows up here.
# Both cells are chosen to have non-zero chroma -- with ``blue, white / red, green`` the
# second cell box-averages to (0, 0), where a scale, sign flip or U/V swap confined to
# that cell would map 0 to 0 and pass.
@@ -411,6 +411,19 @@ class TestRgbToYuv420(BaseTester):
# The two cells really do differ, so the assertion above has something to discriminate.
assert not torch.allclose(uv[:, :, 0], uv[:, :, 1])
+ def test_leading_dims_match_per_image(self, device, dtype):
+ # The chroma is pooled over the leading dims folded into one batch; each image must
+ # come back in its own position, matching a call on that image alone.
+ img = _seeded_rand(2, 3, 3, 4, 6, seed=4524).to(device=device, dtype=dtype)
+
+ y, uv = kornia.color.rgb_to_yuv420(img)
+
+ for i in range(img.shape[0]):
+ for j in range(img.shape[1]):
+ y_ij, uv_ij = kornia.color.rgb_to_yuv420(img[i, j])
+ self.assert_close(y[i, j], y_ij)
+ self.assert_close(uv[i, j], uv_ij)
+
def test_forth_and_back(self, device, dtype):
# 2x2-constant input, so the chroma subsample-then-upsample is lossless and what is
# measured is the colour transform.