File: memory_dataset.py

package info (click to toggle)
pydicom 2.4.3-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 11,700 kB
  • sloc: python: 129,337; makefile: 198; sh: 121
file content (84 lines) | stat: -rw-r--r-- 2,392 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# Copyright pydicom authors 2019. See LICENSE file for details
"""
======================================
Show working with memory-based dataset
======================================

Show how to write a DICOM dataset into a byte array and to read
it back from a byte array. This can be helpful for example if working with
datasets saved as blobs in a database.

"""


from io import BytesIO

from pydicom import dcmread, dcmwrite
from pydicom.filebase import DicomFileLike

print(__doc__)

usage = "Usage: python memory_dataset.py dicom_filename"


def write_dataset_to_bytes(dataset):
    # create a buffer
    with BytesIO() as buffer:
        # create a DicomFileLike object that has some properties of DataSet
        memory_dataset = DicomFileLike(buffer)
        # write the dataset to the DicomFileLike object
        dcmwrite(memory_dataset, dataset)
        # to read from the object, you have to rewind it
        memory_dataset.seek(0)
        # read the contents as bytes
        return memory_dataset.read()


def adapt_dataset_from_bytes(blob):
    # you can just read the dataset from the byte array
    dataset = dcmread(BytesIO(blob))
    # do some interesting stuff
    dataset.is_little_endian = False
    dataset.PatientName = 'Bond^James'
    dataset.PatientID = '007'
    return dataset


class DummyDataBase:
    def __init__(self):
        self._blobs = {}

    def save(self, name, blob):
        self._blobs[name] = blob

    def load(self, name):
        return self._blobs.get(name)


if __name__ == '__main__':
    import sys

    if len(sys.argv) != 2:
        print("Please supply a dicom file name:\n")
        print(usage)
        sys.exit(-1)
    file_path = sys.argv[1]
    db = DummyDataBase()

    # Convert a dataset to a byte array:
    # - read the dataset from a file
    dataset = dcmread(file_path)
    print(dataset)
    # - convert the dataset to bytes
    ds_bytes = write_dataset_to_bytes(dataset)
    # - save the bytes in some storage
    db.save('dataset', ds_bytes)

    # Convert a byte array to a dataset:
    # - get the bytes from storage
    read_bytes = db.load('dataset')
    # - convert the bytes into a dataset and do something interesting with it
    read_dataset = adapt_dataset_from_bytes(read_bytes)
    print(read_dataset)
    # - you can write your dataset to a file if wanted
    dcmwrite(file_path + '_new', read_dataset)