Sei sulla pagina 1di 6

DICOM Image Pre-processing

July 8, 2019

[1]: import numpy as np


import pydicom
import os
import matplotlib.pyplot as plt
from glob import glob
from IPython.display import Image
[2]: def show_dcm_info(dataset):
print("Filename.........:", file_path)
print("Storage type.....:", dataset.SOPClassUID)
print()

pat_name = dataset.PatientName
display_name = pat_name.family_name + ", " + pat_name.given_name
print("Patient's name......:", display_name)
print("Patient id..........:", dataset.PatientID)
print("Patient's Age.......:", dataset.PatientAge)
print("Patient's Sex.......:", dataset.PatientSex)
print("Modality............:", dataset.Modality)
print("Body Part Examined..:", dataset.BodyPartExamined)
print("View Position.......:", dataset.ViewPosition)

if 'PixelData' in dataset:
rows = int(dataset.Rows)
cols = int(dataset.Columns)
print("Image size.......: {rows:d} x {cols:d}, {size:d} bytes".format(
rows=rows, cols=cols, size=len(dataset.PixelData)))
if 'PixelSpacing' in dataset:
print("Pixel spacing....:", dataset.PixelSpacing)
[3]: def plot_pixel_array(dataset, figsize=(10,10)):
plt.figure(figsize=figsize)
plt.imshow(dataset.pixel_array, cmap=plt.cm.bone)
# python -m pip install pillow
# pip install glob3
plt.show()

1
[4]: file_path=""
data_path = "C:
,→\\Users\\dongh\\Documents\\siim-acr-pneumothorax-segmentation\\sample_images"

output_path = working_path = "C:\\Users\\dongh\\"


g = glob(data_path + '/*.dcm')

# Print out the first 5 file names to verify we're in the right folder.
print ("Total of %d DICOM images.\nFirst 5 filenames:" % len(g))
print ('\n'.join(g[:5]))

Total of 1 DICOM images.


First 5 filenames:
C:\Users\dongh\Documents\siim-acr-pneumothorax-segmentation\sample_images\1.2.27
6.0.7230010.3.1.4.8323329.12743.1517875241.599591.dcm

[5]: #
# Loop over the image files and store everything into a list.
#

def load_scan(path):
slices = [pydicom.read_file(path + '/' + s,force=True) for s in os.
,→listdir(path)]

slices.sort(key = lambda x: int(x.InstanceNumber))


print (len(slices))

try:
slice_thickness = np.abs(slices[0].PixelSpacing[0] - slices[0].
,→PixelSpacing[1])

except:
slice_thickness = np.abs(slices[0].PixelSpacing[1] - slices[0].
,→PixelSpacing[2])

for s in slices:
s.SliceThickness = slice_thickness
return slices

def get_pixels_hu(scans):
image = np.stack([s.pixel_array for s in scans])
# Convert to int16 (from sometimes int16),
# should be possible as values should always be low enough (<32k)
image = image.astype(np.int16)

# Set outside-of-scan pixels to 1


# The intercept is usually -1024, so air is approximately 0
image[image == -2000] = 0

2
# Convert to Hounsfield units (HU)
if ('RescaleIntercept' in scans) and ('RescaleSlope' in scans):
intercept = scans[0].RescaleIntercept
slope = scans[0].RescaleSlope

if slope != 1:
image = slope * image.astype(np.float64)
image = image.astype(np.int16)

image += np.int16(intercept)

return np.array(image, dtype=np.int16)

id=0
patient = load_scan(data_path)
imgs = get_pixels_hu(patient)

[6]: np.save(output_path + "fullimages_%d.npy" % (id), imgs)


[7]: # Hounsfield-Units-for-human-body.png
Image("img/Hounsfield-Units-for-human-body.png")
[7]:

3
[8]: file_used=output_path+"fullimages_%d.npy" % id
imgs_to_process = np.load(file_used).astype(np.float64)

plt.hist(imgs_to_process.flatten(), bins=50, color='c')


plt.xlabel("Hounsfield Units (HU)")
plt.ylabel("Frequency")
plt.show()

[9]: # Validation
Image("img/dicom_view.png")
# actual image
[9]:

4
[10]: samples_files = glob('siim-acr-pneumothorax-segmentation\sample_images\*.dcm')

for file_path in samples_files :


dataset = pydicom.dcmread(file_path)
show_dcm_info(dataset)
plot_pixel_array(dataset)
break;
# Python rendering image

Filename...: siim-acr-pneumothorax-segmentation\sample_images\1.2.276.0.72
30010.3.1.4.8323329.12743.1517875241.599591.dcm
Storage type...: 1.2.840.10008.5.1.4.1.1.7

Patient's name...: fcb8a3cf-9449-4186-b29c-db5b93c9c75c,


Patient id...: fcb8a3cf-9449-4186-b29c-db5b93c9c75c
Patient's Age...: 28
Patient's Sex...: M
Modality...: CR

5
Body Part Examined..: CHEST
View Position...: PA
Image size...: 1024 x 1024, 112200 bytes
Pixel spacing...: ['0.19431099999999998', '0.19431099999999998']

Potrebbero piacerti anche