Length of a Dataset object in bytes

25 views
Skip to first unread message

Stacy Maimoon

unread,
Aug 7, 2023, 12:35:01 PM8/7/23
to pydicom
Is there an (elegant) possibility to determine the length in bytes of a Dataset object (including pixel data)? [Need it for caching]

In C++ or C# I would store the object on a memory stream and then get the length of the buffer. But I failed to find anything like memory stream in Python, and you can only save a dataset as a file (not a stream).

Doe anybody have an idea? Thanks!


Darcy Mason

unread,
Aug 7, 2023, 12:42:31 PM8/7/23
to pydicom
Python's `io.BytesIO` is an in-memory stream, and you can pass a file-like object (such as BytesIO) to `Dataset.dcmwrite`[1].

Stacy Maimoon

unread,
Aug 7, 2023, 1:29:42 PM8/7/23
to pydicom
Thanks a lot Darcy,
it was really easy, like:

import io
from pydicom import FileDataset
import pydicom as dicom

#...

def get_dataset_size(dataset: FileDataset):
    with io.BytesIO() as memory_stream:
        dataset.save_as(memory_stream)
        return len(memory_stream.getbuffer())
Reply all
Reply to author
Forward
0 new messages