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:
Nic-Ma: /black

Patch:
diff --git a/docs/source/transforms.rst b/docs/source/transforms.rst
index b6e0190f..f4e02b01 100644
--- a/docs/source/transforms.rst
+++ b/docs/source/transforms.rst
@@ -97,6 +97,12 @@ Vanilla Transforms
     :members:
     :special-members: __call__
 
+`ToNumpy`
+~~~~~~~~~
+.. autoclass:: ToNumpy
+    :members:
+    :special-members: __call__
+
 `Transpose`
 ~~~~~~~~~~~
 .. autoclass:: Transpose
@@ -395,6 +401,12 @@ Dictionary-based Transforms
     :members:
     :special-members: __call__
 
+`ToNumpyd`
+~~~~~~~~~~
+.. autoclass:: ToNumpyd
+    :members:
+    :special-members: __call__
+
 `Rotate90d`
 ~~~~~~~~~~~
 .. autoclass:: Rotate90d
diff --git a/monai/transforms/utility/array.py b/monai/transforms/utility/array.py
index 1de1c6d6..b11154c6 100644
--- a/monai/transforms/utility/array.py
+++ b/monai/transforms/utility/array.py
@@ -134,6 +134,17 @@ class ToTensor(Transform):
         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
index aa942d1c..dd7bae4a 100644
--- a/monai/transforms/utility/dictionary.py
+++ b/monai/transforms/utility/dictionary.py
@@ -26,6 +26,7 @@ from monai.transforms.utility.array import (
     AddChannel,
     AsChannelFirst,
     ToTensor,
+    ToNumpy,
     AsChannelLast,
     CastToType,
     RepeatChannel,
@@ -165,6 +166,27 @@ class ToTensord(MapTransform):
         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
index 00000000..fa41ac2b
--- /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
index 00000000..c9bb4039
--- /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()