Repository: pydicom/pydicom

Issue:
Error decoding dataset with ambiguous VR element when the value is None
Hi all,
    I used the storescu in pynetdicom 1.5.3 to send the dicom ct files(both on mac and ubuntu): 
**python storescu.py 192.168.1.120 9002 ~/Downloads/test/**
(I also tried https://pydicom.github.io/pynetdicom/stable/examples/storage.html#storage-scu)
but it throwed errors: 

_E: Failed to encode the supplied Dataset
E: Store failed: /Users/me/Downloads/test/CT_S1_118.dcm
E: Failed to encode the supplied Dataset
Traceback (most recent call last):
  File "storescu.py", line 283, in main
    status = assoc.send_c_store(ds, ii)
  File "/Users/me/.pyenv/versions/3.8.2/lib/python3.8/site-packages/pynetdicom/association.py", line 1736, in send_c_store
    raise ValueError('Failed to encode the supplied Dataset')
ValueError: Failed to encode the supplied Dataset_

But I used to send same files with storescu in dcm4che successfully.
File attached.

[test.zip](https://github.com/pydicom/pynetdicom/files/5258867/test.zip)


Discussion:
pep8speaks: Hello @scaramallion! Thanks for opening this PR. We checked the lines you've touched for [PEP 8](https://www.python.org/dev/peps/pep-0008) issues, and found:



* In the file [`pydicom/tests/test_filewriter.py`](https://github.com/pydicom/pydicom/blob/f55d192c7b1893d5f67ac4aececf230d8c71da26/pydicom/tests/test_filewriter.py):

> [Line 1098:9](https://github.com/pydicom/pydicom/blob/f55d192c7b1893d5f67ac4aececf230d8c71da26/pydicom/tests/test_filewriter.py#L1098): [E265](https://duckduckgo.com/?q=pep8%20E265) block comment should start with '# '
> [Line 1107:9](https://github.com/pydicom/pydicom/blob/f55d192c7b1893d5f67ac4aececf230d8c71da26/pydicom/tests/test_filewriter.py#L1107): [E265](https://duckduckgo.com/?q=pep8%20E265) block comment should start with '# '


codecov[bot]: # [Codecov](https://codecov.io/gh/pydicom/pydicom/pull/1194?src=pr&el=h1) Report
> Merging [#1194](https://codecov.io/gh/pydicom/pydicom/pull/1194?src=pr&el=desc) into [master](https://codecov.io/gh/pydicom/pydicom/commit/5e70c1dfe09820023fec519dac4c51bebcb7f60d?el=desc) will **increase** coverage by `0.00%`.
> The diff coverage is `100.00%`.

[![Impacted file tree graph](https://codecov.io/gh/pydicom/pydicom/pull/1194/graphs/tree.svg?width=650&height=150&src=pr&token=YciLV15Lwr)](https://codecov.io/gh/pydicom/pydicom/pull/1194?src=pr&el=tree)

```diff
@@           Coverage Diff           @@
##           master    #1194   +/-   ##
=======================================
  Coverage   94.05%   94.05%           
=======================================
  Files          54       54           
  Lines        7969     7973    +4     
=======================================
+ Hits         7495     7499    +4     
  Misses        474      474           
```


| [Impacted Files](https://codecov.io/gh/pydicom/pydicom/pull/1194?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [pydicom/filewriter.py](https://codecov.io/gh/pydicom/pydicom/pull/1194/diff?src=pr&el=tree#diff-cHlkaWNvbS9maWxld3JpdGVyLnB5) | `97.14% <100.00%> (+0.03%)` | :arrow_up: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/pydicom/pydicom/pull/1194?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/pydicom/pydicom/pull/1194?src=pr&el=footer). Last update [5e70c1d...903953f](https://codecov.io/gh/pydicom/pydicom/pull/1194?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).


Patch:
diff --git a/doc/release_notes/v2.1.0.rst b/doc/release_notes/v2.1.0.rst
index bc593a6eb..1e2f561c7 100644
--- a/doc/release_notes/v2.1.0.rst
+++ b/doc/release_notes/v2.1.0.rst
@@ -62,3 +62,4 @@ Fixes
 * Raise ``TypeError`` if :func:`~pydicom.dcmread` or :func:`~pydicom.dcmwrite`
   is called with wrong argument
 * Gracefully handle empty Specific Character Set (:issue:`1190`)
+* Fixed empty ambiguous VR elements raising an exception (:issue:`1193`)
diff --git a/pydicom/filewriter.py b/pydicom/filewriter.py
index 7e69a5de3..8fff71195 100644
--- a/pydicom/filewriter.py
+++ b/pydicom/filewriter.py
@@ -87,6 +87,9 @@ def _correct_ambiguous_vr_element(elem, ds, is_little_endian):
             elem.VR = 'SS'
             byte_type = 'h'
 
+        if elem.VM == 0:
+            return elem
+
         # Need to handle type check for elements with VM > 1
         elem_value = elem.value if elem.VM == 1 else elem.value[0]
         if not isinstance(elem_value, int):
@@ -115,6 +118,9 @@ def _correct_ambiguous_vr_element(elem, ds, is_little_endian):
         # As per PS3.3 C.11.1.1.1
         if ds.LUTDescriptor[0] == 1:
             elem.VR = 'US'
+            if elem.VM == 0:
+                return elem
+
             elem_value = elem.value if elem.VM == 1 else elem.value[0]
             if not isinstance(elem_value, int):
                 elem.value = convert_numbers(elem.value, is_little_endian, 'H')


Test patch:
diff --git a/pydicom/tests/test_filewriter.py b/pydicom/tests/test_filewriter.py
index 3f7e1c22d..72ffd5a31 100644
--- a/pydicom/tests/test_filewriter.py
+++ b/pydicom/tests/test_filewriter.py
@@ -1054,7 +1054,7 @@ class TestCorrectAmbiguousVRElement:
         elem = RawDataElement(0x60003000, 'OB', 1, b'\x00', 0, True, True)
         out = correct_ambiguous_vr_element(elem, Dataset(), True)
         assert out == elem
-        assert type(out) == RawDataElement
+        assert isinstance(out, RawDataElement)
 
     def test_correct_ambiguous_data_element(self):
         """Test correct ambiguous US/SS element"""
@@ -1086,10 +1086,28 @@ class TestCorrectAmbiguousVRElement:
         ds[0x00280120] = elem
         ds.PixelRepresentation = 0
         out = correct_ambiguous_vr_element(elem, ds, True)
-        assert type(out) == DataElement
+        assert isinstance(out, DataElement)
         assert out.VR == 'US'
         assert out.value == 0xfffe
 
+    def test_empty_value(self):
+        """Regression test for #1193: empty value raises exception."""
+        ds = Dataset()
+        elem = RawDataElement(0x00280106, 'US or SS', 0, None, 0, True, True)
+        ds[0x00280106] = elem
+        out = correct_ambiguous_vr_element(elem, ds, True)
+        assert isinstance(out, DataElement)
+        assert out.VR == 'US'
+
+        ds.LUTDescriptor = [1, 1, 1]
+        elem = RawDataElement(0x00283006, 'US or SS', 0, None, 0, True, True)
+        assert out.value is None
+        ds[0x00283006] = elem
+        out = correct_ambiguous_vr_element(elem, ds, True)
+        assert isinstance(out, DataElement)
+        assert out.VR == 'US'
+        assert out.value is None
+
 
 class TestWriteAmbiguousVR:
     """Attempt to write data elements with ambiguous VR."""