Repository: Project-MONAI/MONAI

Issue:
Add ToNumpy transform to support 3rd party transforms
**Is your feature request related to a problem? Please describe.**
As we already have `ToTensor` transform to connect other 3rd party transforms that work for Tensor data only, we also need the `ToNumpy` transform to convert back to numpy.



Discussion:

Resolving patch:
diff --git a/monai/transforms/utility/array.py b/monai/transforms/utility/array.py
--- a/monai/transforms/utility/array.py
+++ b/monai/transforms/utility/array.py
@@ -134,6 +134,17 @@ def __call__(self, img):
         return torch.as_tensor(np.ascontiguousarray(img))
 
 
+class ToNumpy(Transform):
+    """
+    Converts the input Tensor data to numpy array.
+    """
+
+    def __call__(self, img):
+        if torch.is_tensor(img):
+            img = img.detach().cpu().numpy()
+        return np.ascontiguousarray(img)
+
+
 class Transpose(Transform):
     """
     Transposes the input image based on the given `indices` dimension ordering.
diff --git a/monai/transforms/utility/dictionary.py b/monai/transforms/utility/dictionary.py
--- a/monai/transforms/utility/dictionary.py
+++ b/monai/transforms/utility/dictionary.py
@@ -26,6 +26,7 @@
     AddChannel,
     AsChannelFirst,
     ToTensor,
+    ToNumpy,
     AsChannelLast,
     CastToType,
     RepeatChannel,
@@ -165,6 +166,27 @@ def __call__(self, data):
         return d
 
 
+class ToNumpyd(MapTransform):
+    """
+    Dictionary-based wrapper of :py:class:`monai.transforms.ToNumpy`.
+    """
+
+    def __init__(self, keys: Hashable):
+        """
+        Args:
+            keys (hashable items): keys of the corresponding items to be transformed.
+                See also: :py:class:`monai.transforms.compose.MapTransform`
+        """
+        super().__init__(keys)
+        self.converter = ToNumpy()
+
+    def __call__(self, data):
+        d = dict(data)
+        for key in self.keys:
+            d[key] = self.converter(d[key])
+        return d
+
+
 class DeleteKeysd(MapTransform):
     """
     Delete specified keys from data dictionary to release memory.


Test patch:
diff --git a/tests/test_to_numpy.py b/tests/test_to_numpy.py
new file mode 100644
--- /dev/null
+++ b/tests/test_to_numpy.py
@@ -0,0 +1,39 @@
+# Copyright 2020 MONAI Consortium
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#     http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import unittest
+import torch
+import numpy as np
+from monai.transforms import ToNumpy
+
+
+class TestToNumpy(unittest.TestCase):
+    def test_numpy_input(self):
+        test_data = np.array([[1, 2], [3, 4]])
+        test_data = np.rot90(test_data)
+        self.assertFalse(test_data.flags["C_CONTIGUOUS"])
+        result = ToNumpy()(test_data)
+        self.assertTrue(isinstance(result, np.ndarray))
+        self.assertTrue(result.flags["C_CONTIGUOUS"])
+        np.testing.assert_allclose(result, test_data)
+
+    def test_tensor_input(self):
+        test_data = torch.tensor([[1, 2], [3, 4]])
+        test_data = test_data.rot90()
+        self.assertFalse(test_data.is_contiguous())
+        result = ToNumpy()(test_data)
+        self.assertTrue(isinstance(result, np.ndarray))
+        self.assertTrue(result.flags["C_CONTIGUOUS"])
+        np.testing.assert_allclose(result, test_data.numpy())
+
+
+if __name__ == "__main__":
+    unittest.main()
diff --git a/tests/test_to_numpyd.py b/tests/test_to_numpyd.py
new file mode 100644
--- /dev/null
+++ b/tests/test_to_numpyd.py
@@ -0,0 +1,39 @@
+# Copyright 2020 MONAI Consortium
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#     http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import unittest
+import torch
+import numpy as np
+from monai.transforms import ToNumpyd
+
+
+class TestToNumpyd(unittest.TestCase):
+    def test_numpy_input(self):
+        test_data = np.array([[1, 2], [3, 4]])
+        test_data = np.rot90(test_data)
+        self.assertFalse(test_data.flags["C_CONTIGUOUS"])
+        result = ToNumpyd(keys="img")({"img": test_data})["img"]
+        self.assertTrue(isinstance(result, np.ndarray))
+        self.assertTrue(result.flags["C_CONTIGUOUS"])
+        np.testing.assert_allclose(result, test_data)
+
+    def test_tensor_input(self):
+        test_data = torch.tensor([[1, 2], [3, 4]])
+        test_data = test_data.rot90()
+        self.assertFalse(test_data.is_contiguous())
+        result = ToNumpyd(keys="img")({"img": test_data})["img"]
+        self.assertTrue(isinstance(result, np.ndarray))
+        self.assertTrue(result.flags["C_CONTIGUOUS"])
+        np.testing.assert_allclose(result, test_data.numpy())
+
+
+if __name__ == "__main__":
+    unittest.main()