'How do I convert a 4D image to a DICOM image in pydicom?

I have a 4D dicom image which I read with dcmread. Consequently, I change a few pixels to black in order to remove the imprinted patient information. However, if I want so save these changes I get errors.

Code:

pathFile='...' #Fill in Path
ds=dcmread(pathFile)
arr=ds.pixel_array #size(47,600,800,3) here there are 47 frames of images 600x800 in three colors.
arr[:,0:16,0:-1,:]=0 #make some pixel black to remove imprinted information
ds.PixelData=arr.astype(arr.dtype).tobytes()
ds.save_as('test.dcm')

Error I get:

ValueError: (7FE0,0010) Pixel Data has an undefined length indicating
that it's compressed, but the data isn't encapsulated as required. See
pydicom.encaps.encapsulate() for more information

I know I have to use encapsulate my data frame by frame like: ds.PixelData = encapsulate([frame1, frame2, ...]). However I have an extra dimension and I can't seem to work it out. If I use it like this:

ds.PixelData=encapsulate([i for i in arr])

I get the error:

UFuncTypeError: ufunc 'add' did not contain a loop with signature matching types (dtype('S8'), dtype('uint8')) -> None


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source