Search code examples
pythondicompydicom

How do I read and then write a multi-frame DICOM file in pydicom without an image offset?


I read a multi-frame DICOM file with pydicom, after that I write it into a new file. However when I open the DICOM file, the image has an offset/shift.

ds = pydicom.dcmread('./Multiframe/0020.dcm')
arr  = ds.pixel_array
ds.PixelData = encapsulate([arr[0].tobytes(),
                            arr[1].tobytes(),                 
                            arr[2].tobytes(),
                            arr[3].tobytes(),
                            arr[4].tobytes(),
                            arr[5].tobytes(),
                            arr[6].tobytes(),
                            arr[7].tobytes(),
                            arr[8].tobytes(),
                            arr[9].tobytes(),
                            arr[10].tobytes()])

ds.save_as('new.dcm', write_like_original=False)

What is wrong with the code? It works if I write a simple image (not multi-frame), the problem is with the encapsulation.

Original: the original image, an RGB ultrasound scan, presented on a viewer

After: the program's output, with a slight offset, presented by the same viewer


Solution

  • Encapsulation of Pixel Data (both single and multi-framed) is only required for compressed transfer syntaxes, such as JPEG or RLE Lossless. If you have an uncompressed syntax such as Explicit VR Little Endian then no encapsulation is necessary:

    ds = pydicom.dcmread('./Multiframe/0020.dcm')
    arr  = ds.pixel_array
    if ds.file_meta.TransferSyntaxUID.is_compressed:
        raise AttributeError("Encapsulation required for compressed transfer syntaxes")
    
    ds.PixelData = arr.tobytes()
    ds.save_as('new.dcm', write_like_original=False)