-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_load.py
227 lines (193 loc) · 9.28 KB
/
data_load.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import os
import cv2
import numpy as np
import pandas as pd
from pandas import DataFrame
import config
np.random.seed(1)
class DataLoad:
def __init__(self, train_path: str, test_path: str):
self.train_path = train_path
self.test_path = test_path
train_images = [] # [{'patient ID': id, 'ImgNumber': number, 'ImgPath': path}]
test_images = [] # [{'patient ID': id, 'ImgNumber': number, 'ImgPath': path}]
self.__load_all_image_path__(train_path, train_images)
self.__load_all_image_path__(test_path, test_images)
self.train_images = pd.DataFrame(train_images, columns=['patient ID', 'LR', 'ImgNumber', 'ImgPath'])
self.test_images = pd.DataFrame(test_images, columns=['patient ID', 'LR', 'ImgNumber', 'ImgPath'])
self.train_data: DataFrame = pd.merge(self.get_train_csv(), self.train_images, on='patient ID')
self.test_data: DataFrame = pd.merge(self.get_test_csv(), self.test_images, on='patient ID')
def get_train_csv(self):
return self.load_csv(self.train_path)
def get_test_csv(self):
return self.load_csv(self.test_path)
@staticmethod
def load_csv(path) -> DataFrame:
"""
加载CSV数据集
:param path: 路径
:return: DataFrame
"""
files = os.listdir(path)
for file in files:
if file.endswith('.csv'):
data = pd.read_csv(os.path.join(path, file), header=0)
return data
def __load_all_image_path__(self, path: str, images: list):
"""
加载所有图像路径
:param path:路径
:param images:
:return:
"""
files = os.listdir(path)
for file in files:
file_path = os.path.join(path, file)
if os.path.isdir(file_path):
self.__load_all_image_path__(file_path, images)
elif file.endswith('.jpg'):
split = file.replace('.jpg', '').split('_')
file_id = split[0]
if len(split) > 2:
file_number = split[1] + split[2][-3:]
else:
file_number = split[1]
# _1_000000
images.append({'patient ID': file_id,
'LR': file_id[-1],
'ImgNumber': file_number,
'ImgPath': file_path.replace(config.root_path + '\\', '').replace('\\', '/')})
@staticmethod
def read_image(path: str, to_float=False):
"""
使用OpenCV加载图像数据
:param path:
:param to_float:
:return:
"""
img: np.ndarray = cv2.imread(path)
# 裁剪
# img = img[:500, 500:, :]
if to_float:
img = img.astype('float32')
img = img / 255.0
return img
def get_train_data_cst_all(self, size=None, read_img=False, to_float=False) -> pd.DataFrame:
"""
CST,获取治疗前和治疗后的训练图像,各取size个样本
:param size:
:param read_img:
:return:
"""
pre_cst = self.get_train_data_pre_cst(size, read_img, to_float)
cst = self.get_train_data_cst(size, read_img, to_float)
pre_cst = pre_cst.rename({'preCST': 'label', 'Img': 'feature', 'ImgPath': 'feature'}, axis=1)
pre_cst['type'] = 'preCST'
cst = cst.rename({'CST': 'label', 'Img': 'feature', 'ImgPath': 'feature'}, axis=1)
cst['type'] = 'CST'
cst_data = pd.concat([pre_cst, cst], axis=0, ignore_index=True)
return cst_data[['patient ID', 'type', 'label', 'feature']]
def get_train_data_pre_cst(self, size=None, read_img=False, to_float=False) -> pd.DataFrame:
"""
获取治疗前的训练数据 preCST
:param size: 获取样本数量,None为获取全部
:param read_img 是否读取图像,False:不读取,返回'ImgPath';True:读取,返回'Img'
:return: ['patient ID', 'preCST', 'ImgPath'|'Img']
"""
train_data = self.train_data[self.train_data['ImgNumber'].apply(lambda x: x.startswith('10'))]
img_number = train_data.groupby(['patient ID']).count()['ImgNumber'] / 2 + 1000
img_number = img_number.astype(int)
train_data = train_data[
train_data.apply(lambda x: img_number[x.loc['patient ID']] == int(x.loc['ImgNumber']), axis=1)]
# train_data.loc[train_data['preCST'].isna(), 'preCST'] = 0
train_data.dropna(subset=['preCST'], inplace=True, axis=0)
if size is not None:
train_data = train_data.head(size)
if read_img:
train_data['Img'] = train_data['ImgPath'].apply(lambda path: np.array(self.read_image(path, to_float)))
return train_data[['patient ID', 'preCST', 'Img']]
else:
return train_data[['patient ID', 'preCST', 'ImgPath']]
def get_train_data_cst(self, size=None, read_img=False, to_float=False) -> pd.DataFrame:
"""
获取治疗后的训练数据 CST
:param size: 获取样本数量,None为获取全部
:param read_img 是否读取图像,False:不读取,返回'ImgPath';True:读取,返回'Img'
:return: ['patient ID', 'CST', 'ImgPath'|'Img']
"""
train_data = self.train_data[self.train_data['ImgNumber'].apply(lambda x: x.startswith('20'))]
img_number = train_data.groupby(['patient ID']).count()['ImgNumber'] / 2 + 2000
img_number = img_number.astype(int)
train_data = train_data[
train_data.apply(lambda x: img_number[x.loc['patient ID']] == int(x.loc['ImgNumber']), axis=1)]
# train_data.loc[train_data['CST'].isna(), 'preCST'] = 0
train_data.dropna(subset=['CST'], inplace=True, axis=0)
if size is not None:
train_data = train_data.head(size)
if read_img:
train_data['Img'] = train_data['ImgPath'].apply(lambda path: np.array(self.read_image(path, to_float)))
return train_data[['patient ID', 'CST', 'Img']]
else:
return train_data[['patient ID', 'CST', 'ImgPath']]
def get_test_data_cst_all(self, size=None, read_img=False, to_float=False) -> pd.DataFrame:
"""
CST,获取治疗前和治疗后的预测图像,各取size个样本
:param size:
:param read_img:
:param to_float:
:return:
"""
pre_cst = self.get_test_data_pre_cst(size, read_img, to_float)
cst = self.get_test_data_cst(size, read_img, to_float)
pre_cst = pre_cst.rename({'Img': 'feature', 'ImgPath': 'feature'}, axis=1)
pre_cst['type'] = 'preCST'
cst = cst.rename({'Img': 'feature', 'ImgPath': 'feature'}, axis=1)
cst['type'] = 'CST'
cst_data = pd.concat([pre_cst, cst], axis=0, ignore_index=True)
return cst_data[['patient ID', 'type', 'feature']]
def get_test_data_pre_cst(self, size=None, read_img=False, to_float=False) -> pd.DataFrame:
"""
获取治疗前的预测数据 preCST
:param size: 获取样本数量,None为获取全部
:param read_img 是否读取图像,False:不读取,返回'ImgPath';True:读取,返回'Img'
:return: ['patient ID', 'ImgPath'|'Img']
"""
test_data = self.test_data[self.test_data['ImgNumber'].apply(lambda x: x.startswith('10'))]
img_number = test_data.groupby(['patient ID']).count()['ImgNumber'] / 2 + 1000
img_number = img_number.astype(int)
test_data = test_data[
test_data.apply(lambda x: img_number[x.loc['patient ID']] == int(x.loc['ImgNumber']), axis=1)]
if size is not None:
test_data = test_data.head(size)
if read_img:
test_data['Img'] = test_data['ImgPath'].apply(lambda path: np.array(self.read_image(path, to_float)))
return test_data[['patient ID', 'Img']]
else:
return test_data[['patient ID', 'ImgPath']]
def get_test_data_cst(self, size=None, read_img=False, to_float=False) -> pd.DataFrame:
"""
获取治疗前的预测数据 CST
:param size: 获取样本数量,None为获取全部
:param read_img 是否读取图像,False:不读取,返回'ImgPath';True:读取,返回'Img'
:return: ['patient ID', 'ImgPath'|'Img']
"""
test_data = self.test_data[self.test_data['ImgNumber'].apply(lambda x: x.startswith('20'))]
img_number = test_data.groupby(['patient ID']).count()['ImgNumber'] / 2 + 2000
img_number = img_number.astype(int)
test_data = test_data[
test_data.apply(lambda x: img_number[x.loc['patient ID']] == int(x.loc['ImgNumber']), axis=1)]
if size is not None:
test_data = test_data.head(size)
if read_img:
test_data['Img'] = test_data['ImgPath'].apply(lambda path: np.array(self.read_image(path, to_float)))
return test_data[['patient ID', 'Img']]
else:
return test_data[['patient ID', 'ImgPath']]
if __name__ == '__main__':
dataLoad = DataLoad(config.TRAIN_DATA_FILE_NEW, config.TEST_DATA_FILE_NEW)
train_data = dataLoad.get_train_data_cst_all(3, read_img=True)
print(train_data)
print(train_data.shape)
train_data = dataLoad.get_test_data_cst_all(3, read_img=True)
print(train_data)
print(train_data.shape)