Recently I needed to load DICOM files for modeling and I've learned about handly library - imageio. It can handle a lot of different file types effortlessly, one of them DICOM volumetrtic datasets.
# install imageio if you haven't already
!pip install imageio
Requirement already satisfied: imageio in /opt/conda/envs/fastai/lib/python3.8/site-packages (2.9.0) Requirement already satisfied: numpy in /opt/conda/envs/fastai/lib/python3.8/site-packages (from imageio) (1.19.1) Requirement already satisfied: pillow in /opt/conda/envs/fastai/lib/python3.8/site-packages (from imageio) (7.2.0)
import imageio
import torch
As an example, I've downloaded some dicom files from this site
!curl "https://www.visus.com/fileadmin/content/pictures/Downloads/JiveX_DICOME_Viewer/case1.zip" > "case1.zip"
!unzip -q case1.zip
% Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 8449k 100 8449k 0 0 149k 0 0:00:56 0:00:56 --:--:-- 475k
and simply pass the folder to imageio like this:
np_arr = imageio.volread('case1')
Reading DICOM (examining files): 1/31 files (3.2%31/31 files (100.0%) Found 1 correct series. Reading DICOM (loading data): 31/31 (100.0%)
As I prefert to work with PyTorch tensors...
dicom_torch = torch.from_numpy(np_arr)
dicom_torch.shape
torch.Size([31, 512, 512])
... and this is how it looks like
import matplotlib.pyplot as plt
%matplotlib inline
plt.imshow(dicom_torch[10])
<matplotlib.image.AxesImage at 0x7f3ebe5effd0>