a b/DATA2NPY/dicom2npy.py
1
import numpy as np
2
import os
3
import dicom
4
5
6
N = 82
7
W = 512
8
H = 512
9
path1 = 'DOI'
10
path2 = 'images'
11
if not os.path.exists(path2):
12
    os.makedirs(path2)
13
14
for n in range(N):
15
    volumeID = '{:0>4}'.format(n + 1)
16
    print 'Processing File ' + volumeID
17
    filename1 = 'PANCREAS_' + volumeID
18
    directory1 = os.path.join(path1, filename1)
19
    filename2 = volumeID + '.npy'
20
    for path_, _, file_ in os.walk(directory1):
21
        L = len(file_)
22
        if L > 0:
23
            print '  ' + str(L) + ' slices along the axial view.'
24
            data = np.zeros((W, H, L), dtype = np.int16)
25
            for f in sorted(file_):
26
                file1 = os.path.abspath(os.path.join(path_, f))
27
                image = dicom.read_file(file1)
28
                sliceID = image.data_element("InstanceNumber").value - 1
29
                if image.pixel_array.shape[0] <> 512 or image.pixel_array.shape[1] <> 512:
30
                    exit('  Error: DICOM image does not fit ' + str(W) + 'x' + str(H) + ' size!')
31
                data[:, :, sliceID] = image.pixel_array
32
            file2 = os.path.join(path2, filename2)
33
            np.save(file2, data)
34
    print 'File ' + volumeID + ' is saved in ' + file2 + ' .'
35