1
+ # ------------------------------------------------------------------------------
2
+ # Copyright (c) Tencent
3
+ # Licensed under the GPLv3 License.
4
+ # Created by Kai Ma ([email protected] )
5
+ # ------------------------------------------------------------------------------
6
+ import os
7
+ import cv2
8
+ import time
9
+ import pydicom
10
+ import numpy as np
11
+ import SimpleITK as sitk
12
+
13
+ # Load the scans in given folder path
14
+ def load_scan_dcm (path ):
15
+ slices = [pydicom .dcmread (os .path .join (path , s )) for s in os .listdir (path ) if 'dcm' in s ]
16
+ slices .sort (key = lambda x : int (x .ImagePositionPatient [2 ]))
17
+
18
+ try :
19
+ slice_thickness = np .abs (slices [0 ].ImagePositionPatient [2 ] - slices [1 ].ImagePositionPatient [2 ])
20
+ except :
21
+ slice_thickness = np .abs (slices [0 ].SliceLocation - slices [1 ].SliceLocation )
22
+
23
+ for s in slices :
24
+ if hasattr (s , 'SliceThickness' ):
25
+ pass
26
+ else :
27
+ s .SliceThickness = slice_thickness
28
+ return slices
29
+
30
+ # input could be .mhd/.mha format
31
+ def load_scan_mhda (path ):
32
+ img_itk = sitk .ReadImage (path )
33
+ img = sitk .GetArrayFromImage (img_itk )
34
+ return img_itk , img , img_itk .GetOrigin (), img_itk .GetSize (), img_itk .GetSpacing ()
35
+
36
+ # output coule be .mhd/.mha format
37
+ def save_scan_mhda (volume , origin , spacing , path ):
38
+ itkimage = sitk .GetImageFromArray (volume , isVector = False )
39
+ itkimage .SetSpacing (spacing )
40
+ itkimage .SetOrigin (origin )
41
+ sitk .WriteImage (itkimage , path , True )
42
+
43
+ # do betstriping
44
+ def bedstriping (ct_scan , ct_mask ):
45
+ bedstrip_scan = ct_scan * ct_mask
46
+ return bedstrip_scan
47
+
48
+ # build CycleGAN trainSet A
49
+ def buildTrainA (raw_root_path , save_root_path ):
50
+ files_list = os .listdir (raw_root_path )
51
+ if not os .path .exists (save_root_path ):
52
+ os .makedirs (save_root_path )
53
+ start = time .time ()
54
+ for fileIndex , fileName in enumerate (files_list ):
55
+ t0 = time .time ()
56
+ print ('Begin {}/{}: {}' .format (fileIndex + 1 , len (files_list ), fileName ))
57
+ imageDir = os .path .join (raw_root_path , fileName )
58
+ imagePath = os .path .join (imageDir , 'xray1.png' )
59
+ image = cv2 .imread (imagePath , 0 )
60
+ savePath = os .path .join (save_root_path , '{}.png' .format (fileName ))
61
+ cv2 .imwrite (savePath , image )
62
+ t1 = time .time ()
63
+ print ('End! Case time: {}' .format (t1 - t0 ))
64
+ end = time .time ()
65
+ print ('Finally! Total time of build TrainA: {}' .format (end - start ))
66
+
67
+ # build CycleGAN trainSet B
68
+ def buildTrainB (raw_root_path , save_root_path ):
69
+ BSize = 1000
70
+ files_list = os .listdir (raw_root_path )
71
+ if not os .path .exists (save_root_path ):
72
+ os .makedirs (save_root_path )
73
+ tb = np .arange (0 , len (files_list ))
74
+ np .random .shuffle (tb )
75
+ start = time .time ()
76
+ for i in range (0 , BSize ):
77
+ t0 = time .time ()
78
+ imageName = files_list [tb [i ]]
79
+ print ('Begin {}/{}: {}' .format (i + 1 , BSize , imageName ))
80
+ imagePath = os .path .join (raw_root_path , imageName )
81
+ image = cv2 .imread (imagePath , 0 )
82
+ image = cv2 .resize (image , (320 , 320 ))
83
+ savePath = os .path .join (save_root_path , imageName )
84
+ cv2 .imwrite (savePath , image )
85
+ t1 = time .time ()
86
+ print ('End! Case time: {}' .format (t1 - t0 ))
87
+ end = time .time ()
88
+ print ('Finlly! Total time of build TrainB: {}' .format (end - start ))
89
+
90
+ # resize all images in a directory
91
+ def resize_to_standard (path ):
92
+ images = os .listdir (path )
93
+ for i in images :
94
+ imageName = os .path .join (path , i )
95
+ image = cv2 .imread (imageName , 0 )
96
+ image = cv2 .resize (image , (320 , 320 ))
97
+ cv2 .imwrite (imageName , image )
98
+ print ('All images have been resized!' )
99
+
100
+ def convert2hu (path ):
101
+ img , scan , origin , size , spacing = load_scan_mhda (path )
102
+ #print(scan.dtype)
103
+ scan = scan .astype (np .int16 )
104
+ scanhu = scan - 1024
105
+ root , file = os .path .split (path )
106
+ fileName = file .replace ('.mha' , 'hu' )
107
+ #print(root, file)
108
+ savePath = os .path .join (root , fileName + '.mha' )
109
+ save_scan_mhda (scanhu , origin , spacing , savePath )
110
+
111
+ def psnr (img_1 , img_2 , PIXEL_MAX = 255.0 ):
112
+ mse = np .mean ((img_1 - img_2 ) ** 2 )
113
+ if mse == 0 :
114
+ return 100
115
+ return 20 * np .log10 (PIXEL_MAX / np .sqrt (mse ))
116
+
117
+
118
+ if __name__ == '__main__' :
119
+ raw_root_pathA = 'D:/LIDC_TEST'
120
+ save_root_pathA = 'D:/xrayv2r/trainA'
121
+ raw_root_pathB = 'F:/Data/NIHCXR/images_002/images'
122
+ save_root_pathB = 'D:/xrayv2r/trainB'
123
+ #buildTrainA(raw_root_pathA, save_root_pathA)
124
+ #buildTrainB(raw_root_pathB, save_root_pathB)
125
+
126
+ '''
127
+ raw_root_pathA = 'D:/xrayv2r/trainA500'
128
+ ASize = 260
129
+ files_list = os.listdir(raw_root_pathA)
130
+ if not os.path.exists(save_root_pathA):
131
+ os.makedirs(save_root_pathA)
132
+ start = time.time()
133
+ for i in range(0, ASize):
134
+ t0 = time.time()
135
+ imageName = files_list[i]
136
+ print('Begin {}/{}: {}'.format(i+1, ASize, imageName))
137
+ imagePath = os.path.join(raw_root_pathA, imageName)
138
+ image = cv2.imread(imagePath, 0)
139
+ #image = cv2.resize(image, (320, 320))
140
+ savePath = os.path.join(save_root_pathA, imageName)
141
+ cv2.imwrite(savePath, image)
142
+ t1 = time.time()
143
+ print('End! Case time: {}'.format(t1-t0))
144
+ end = time.time()
145
+ print('Finlly! Total time of build TrainB: {}'.format(end-start))
146
+ '''
0 commit comments