I'm trying get all images in a multi-frame DICOM file. Right now I was successfully able to see and save a single image in a single-frame DICOM file, by using the pydicom
and matplotlib
libraries, like so:
filename = pydicom.data.data_manager.get_files(*base folder path*,*dicom filename*)[0]
ds = pydicom.dcmread(filename)
plt.imshow(ds.pixel_array, cmap=plt.cm.bone)
plt.show()
Now, I wanted to be able to see and save all images in a multi-frame DICOM image, but by using this snippet of code, it returns the following error:
TypeError: Invalid shape (150, 768, 1024, 3) for image data
I've searched a bit on the web, but couldn't seem to find anything to enlighten me. I wanted to know if someone has passed through this, and what's the best way to overcome it, and be able to get all images in a multi-frame DICOM file.
Note: The similar questions found on Stack Overflow are either outdated or do not comply with what I want.
CodePudding user response:
DICOM is essentially a 'three-dimensional' image format: it can store lots of images or 'slices'. However, since colour images are already 3-dimensional (height, width, RGB channels), DICOM datasets can actually be 4-dimensional (apparently... I didn't know this). At least, I think that's why there are four elements in the shape
of your dataset.
My guess is that the dataset contains 150 images, each of which having 768 by 1024 pixels and 3 channels.
So assuming ds.pixel_array
is array-like, you should be able to see the middle slice like so:
plt.imshow(ds.pixel_array[75])
To save them all, you'd do something like this pseudocode:
for i, slice in enumerate(ds.pixel_array):
plt.imshow(slice)
plt.savefig(f'slice_{i:03n}.png')
Obviously, that will just re-create what you essentially already have but in a less convenient format, but you get the idea.