Repository: Project-MONAI/MONAI

Issue:
About ValueError: Unsupported output type: <class 'itk.itkPyBufferPython.NDArrayITKBase'>  that occurs when transforms compose 
## Problem Description 

Hi,I am a novice to MONAI, and An error occurred when I set up pre-processing transforms,
my image format is dicom.
My development platform is windows10, but my test on ubuntu20.04 is no problem.
I don't know how to solve it, hope to get your help, thank you 

The following is information about the code and error 

> MONAI version: 0.7.dev2135
   Numpy version: 1.21.1
Pytorch version: 1.7.1+cu101
MONAI flags: HAS_EXT = False, USE_COMPILED = False
MONAI rev id: fc69e1d96c6250c6479ea7575b9e6f73e70b8baf
Optional dependencies:
Pytorch Ignite version: 0.4.5
Nibabel version: 3.2.1
scikit-image version: 0.18.3
Pillow version: 8.0.1
Tensorboard version: 2.6.0
gdown version: 3.13.0
TorchVision version: 0.8.2+cu101
tqdm version: 4.62.2
lmdb version: 1.2.1
psutil version: 5.8.0
pandas version: 1.3.2
einops version: 0.3.2
For details about installing the optional dependencies, please visit:
    https://docs.monai.io/en/latest/installation.html#installing-the-recommended-dependencies

```python
transform = Compose([
    LoadImaged(keys="image"),
    SqueezeDimd(keys="image", dim=-1),
    AddChanneld(keys="image"),
    ScaleIntensityd("image"),
    CropForegroundd(keys="image", source_key="image"),
    EnsureTyped(keys="image"),
])

test_data = {"image": newdcmDir}
print(f"filename:{newdcmDir}")
result = transform(test_data)
#print(f"image data shape:{result['image'].shape}")
#print(f"meta data:{result['image_meta_dict']}")
```

=== Transform input info -- ScaleIntensityd ===

=== Transform input info -- ScaleIntensityd ===

=== Transform input info -- ScaleIntensityd ===

=== Transform input info -- ScaleIntensityd ===

=== Transform input info -- ScaleIntensityd ===

=== Transform input info -- ScaleIntensityd ===

=== Transform input info -- ScaleIntensityd ===

=== Transform input info -- ScaleIntensityd ===

=== Transform input info -- ScaleIntensityd ===

=== Transform input info -- ScaleIntensityd ===
image statistics:
Type: <class 'itk.itkPyBufferPython.NDArrayITKBase'>
Shape: (1, 1024, 1024)
Value range: (0.0, 4091.0)
show more (open the raw output data in a text editor) ...
       [ 0.,  0.,  1.,  0.],
       [ 0.,  0.,  0.,  1.]]), 'affine': array([[-1.,  0.,  0.,  0.],
       [ 0., -1.,  0.,  0.],
       [ 0.,  0.,  1.,  0.],
       [ 0.,  0.,  0.,  1.]]), 'spatial_shape': array([1024, 1024,    1]), 'original_channel_dim': 'no_channel', 'filename_or_obj': 'C:/Users/Bxd/remote/data_circle/data/imagesTest/1.IMA'}

 RuntimeError: applying transform <monai.transforms.intensity.dictionary.ScaleIntensityd object at 0x00000285C81DD910>
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~\AppData\Local\Programs\Python\Python39\lib\site-packages\monai\transforms\transform.py in apply_transform(transform, data, map_items, unpack_items)
     91             return [_apply_transform(transform, item, unpack_items) for item in data]
---> 92         return _apply_transform(transform, data, unpack_items)
     93     except Exception as e:

~\AppData\Local\Programs\Python\Python39\lib\site-packages\monai\transforms\transform.py in _apply_transform(transform, parameters, unpack_parameters)
     59 
---> 60     return transform(parameters)
     61 

~\AppData\Local\Programs\Python\Python39\lib\site-packages\monai\transforms\intensity\dictionary.py in __call__(self, data)
    505         for key in self.key_iterator(d):
--> 506             d[key] = self.scaler(d[key])
    507         return d

~\AppData\Local\Programs\Python\Python39\lib\site-packages\monai\transforms\intensity\array.py in __call__(self, img)
    402         if self.minv is not None and self.maxv is not None:
--> 403             return rescale_array(img, self.minv, self.maxv, img.dtype)
    404         if self.factor is not None:

~\AppData\Local\Programs\Python\Python39\lib\site-packages\monai\transforms\utils.py in rescale_array(arr, minv, maxv, dtype)
    143     if dtype is not None:
--> 144         arr, *_ = convert_data_type(arr, dtype=dtype)
    145 

~\AppData\Local\Programs\Python\Python39\lib\site-packages\monai\utils\type_conversion.py in convert_data_type(data, output_type, device, dtype)
    186     else:
--> 187         raise ValueError(f"Unsupported output type: {output_type}")
    188     return data, orig_type, orig_device

ValueError: Unsupported output type: <class 'itk.itkPyBufferPython.NDArrayITKBase'>

The above exception was the direct cause of the following exception:

RuntimeError                              Traceback (most recent call last)
<ipython-input-18-2f84588052ad> in <module>
     10 test_data = {"image": newdcmDir}
     11 print(f"filename:{newdcmDir}")
---> 12 result = transform(test_data)
     13 #print(f"image data shape:{result['image'].shape}")
     14 #print(f"meta data:{result['image_meta_dict']}")

~\AppData\Local\Programs\Python\Python39\lib\site-packages\monai\transforms\compose.py in __call__(self, input_)
    158     def __call__(self, input_):
    159         for _transform in self.transforms:
--> 160             input_ = apply_transform(_transform, input_, self.map_items, self.unpack_items)
    161         return input_
    162 

~\AppData\Local\Programs\Python\Python39\lib\site-packages\monai\transforms\transform.py in apply_transform(transform, data, map_items, unpack_items)
    114             else:
    115                 _log_stats(data=data)
--> 116         raise RuntimeError(f"applying transform {transform}") from e
    117 
    118 

RuntimeError: applying transform <monai.transforms.intensity.dictionary.ScaleIntensityd object at 0x00000285C81DD910>


Discussion:

Resolving patch:
diff --git a/monai/utils/type_conversion.py b/monai/utils/type_conversion.py
--- a/monai/utils/type_conversion.py
+++ b/monai/utils/type_conversion.py
@@ -171,7 +171,14 @@ def convert_data_type(
     Returns:
         modified data, orig_type, orig_device
     """
-    orig_type = type(data)
+    orig_type: Any
+    if isinstance(data, torch.Tensor):
+        orig_type = torch.Tensor
+    elif isinstance(data, np.ndarray):
+        orig_type = np.ndarray
+    else:
+        orig_type = type(data)
+
     orig_device = data.device if isinstance(data, torch.Tensor) else None
 
     output_type = output_type or orig_type


Test patch: