|
a |
|
b/Dicom.py |
|
|
1 |
import numpy as np |
|
|
2 |
import pydicom as dicom |
|
|
3 |
|
|
|
4 |
def getSegmentedPixelColor (value, intervals): |
|
|
5 |
for i in range(len(intervals)): |
|
|
6 |
if value >= intervals[i][0] and value <= intervals[i][1]: |
|
|
7 |
return intervals[i][2] |
|
|
8 |
return [0,0,0] |
|
|
9 |
|
|
|
10 |
# Linear transformation : from [bt < pxvalue < wt] linear to [0 <pyvalue< 255] !important: has loss of information |
|
|
11 |
def linearTransform(pxvalue, bt, wt): |
|
|
12 |
if pxvalue < bt: |
|
|
13 |
y=0 |
|
|
14 |
elif pxvalue > wt: |
|
|
15 |
y=255 |
|
|
16 |
else: |
|
|
17 |
y=pxvalue*255/(wt-bt)-255*bt/(wt-bt) |
|
|
18 |
return y |
|
|
19 |
|
|
|
20 |
# Linear transformation : convert to Hounsfield units (HU) |
|
|
21 |
def getHuPixels (pixels_array, rows, cols, intercept, slope): |
|
|
22 |
m = np.zeros((rows, cols), np.int16) |
|
|
23 |
for i in range(rows): |
|
|
24 |
for j in range(cols): |
|
|
25 |
m[i][j] = pixels_array[i][j] * slope + intercept |
|
|
26 |
return m |
|
|
27 |
|
|
|
28 |
class Dicom: |
|
|
29 |
def __init__(self, src): |
|
|
30 |
self.__ds = dicom.dcmread(src) |
|
|
31 |
self.__patientId = self.__ds.PatientID |
|
|
32 |
self.__cols = self.__ds.Columns |
|
|
33 |
self.__rows = self.__ds.Rows |
|
|
34 |
self.__huPixelsArray = getHuPixels(self.__ds.pixel_array, self.__rows, self.__cols, self.__ds.RescaleIntercept, self.__ds.RescaleSlope) |
|
|
35 |
|
|
|
36 |
def getPatientId (self): |
|
|
37 |
return self.__patientId |
|
|
38 |
|
|
|
39 |
def getPixelsArray (self): |
|
|
40 |
return self.__huPixelsArray |
|
|
41 |
|
|
|
42 |
def getRawPixelsArray (self): |
|
|
43 |
return self.__ds.pixel_array |
|
|
44 |
|
|
|
45 |
def getLinearRGB (self, bt, wt): |
|
|
46 |
image = np.zeros((self.__rows, self.__cols, 3), np.uint8) |
|
|
47 |
for i in range(self.__rows): |
|
|
48 |
for j in range(self.__cols): |
|
|
49 |
color = linearTransform(self.getPixelsArray()[i][j], bt, wt) |
|
|
50 |
image[i][j] = (color,color,color) |
|
|
51 |
return image |
|
|
52 |
|
|
|
53 |
# Remember, open-cv uses BGR color system |
|
|
54 |
def getSegmentedRGB (self, intervals = [(-3000,-1000,[0,0,0]),(-15,15,[255,0,128]),(20,50,[255,0,0]),(60,100,[0,0,255]),(101,3000,[255,255,255])]): # List of intervals to filter |
|
|
55 |
image = np.zeros((self.__rows, self.__cols, 3), np.uint8) |
|
|
56 |
for i in range(self.__rows): |
|
|
57 |
for j in range(self.__cols): |
|
|
58 |
image[i][j] = getSegmentedPixelColor(self.getPixelsArray()[i][j], intervals) |
|
|
59 |
return image |
|
|
60 |
|
|
|
61 |
def showHistogram (self): |
|
|
62 |
import matplotlib.pyplot as plt |
|
|
63 |
plt.hist(self.getPixelsArray().flatten(), bins=50, color='c') |
|
|
64 |
plt.xlabel("Hounsfield Units (HU)") |
|
|
65 |
plt.ylabel("Frequency") |
|
|
66 |
plt.show() |