Tutorial 3 - Manipulação de imagens em arquivos DICOM

Neste tutorial veremos exemplos de como manipular imagens em arquivos DICOM com as bibliotecas pydicom e ImageIO.

Documentação básica sobre leitura, acesso, modificação e escrita de arquivos DICOM

pydicom

imageio


Bibliotecas e pacotes

!pip install pydicom
Collecting pydicom
[?25l  Downloading https://files.pythonhosted.org/packages/f4/15/df16546bc59bfca390cf072d473fb2c8acd4231636f64356593a63137e55/pydicom-2.1.2-py3-none-any.whl (1.9MB)
     |████████████████████████████████| 1.9MB 5.4MB/s 
[?25hInstalling collected packages: pydicom
Successfully installed pydicom-2.1.2
import numpy as np

import imageio

from pydicom import dcmread

import matplotlib.pyplot as plt

%matplotlib inline

Tutorial

Fontes das imagens


FAÇA VOCÊ

Baixe e faça o upload do arquivo DICOM


pydicom

Carregar arquivos

dicom_ds = dcmread("0015.DCM")

Visualizar a lista de elementos de dados

print(dicom_ds)
Dataset.file_meta -------------------------------
(0002, 0000) File Meta Information Group Length  UL: 202
(0002, 0001) File Meta Information Version       OB: b'\x00\x01'
(0002, 0002) Media Storage SOP Class UID         UI: X-Ray Radiofluoroscopic Image Storage
(0002, 0003) Media Storage SOP Instance UID      UI: 1.2.840.113619.2.15.1008000062035011254.825190719.0.31.2.1
(0002, 0010) Transfer Syntax UID                 UI: Explicit VR Little Endian
(0002, 0012) Implementation Class UID            UI: 1.2.840.113619.6.36
(0002, 0013) Implementation Version Name         SH: '1_2_5'
(0002, 0016) Source Application Entity Title     AE: 'ard-demo'
-------------------------------------------------
(0008, 0005) Specific Character Set              CS: 'ISO_IR 100'
(0008, 0008) Image Type                          CS: ['ORIGINAL', 'PRIMARY', 'SINGLE PLANE']
(0008, 0016) SOP Class UID                       UI: X-Ray Radiofluoroscopic Image Storage
(0008, 0018) SOP Instance UID                    UI: 1.2.840.113619.2.15.1008000062035011254.825190719.0.31.2.1
(0008, 0020) Study Date                          DA: '19960308'
(0008, 0021) Series Date                         DA: '19960308'
(0008, 0022) Acquisition Date                    DA: '19960308'
(0008, 0023) Content Date                        DA: '19960308'
(0008, 0030) Study Time                          TM: ''
(0008, 0032) Acquisition Time                    TM: '105650'
(0008, 0033) Content Time                        TM: '105650'
(0008, 0050) Accession Number                    SH: ''
(0008, 0060) Modality                            CS: 'RF'
(0008, 0070) Manufacturer                        LO: 'GE MEDICAL SYSTEMS'
(0008, 0090) Referring Physician's Name          PN: ''
(0008, 1010) Station Name                        SH: ''
(0008, 1030) Study Description                   LO: '5'
(0008, 103e) Series Description                  LO: ''
(0008, 1050) Performing Physician's Name         PN: '00558747^'
(0008, 1090) Manufacturer's Model Name           LO: 'DRS'
(0010, 0010) Patient's Name                      PN: 'Rubo DEMO'
(0010, 0020) Patient ID                          LO: '10-55-87'
(0010, 0030) Patient's Birth Date                DA: ''
(0010, 0040) Patient's Sex                       CS: 'F'
(0010, 1010) Patient's Age                       AS: ''
(0018, 0060) KVP                                 DS: None
(0018, 1020) Software Versions                   LO: '4.00'
(0018, 1150) Exposure Time                       IS: None
(0018, 1151) X-Ray Tube Current                  IS: None
(0018, 1155) Radiation Setting                   CS: 'GR'
(0018, 1400) Acquisition Device Processing Descr LO: '10 OUT OF 20. 0=LOW, 20=HIGH CONVOLUTION KERNEL'
(0018, 1600) Shutter Shape                       CS: ['CIRCULAR', 'RECTANGULAR']
(0018, 1602) Shutter Left Vertical Edge          IS: "10"
(0018, 1604) Shutter Right Vertical Edge         IS: "950"
(0018, 1606) Shutter Upper Horizontal Edge       IS: "10"
(0018, 1608) Shutter Lower Horizontal Edge       IS: "950"
(0018, 1610) Center of Circular Shutter          IS: [0480,  0480]
(0018, 1612) Radius of Circular Shutter          IS: "470"
(0020, 000d) Study Instance UID                  UI: 1.2.840.113619.2.15.1008000062035011254.825190719.2.31
(0020, 000e) Series Instance UID                 UI: 1.2.840.113619.2.15.1008000062035011254.825190719.1.31
(0020, 0010) Study ID                            SH: ''
(0020, 0011) Series Number                       IS: "1"
(0020, 0013) Instance Number                     IS: "2"
(0020, 0020) Patient Orientation                 CS: ''
(0020, 4000) Image Comments                      LT: 'L1'
(0028, 0002) Samples per Pixel                   US: 1
(0028, 0004) Photometric Interpretation          CS: 'MONOCHROME2'
(0028, 0010) Rows                                US: 1024
(0028, 0011) Columns                             US: 1024
(0028, 0100) Bits Allocated                      US: 8
(0028, 0101) Bits Stored                         US: 8
(0028, 0102) High Bit                            US: 7
(0028, 0103) Pixel Representation                US: 0
(0028, 1040) Pixel Intensity Relationship        CS: 'LIN'
(0028, 1050) Window Center                       DS: "127.0"
(0028, 1051) Window Width                        DS: "255.0"
(0028, 2110) Lossy Image Compression             CS: '00'
(0028, 6010) Representative Frame Number         US: 1
(0028, 6020) Frame Numbers of Interest (FOI)     US: 2
(0028, 6022) Frame of Interest Description       LO: 'L1'
(0037, 0010) Private Creator                     LO: 'GEMS_DRS_1'
(0037, 1010) [Refering Department]               LO: 'EX 101^'
(0037, 1020) [Screen Number]                     US: 2
(0037, 1040) [Left Orientation]                  CS: ''
(0037, 1042) [Right Orientation]                 CS: ''
(0037, 1050) [Inversion]                         CS: 'INV_NORMAL'
(0037, 1060) [DSA]                               CS: ''
(7fe0, 0010) Pixel Data                          OB: Array of 1048576 elements

Metadados

dicom_ds.file_meta
(0002, 0000) File Meta Information Group Length  UL: 202
(0002, 0001) File Meta Information Version       OB: b'\x00\x01'
(0002, 0002) Media Storage SOP Class UID         UI: X-Ray Radiofluoroscopic Image Storage
(0002, 0003) Media Storage SOP Instance UID      UI: 1.2.840.113619.2.15.1008000062035011254.825190719.0.31.2.1
(0002, 0010) Transfer Syntax UID                 UI: Explicit VR Little Endian
(0002, 0012) Implementation Class UID            UI: 1.2.840.113619.6.36
(0002, 0013) Implementation Version Name         SH: '1_2_5'
(0002, 0016) Source Application Entity Title     AE: 'ard-demo'

Acessando elementos pelas tags

dicom_ds[0x0008,0x0016]
(0008, 0016) SOP Class UID                       UI: X-Ray Radiofluoroscopic Image Storage

Acessando o array da imagem

img_xray = dicom_ds.pixel_array

img_xray.shape
(1024, 1024)
plt.imshow(img_xray, cmap="gray", vmin=0, vmax=255)

plt.colorbar()
<matplotlib.colorbar.Colorbar at 0x7f617d2a9da0>

png

Outro exemplo

Exemplo disponível na documentação.

# authors : Guillaume Lemaitre <g.lemaitre58@gmail.com>

# license : MIT



import matplotlib.pyplot as plt

from pydicom import dcmread

from pydicom.data import get_testdata_file



fpath = get_testdata_file('CT_small.dcm')

ds = dcmread(fpath)



# Normal mode:

print()

print(f"File path........: {fpath}")

print(f"SOP Class........: {ds.SOPClassUID} ({ds.SOPClassUID.name})")

print()



pat_name = ds.PatientName

display_name = pat_name.family_name + ", " + pat_name.given_name

print(f"Patient's Name...: {display_name}")

print(f"Patient ID.......: {ds.PatientID}")

print(f"Modality.........: {ds.Modality}")

print(f"Study Date.......: {ds.StudyDate}")

print(f"Image size.......: {ds.Rows} x {ds.Columns}")

print(f"Pixel Spacing....: {ds.PixelSpacing}")



# use .get() if not sure the item exists, and want a default value if missing

print(f"Slice location...: {ds.get('SliceLocation', '(missing)')}")



# plot the image using matplotlib

plt.imshow(ds.pixel_array, cmap=plt.cm.gray)

plt.show()
File path........: /usr/local/lib/python3.6/dist-packages/pydicom/data/test_files/CT_small.dcm
SOP Class........: 1.2.840.10008.5.1.4.1.1.2 (CT Image Storage)

Patient's Name...: CompressedSamples, CT1
Patient ID.......: 1CT1
Modality.........: CT
Study Date.......: 20040119
Image size.......: 128 x 128
Pixel Spacing....: [0.661468, 0.661468]
Slice location...: -77.2040634155

png

ImageIO

Carregar arquivos

im = imageio.imread("0015.DCM")

im.shape
(1024, 1024)

Metadados

im.meta
Dict([('TransferSyntaxUID', '1.2.840.10008.1.2.1'),
      ('SOPClassUID', '1.2.840.10008.5.1.4.1.1.12.2'),
      ('SOPInstanceUID',
       '1.2.840.113619.2.15.1008000062035011254.825190719.0.31.2.1'),
      ('StudyDate', '19960308'),
      ('SeriesDate', '19960308'),
      ('AcquisitionDate', '19960308'),
      ('ContentDate', '19960308'),
      ('StudyTime', ''),
      ('AcquisitionTime', '105650'),
      ('ContentTime', '105650'),
      ('Modality', 'RF'),
      ('Manufacturer', 'GE MEDICAL SYSTEMS'),
      ('StudyDescription', '5'),
      ('SeriesDescription', ''),
      ('PatientName', 'Rubo DEMO'),
      ('PatientID', '10-55-87'),
      ('PatientBirthDate', ''),
      ('PatientSex', 'F '),
      ('PatientAge', ''),
      ('StudyInstanceUID',
       '1.2.840.113619.2.15.1008000062035011254.825190719.2.31'),
      ('SeriesInstanceUID',
       '1.2.840.113619.2.15.1008000062035011254.825190719.1.31'),
      ('SeriesNumber', 1),
      ('InstanceNumber', 2),
      ('PatientOrientation', ''),
      ('SamplesPerPixel', 1),
      ('Rows', 1024),
      ('Columns', 1024),
      ('BitsAllocated', 8),
      ('BitsStored', 8),
      ('HighBit', 7),
      ('PixelRepresentation', 0),
      ('PixelData',
       b'Data converted to numpy array, raw data removed to preserve memory'),
      ('shape', (1024, 1024)),
      ('sampling', (1.0, 1.0))])
im.meta["BitsAllocated"]
8

Acessando o array da imagem

im
Array([[46, 49, 46, ...,  0,  0,  0],
       [ 0,  0,  0, ...,  0,  0,  0],
       [ 0,  0,  0, ...,  0,  0,  0],
       ...,
       [ 0,  0,  0, ...,  0,  0,  0],
       [ 0,  0,  0, ...,  0,  0,  0],
       [ 0,  0,  0, ...,  0,  0,  0]], dtype=uint8)
plt.imshow(im, cmap="gray", vmin=0, vmax=255)
<matplotlib.image.AxesImage at 0x7f617cd37940>

png