π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fix NumPy annotation conversion in AugmentationSequential (#5274)
Karnajeet Gosavi81f749549d8c
diff --git a/changelog.d/5239.fixed.md b/changelog.d/5239.fixed.mdindex ba77b72e1..433e18b92 100644--- a/changelog.d/5239.fixed.md+++ b/changelog.d/5239.fixed.md@@ -11,5 +11,4 @@ and `save()` clamp a float image to `[0, 1]` and round it to 8 bits on the CPU,image was multiplied by 255 (200 became 56). A negative value now gives 0 on every torch version anda `uint8` image keeps its values. In-range float pixels change by at most one step, from truncationto rounding (0.999 now gives 255 instead of 254). `show()` renders bfloat16 outputs, which used to-raise `TypeError: Got unsupported ScalarType BFloat16`. Non-image NumPy arguments of-`AugmentationSequential` (masks, boxes) are still converted with the image rule: #5236.+raise `TypeError: Got unsupported ScalarType BFloat16`.diff --git a/changelog.d/5274.breaking.md b/changelog.d/5274.breaking.mdnew file mode 100644index 000000000..17988ce14--- /dev/null+++ b/changelog.d/5274.breaking.md@@ -0,0 +1,6 @@+`AugmentationSequential` converts each NumPy argument by its data key, and only `input` takes the image conversion.+A NumPy mask keeps its dtype and values: an `int64` label 3 used to come out as `float32` 3 / 255, and a `uint8`+0/255 binary mask as `float32` 0/1; they now come out as `int64` 3 and `uint8` 0/255, as the same mask passed as a+tensor does. A NumPy mask is still read like a NumPy image, `(H, W)`, `(H, W, C)` or `(B, H, W, C)`. NumPy boxes,+keypoints and class labels, which went through the image conversion and raised, now convert like their tensors, and+a dictionary input with NumPy values, which raised `AttributeError`, converts too. (#5236)diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex b964d5a71..3beab1c14 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -26,10 +26,12 @@ from kornia.augmentation._3d.base import AugmentationBase3D, RigidAffineAugmentafrom kornia.augmentation.base import _AugmentationBasefrom kornia.augmentation.utils.helpers import _boxes_to_padded_tensorfrom kornia.constants import DataKey, Resample+from kornia.core.external import numpy as npfrom kornia.core.ops import eye_likefrom kornia.core.utils import is_autocast_enabled, is_exportingfrom kornia.geometry.boxes import Boxes, VideoBoxesfrom kornia.geometry.keypoints import Keypoints, VideoKeypoints+from kornia.image.utils import image_to_tensorfrom .base import TransformMatrixMinInfrom .image import ImageSequential@@ -643,6 +645,23 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):"""# Wrap the forward method with the decoratorif not self._disable_features:+ converted_inputs = inputs+ if len(inputs) == 1 and isinstance(inputs[0], dict):+ keys, data_keys, args, _ = self._preproc_dict_data(inputs[0])+ converted_dict = dict(inputs[0])+ for key, arg, data_key in zip(keys, args, data_keys):+ if isinstance(arg, np.ndarray):+ if data_key in _IMG_OPTIONS:+ converted_dict[key] = self.to_tensor(arg)+ else:+ converted_dict[key] = self._convert_numpy_non_image(arg, data_key)+ converted_inputs = (converted_dict,)+ else:+ data_keys = self.transform_op.preproc_datakeys(kwargs.get("data_keys", self.data_keys))+ # Arguments beyond the data keys pass through unconverted, so ``forward`` still rejects the count.+ converted_inputs = tuple(+ self._convert_numpy_non_image(arg, data_key) for arg, data_key in zip(inputs, data_keys)+ ) + tuple(inputs[len(data_keys) :])# TODO: Some more behaviour for AugmentationSequential needs to be revisited later# e.g. We convert only images, etc.self._check_output_type(output_type)@@ -651,7 +670,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):decorated_forward = self.convert_input_output(input_names_to_handle=input_names_to_handle)(super(ImageSequential, self).__call__)- tensor_output = decorated_forward(*inputs, **kwargs)+ tensor_output = decorated_forward(*converted_inputs, **kwargs)in_data_keys: Optional[List[DataKey]]original_keys: Optional[Tuple[str, ...]] = None@@ -671,6 +690,14 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):_output_image = super(ImageSequential, self).__call__(*inputs, **kwargs)return _output_image+ @staticmethod+ def _convert_numpy_non_image(arg: Any, data_key: DataKey) -> Any:+ if not isinstance(arg, np.ndarray) or data_key in _IMG_OPTIONS:+ return arg+ if data_key in _MSK_OPTIONS:+ return image_to_tensor(arg)+ return torch.as_tensor(arg)+def _select_output_image(self, output: Any, data_keys: List[DataKey], original_keys: Optional[Tuple[str, ...]]) -> Any:diff --git a/testing/half_precision_eager_rng.py b/testing/half_precision_eager_rng.pyindex bb3c2f471..2de26fd37 100644--- a/testing/half_precision_eager_rng.py+++ b/testing/half_precision_eager_rng.py@@ -149,7 +149,7 @@ AUDITED_EAGER_RNG_CALLS = tuple((*_audited("tests/augmentation/container/test_augmentation_sequential.py",- 49,+ 71,"torch.randn",2,(diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.pyindex c4426b587..44f132920 100644--- a/tests/augmentation/container/test_augmentation_sequential.py+++ b/tests/augmentation/container/test_augmentation_sequential.py@@ -18,6 +18,7 @@from functools import partialfrom unittest.mock import patch+import numpy as npimport pytestimport torch@@ -35,6 +36,27 @@ from testing.base import BaseTester, assert_closeclass TestAugmentationSequential:+ @pytest.mark.parametrize("as_dict", [False, True])+ def test_numpy_annotations_are_not_scaled_like_images(self, as_dict):+ image = np.zeros((8, 9, 3), dtype=np.uint8)+ mask = np.zeros((8, 9), dtype=np.int64)+ mask[2:5, 3:6] = 3+ boxes = np.array([[[3.0, 2.0, 6.0, 5.0]]], dtype=np.float32)+ keypoints = np.array([[[4.0, 3.0]]], dtype=np.float32)+ data_keys = ["input", "mask", "bbox_xyxy", "keypoints"]+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=0.0), data_keys=None if as_dict else data_keys)++ if as_dict:+ output = aug(dict(zip(data_keys, (image, mask, boxes, keypoints))))+ out_mask, out_boxes, out_keypoints = output["mask"], output["bbox_xyxy"], output["keypoints"]+ else:+ _, out_mask, out_boxes, out_keypoints = aug(image, mask, boxes, keypoints)++ assert out_mask.dtype == torch.int64+ assert set(out_mask.unique().tolist()) == {0, 3}+ assert torch.equal(out_boxes, torch.from_numpy(boxes))+ assert torch.equal(out_keypoints, torch.from_numpy(keypoints))+@pytest.mark.parametrize("data_keys", ["input", "image", ["mask", "input"], ["input", "bbox_yxyx"], [0, 10], [BorderType.REFLECT]])@@ -1278,6 +1300,26 @@ class TestConventionAugmentationSequential(BaseTester):assert keys == [DataKey.BBOX, DataKey.BBOX, DataKey.LABEL, DataKey.LABEL, DataKey.LABEL, DataKey.LABEL]assert metadata == []+ def test_numpy_mask_is_read_channels_last_without_scaling_5236(self):+ # A NumPy mask is laid out like a NumPy image, (H, W) or (H, W, C), and keeps its labels: an (8, 9, 1) mask+ # becomes (1, 1, 8, 9) and flips with the image. The label block sits off the flip axis (columns 1-2 go to+ # 6-7), and a mask read as (C, H, W) = (8, 9, 1) would come back with another shape.+ image = np.zeros((8, 9, 3), dtype=np.uint8)+ mask = np.zeros((8, 9, 1), dtype=np.int64)+ mask[2:5, 1:3] = 3+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])+ _, out_mask = aug(image, mask)+ expected = torch.zeros(1, 1, 8, 9, dtype=torch.int64)+ expected[..., 2:5, 6:8] = 3+ assert torch.equal(out_mask, expected)++ def test_argument_without_a_data_key_raises(self):+ # ``__call__`` converts NumPy arguments by data key; an argument with no key must still reach ``forward``,+ # which rejects the count, instead of being dropped.+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input"])+ with pytest.raises(AssertionError, match="number of inputs must align"):+ aug(torch.zeros(1, 3, 8, 9), torch.zeros(1, 1, 8, 9))+def test_convention_same_on_batch_none_does_not_override_a_child(self, device, dtype):# Convention pin: `AugmentationSequential(same_on_batch=None)` - the default - keeps whatever each# child was built with, while `True` and `False` overwrite the child's own setting in both directions.