Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Accept transposed video batches in Bayer demosaicing (#5804)

Anton Solovieveca255af36cc
diff --git a/changelog.d/5804.fixed.md b/changelog.d/5804.fixed.md
new file mode 100644
index 000000000..90ab44426
--- /dev/null
+++ b/changelog.d/5804.fixed.md
@@ -0,0 +1 @@
+`raw_to_rgb` now accepts non-contiguous leading batch dimensions, including video tensors with transposed batch and time axes.
diff --git a/kornia/color/raw.py b/kornia/color/raw.py
index 06abdaaf4..5ef8e5497 100644
--- a/kornia/color/raw.py
+++ b/kornia/color/raw.py
@@ -87,7 +87,7 @@ def raw_to_rgb(image: torch.Tensor, cfa: CFA) -> torch.Tensor:
imagesize = image.size()
- image = image.view(-1, 1, image.shape[-2], image.shape[-1])
+ image = image.reshape(-1, 1, image.shape[-2], image.shape[-1])
# BG is defined as pel 1,1 being blue, that is the top left is actually green. This matches
# opencv naming so makes sense to keep
diff --git a/tests/color/test_raw.py b/tests/color/test_raw.py
index 001d52011..9041aec58 100644
--- a/tests/color/test_raw.py
+++ b/tests/color/test_raw.py
@@ -65,6 +65,26 @@ class TestRawToRgb(BaseTester):
with pytest.raises(ValueError):
assert kornia.color.raw_to_rgb(img, kornia.color.CFA.GR)
+ @pytest.mark.parametrize("cfa", list(kornia.color.CFA))
+ def test_transposed_batch(self, device, dtype, cfa):
+ image = torch.rand(2, 3, 1, 4, 6, device=device, dtype=dtype).transpose(0, 1)
+ assert not image.is_contiguous()
+ expected = torch.stack(
+ [torch.stack([kornia.color.raw_to_rgb(frame, cfa) for frame in batch]) for batch in image]
+ )
+ actual = kornia.color.raw_to_rgb(image, cfa)
+ self.assert_close(actual, expected)
+ self.assert_close(kornia.color.rgb_to_raw(actual, cfa), image)
+
+ def test_transposed_batch_gradcheck(self, device):
+ image = torch.rand(2, 2, 1, 2, 2, device=device, dtype=torch.float64, requires_grad=True)
+ self.gradcheck(lambda x: kornia.color.raw_to_rgb(x.transpose(0, 1), kornia.color.CFA.BG), (image,))
+
+ def test_transposed_batch_dynamo(self, device, dtype, torch_optimizer):
+ image = torch.rand(2, 3, 1, 4, 6, device=device, dtype=dtype).transpose(0, 1)
+ op = kornia.color.raw_to_rgb
+ self.assert_close(torch_optimizer(op)(image, kornia.color.CFA.BG), op(image, kornia.color.CFA.BG))
+
# With he current implementations we should get back an identical raw representation when doing raw -> rgb -> raw
# Note that with more advanced implementations this may not necessarily be true or desirable
def test_forth_and_back(self, device, dtype): # skipcq: PYL-R0201