# -*- coding: utf-8 -*-
"""
.. module:: image_utils
:synopsis: Module for DICOM file reading
"""
import numpy as np
import dicom
[docs]def createImageCorners(w, h, pixel2mmX, pixel2mmY):
pc = np.array((
(w*pixel2mmX,0,0,1),
(w*pixel2mmX,h*pixel2mmY,0,1),
(0,0,0,1),
(0,h*pixel2mmY,0,1),
)).T
return pc
[docs]def pixelData2grey(D):
"""Convert pixel array to grey values
:param np.ndarray D: pixel array, in format Nch x Nf x Nr x Nc, to convert.
If Nch is 3, then channels are supposed to be R, G, B.
If Nch is 2, then the values are supposed to be grey level and alpha.
If Nch is 1, then the values are supposed to be grey level.
:return: Nf x Nr x Nc array of grey level
:rtype: np.ndarray
"""
d = D.shape
if d[0] < 3:
I = D[0,:]
elif d[0] == 3:
I = rgb2grey(D[0,:], D[1,:], D[2,:])
else:
raise Exception('Image data format not recognized')
return I
[docs]def rgb2grey(R, G, B):
# Taken from http://en.wikipedia.org/wiki/Grayscale
I = (.2126*R+.7152*G+.0722*B).astype(np.uint8)
return I
[docs]def readDICOM(filePath, method='flattened'):
"""Read DICOM file.
:param str filePath: DCOM full file path.
:param str method: pixel array parsing method.
If 'RGB', pixel array is supposed to be 3 x Nf x Nr x Nc. Data for frame i is into [:,i,:,:]
If 'flattened', pixel array is supposed to be Nch x Nf x Nr x Nc. Data for frame i is into [j,k:k+3,:,:], where j = floor(Nch*i / Nf), k = (Nch*i) % Nf.
When using 'flattened', pixel array with dimension Nf x Nr x Nc is also supprted (the only stored value is supposed to be a grey level)
:return: list of following variables:
D (*np.ndarray*) – pixel array reshaped in the standard way Nch x Nf x Nr x Nc as for ``method='flattened'``
ds (*dicom.dataset.FileDataset*) – additional parameters in the DICOM file
"""
ds = dicom.read_file(filePath)
D = ds.pixel_array
if method == 'RGB':
pass
if method == 'flattened':
if len(D.shape) == 4: # first dimension keeps or data channels (RGB, grey-alpha, grey, ...)
N = D.shape[0]
print D.shape
D = np.reshape(D, (D.shape[0]*D.shape[1],D.shape[2],D.shape[3]))[None,:]
D = D[:,::N,:,:]
elif len(D.shape) == 3:
D = D[None,:]
else:
raise Exception('{0}: unknown data format'.format(method))
return D, ds