Sunday, September 10, 2017

Parse DICOM Image in Python | Convert DICOM to PNG in Python

DICOM:

Digital Imaging and Communications in Medicine (DICOM) is a standard for storing and transmitting medical images. It includes a file format definition and a network communications protocol.

PNG:

PNG (pronounced ping as in ping-pong; for Portable Network Graphics) is a file format for image compression that, in time, is expected to replace the Graphics Interchange Format (GIF) that is widely used on today's Internet. Portable Network Graphics (PNG /ˈpɪŋ/) is a raster graphics file format that supports lossless data compression. PNG was created as an improved, non-patented replacement for Graphics Interchange Format (GIF), and is the most widely used lossless image compression format on the Internet.

Prerequisites:

You need to install following python packages: pydicom, pylab, pypng

To install these modules you can type following commands in console:
pip install pydicom
pip install pylab
pip install pypng

Parse and explore DICOM data in Python:



import dicom

myimage = dicom.read_file("\\path\\to\\dicom\\file")

myimage.PatientsName
myimage[0x10,0x10].value
myimage[0x10,0x10].value = 'Test'

myimage.PatientID = "12345"
myimage.SeriesNumber = 5


View/Plot DICOM image in Python:


import dicom
import pylab

myimage=dicom.read_file("\\path\\to\\dicom.dcm")
pylab.imshow(myimage.pixel_array,cmap=pylab.cm.bone)
pylab.show()


Save DICOM file as PNG image using Python:

import dicom
import png

mri_file = open(mri_file_path, 'rb')
myimage = dicom.read_file(mri_file)
mri_file.close()

shape = myimage.pixel_array.shape

image_2d = []
max_val = 0
for row in myimage.pixel_array:
    pixels = []
    for col in row:
        pixels.append(col)
        if col > max_val: max_val = col
    image_2d.append(pixels)

image_2d_scaled = []
for row in image_2d:
    row_scaled = []
    for col in row:
        col_scaled = int((float(col) / float(max_val)) * 255.0)
        row_scaled.append(col_scaled)
    image_2d_scaled.append(row_scaled)

png_file = open(png_file_path, 'wb')
w = png.Writer(shape[1], shape[0], greyscale=True)
w.write(png_file, image_2d_scaled)
png_file.close()


References:
http://pydicom.readthedocs.io/en/stable/pydicom_user_guide.html
http://pydicom.readthedocs.io/en/stable/viewing_images.html
https://github.com/diahpitaloka15/dicom-to-png/blob/master/mritopng.py

Bonus link:
Free online DICOM image viewer: https://www.ofoct.com/viewer/dicom-viewer-online.html

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.