-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
599 lines (533 loc) · 27.7 KB
/
utils.py
File metadata and controls
599 lines (533 loc) · 27.7 KB
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
import csv
import os.path
from torch.nn.init import xavier_normal_, kaiming_normal_, constant_, normal_
import torch.nn as nn
from models import norm as mynn
import numpy as np
import SimpleITK as sitk
import evaluation_atm_22 as atm22
from skimage.morphology import skeletonize,cube,closing
from skimage import measure
def weights_init(net, init_type='normal'):
"""
:param m: modules of CNNs
:return: initialized modules
"""
def init_func(m):
# if isinstance(m, nn.Conv3d) or isinstance(m, nn.Linear):
if isinstance(m, nn.Conv3d) :
if init_type == 'normal':
normal_(m.weight.data)
elif init_type == 'xavier':
xavier_normal_(m.weight.data)
else:
kaiming_normal_(m.weight.data)
if m.bias is not None:
constant_(m.bias.data, 0)
elif isinstance(m, nn.BatchNorm3d):
# 对于归一化层,通常初始化权重为1,偏置为0
constant_(m.weight, 1)
constant_(m.bias, 0)
print('initialize network with %s' % init_type)
net.apply(init_func) # apply the initialization function <init_func>
return
def combineImage(predList,valpath,inputLabelPath,skepath,epoch=0,datasetflag="",featureNum=3):
"""
:param predList:
列表元素: tempDics = {"name": name, "info": labelInfo, "sub": subVolumList}
info:
info=[]
info.append(labels.GetSize())
info.append(labels.GetOrigin())
info.append(labels.GetSpacing())
info.append(labels.GetDirection())
subVolumList = [siglabel, subPosition, prelabeledges]
subPosition为裁剪区域在原图中的位置,原图为numpy数组类型zyx subposition 列表内为张量
:return:
"""
if isinstance(predList, list):
if not os.path.exists(valpath):
os.makedirs(valpath)
errpath = os.path.join(valpath,"valmetrics.csv")
with open(errpath, "a") as csvout:
writer = csv.writer(csvout)
writer.writerow(["epoch: ", epoch])
row = ["index", 'totalMetrics', 'TD', 'BD', 'DCS', "accuracy", 'sensitive', 'specificity']
writer.writerow(row)
csvout.close()
metricsList = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
numoflist = len(predList)
for i in range(len(predList)):
infolist = predList[i]['info']
labelnp = np.zeros(infolist[0][::-1])
# edgenp = np.zeros(infolist[0][::-1])
tagnp = np.zeros(infolist[0][::-1])
subVolum = predList[i]['sub']
for j in range(int(len(subVolum)/featureNum)):
ip = subVolum[j*featureNum+1]
labelnp[ip[0]:ip[1],ip[2]:ip[3],ip[4]:ip[5]] += subVolum[j*featureNum]
# edgenp[ip[0]:ip[1],ip[2]:ip[3],ip[4]:ip[5]] += subVolum[j*featureNum+2]
tagnp[ip[0]:ip[1],ip[2]:ip[3],ip[4]:ip[5]] +=1
if np.all(tagnp != 0):
labelnp1 = labelnp / tagnp
# edgenp1 = edgenp / tagnp
# labeladdedgenp1 = labelnp1 + edgenp1
# return labelnp
labelnp = (labelnp1 > 0.5).astype(dtype='uint8')
# edgenp = (edgenp1 > 0.5).astype(dtype='uint8')
# labeladdedgenp = (labeladdedgenp1 > 0.5).astype(dtype='uint8')
# labelnp = (labelnp > 0.8).astype(dtype='uint8')
# 提取最大连通分量
labelnp = maxConnect(labelnp)
labelimage = sitk.GetImageFromArray(labelnp)
labelimage1 = sitk.GetImageFromArray(labelnp1)
# edgeimage = sitk.GetImageFromArray(edgenp)
# edgeimage1 = sitk.GetImageFromArray(edgenp1)
# labeladdedgeImage = sitk.GetImageFromArray(labeladdedgenp)
# labeladdedgeImage1 = sitk.GetImageFromArray(labeladdedgenp1)
# a = [t.item() for t in infolist[1]]
labelimage.SetOrigin([t.item() for t in infolist[1]])
labelimage.SetSpacing([t.item() for t in infolist[2]])
labelimage.SetDirection([t.item() for t in infolist[3]])
labelimage1.CopyInformation(labelimage)
# edgeimage.CopyInformation(labelimage)
# edgeimage1.CopyInformation(labelimage)
# labeladdedgeImage.CopyInformation(labelimage)
# labeladdedgeImage1.CopyInformation(labelimage)
# if not os.path.exists(valpath):
# os.makedirs(valpath)
path = os.path.join(valpath,f"ATM_{predList[i]['name']}_pre.nii.gz")#'./result/val/'+predList[i][name] +"nii.gz"
path1 = os.path.join(valpath,
f"ATM_{predList[i]['name']}_pre1.nii.gz") # './result/val/'+predList[i][name] +"nii.gz"
sitk.WriteImage(labelimage,path)
sitk.WriteImage(labelimage1, path1)
# pathedge = os.path.join(valpath,
# f"ATM_{predList[i]['name']}_predge.nii.gz") # './result/val/'+predList[i][name] +"nii.gz"
# pathedge1 = os.path.join(valpath,
# f"ATM_{predList[i]['name']}_predge1.nii.gz") # './result/val/'+predList[i][name] +"nii.gz"
# # sitk.WriteImage(edgeimage, pathedge)
# # sitk.WriteImage(edgeimage1, pathedge1)
# pathedgeadd = os.path.join(valpath,
# f"ATM_{predList[i]['name']}_predgeadd.nii.gz") # './result/val/'+predList[i][name] +"nii.gz"
# pathedgeadd1 = os.path.join(valpath,
# f"ATM_{predList[i]['name']}_predgeadd1.nii.gz") # './result/val/'+predList[i][name] +"nii.gz"
# sitk.WriteImage(labeladdedgeImage, pathedgeadd)
# sitk.WriteImage(labeladdedgeImage1, pathedgeadd1)
#计算metrics
if os.path.exists(inputLabelPath):
if datasetflag=="ATM22":
path = os.path.join(inputLabelPath,f"ATM_{predList[i]['name']}_0000_label.nii.gz")
parsepath = os.path.join(skepath, f"ATM_{predList[i]['name']}_0000__parse.nii.gz")
elif datasetflag=="Aeropath":
path = os.path.join(inputLabelPath, f"{predList[i]['name']}_CT_HR_labels.nii.gz")
parsepath = os.path.join(skepath, f"{predList[i]['name']}_CT_HR__parse.nii.gz")
elif datasetflag=='Parse22':
path = os.path.join(inputLabelPath, f"{predList[i]['name']}_label.nii.gz")
parsepath = os.path.join(skepath, f"{predList[i]['name']}_parse.nii.gz")
# path = os.path.join(inputLabelPath,f"ATM_{predList[i]['name']}_0000_label.nii.gz")
# path = os.path.join(inputLabelPath, f"{predList[i]['name']}_CT_HR_labels.nii.gz")
inputLabelImage = sitk.ReadImage(path)
inputLabelImage_np = sitk.GetArrayFromImage(inputLabelImage)
inputLabelSke_np = skeletonize(inputLabelImage_np)
# parsepath = os.path.join(skepath,f"ATM_{predList[i]['name']}_0000__parse.nii.gz")
# parsepath = os.path.join(skepath, f"{predList[i]['name']}_CT_HR__parse.nii.gz")
parseImage = sitk.ReadImage(parsepath)
parse_np = sitk.GetArrayFromImage(parseImage)
td = atm22.tree_length_calculation(labelnp,inputLabelSke_np)
_,_,bd = atm22.branch_detected_calculation(labelnp,parse_np,inputLabelSke_np)
# bd=0
dcs = atm22.dice_coefficient_score_calculation(labelnp,inputLabelImage_np)
pre = atm22.precision_calculation(labelnp,inputLabelImage_np)
sen = atm22.sensitivity_calculation(labelnp,inputLabelImage_np)
spe = atm22.specificity_calculation(labelnp,inputLabelImage_np)
totalMetrics = 0.25 * td + 0.25 * bd + 0.25 * dcs + 0.25 * pre
with open(errpath, "a") as csvout:
writer = csv.writer(csvout)
row = [predList[i]['name'], totalMetrics, td, bd, dcs, pre, sen, spe]
writer.writerow(row)
csvout.close()
metricsList[0] = metricsList[0] + totalMetrics
metricsList[1] = metricsList[1] + td
metricsList[2] = metricsList[2] + bd
metricsList[3] = metricsList[3] + dcs
metricsList[4] = metricsList[4] + pre
metricsList[5] = metricsList[5] + sen
metricsList[6] = metricsList[6] + spe
else:
print('input label path is not existing')
else:
print(f"未完成完整图像")
if numoflist >0:
with open(errpath, 'a') as csvout:
writer = csv.writer(csvout)
row = [item / numoflist for item in metricsList]
row.insert(0,'meanMetrics: ')
writer.writerow(row)
csvout.close()
else:
print('预测结果列表为空')
else:
print("预测子区域结果未存入列表")
def combineImage_featuremap(predList,valpath,inputLabelPath,skepath,epoch=0,datasetflag="",featureNum=3):
"""
:param predList:
列表元素: tempDics = {"name": name, "info": labelInfo, "sub": subVolumList}
info:
info=[]
info.append(labels.GetSize())
info.append(labels.GetOrigin())
info.append(labels.GetSpacing())
info.append(labels.GetDirection())
subVolumList = [siglabel, subPosition, prelabeledges]
subPosition为裁剪区域在原图中的位置,原图为numpy数组类型zyx subposition 列表内为张量
:return:
"""
if isinstance(predList, list):
if not os.path.exists(valpath):
os.makedirs(valpath)
errpath = os.path.join(valpath,"valmetrics.csv")
with open(errpath, "a") as csvout:
writer = csv.writer(csvout)
writer.writerow(["epoch: ", epoch])
row = ["index", 'totalMetrics', 'TD', 'BD', 'DCS', "accuracy", 'sensitive', 'specificity']
writer.writerow(row)
csvout.close()
metricsList = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
numoflist = len(predList)
for i in range(len(predList)):
infolist = predList[i]['info']
labelnp = np.zeros(infolist[0][::-1])
edgenp = np.zeros(infolist[0][::-1])
if featureNum>3:
mainnp = np.zeros(infolist[0][::-1])
dec0np = np.zeros(infolist[0][::-1])
catfnp = np.zeros(infolist[0][::-1])
tagnp = np.zeros(infolist[0][::-1])
subVolum = predList[i]['sub']
for j in range(int(len(subVolum)/featureNum)):
ip = subVolum[j*featureNum+1]
labelnp[ip[0]:ip[1],ip[2]:ip[3],ip[4]:ip[5]] += subVolum[j*featureNum]
edgenp[ip[0]:ip[1],ip[2]:ip[3],ip[4]:ip[5]] += subVolum[j*featureNum+2]
if featureNum>3:
mainnp[ip[0]:ip[1], ip[2]:ip[3], ip[4]:ip[5]] += subVolum[j * featureNum+3]
dec0np[ip[0]:ip[1], ip[2]:ip[3], ip[4]:ip[5]] += subVolum[j * featureNum + 4]
catfnp[ip[0]:ip[1], ip[2]:ip[3], ip[4]:ip[5]] += subVolum[j * featureNum + 5]
tagnp[ip[0]:ip[1],ip[2]:ip[3],ip[4]:ip[5]] +=1
if np.all(tagnp != 0):
labelnp1 = labelnp / tagnp
edgenp1 = edgenp / tagnp
labeladdedgenp1 = labelnp1 + edgenp1
# return labelnp
labelnp = (labelnp1 > 0.5).astype(dtype='uint8')
edgenp = (edgenp1 > 0.5).astype(dtype='uint8')
labeladdedgenp = (labeladdedgenp1 > 0.5).astype(dtype='uint8')
# labelnp = (labelnp > 0.8).astype(dtype='uint8')
# 提取最大连通分量
labelnp = maxConnect(labelnp)
labelimage = sitk.GetImageFromArray(labelnp)
labelimage1 = sitk.GetImageFromArray(labelnp1)
edgeimage = sitk.GetImageFromArray(edgenp)
edgeimage1 = sitk.GetImageFromArray(edgenp1)
labeladdedgeImage = sitk.GetImageFromArray(labeladdedgenp)
labeladdedgeImage1 = sitk.GetImageFromArray(labeladdedgenp1)
# a = [t.item() for t in infolist[1]]
labelimage.SetOrigin([t.item() for t in infolist[1]])
labelimage.SetSpacing([t.item() for t in infolist[2]])
labelimage.SetDirection([t.item() for t in infolist[3]])
labelimage1.CopyInformation(labelimage)
edgeimage.CopyInformation(labelimage)
edgeimage1.CopyInformation(labelimage)
labeladdedgeImage.CopyInformation(labelimage)
labeladdedgeImage1.CopyInformation(labelimage)
if not os.path.exists(valpath):
os.makedirs(valpath)
path = os.path.join(valpath,f"ATM_{predList[i]['name']}_pre.nii.gz")#'./result/val/'+predList[i][name] +"nii.gz"
path1 = os.path.join(valpath,
f"ATM_{predList[i]['name']}_pre1.nii.gz") # './result/val/'+predList[i][name] +"nii.gz"
sitk.WriteImage(labelimage,path)
sitk.WriteImage(labelimage1, path1)
pathedge = os.path.join(valpath,
f"ATM_{predList[i]['name']}_predge.nii.gz") # './result/val/'+predList[i][name] +"nii.gz"
pathedge1 = os.path.join(valpath,
f"ATM_{predList[i]['name']}_predge1.nii.gz") # './result/val/'+predList[i][name] +"nii.gz"
# sitk.WriteImage(edgeimage, pathedge)
# sitk.WriteImage(edgeimage1, pathedge1)
pathedgeadd = os.path.join(valpath,
f"ATM_{predList[i]['name']}_predgeadd.nii.gz") # './result/val/'+predList[i][name] +"nii.gz"
pathedgeadd1 = os.path.join(valpath,
f"ATM_{predList[i]['name']}_predgeadd1.nii.gz") # './result/val/'+predList[i][name] +"nii.gz"
# sitk.WriteImage(labeladdedgeImage, pathedgeadd)
# sitk.WriteImage(labeladdedgeImage1, pathedgeadd1)
if featureNum>3:
mainnp = mainnp / tagnp
dec0np = dec0np / tagnp
catfnp = catfnp /tagnp
mainImage = sitk.GetImageFromArray(mainnp)
dec0Image = sitk.GetImageFromArray(dec0np)
catfImage = sitk.GetImageFromArray(catfnp)
mainImage.CopyInformation(labelimage)
dec0Image.CopyInformation(labelimage)
catfImage.CopyInformation(labelimage)
pathmain = os.path.join(valpath,f"ATM_{predList[i]['name']}_main.nii.gz")
pathdec0 = os.path.join(valpath,f"ATM_{predList[i]['name']}_dec0.nii.gz")
pathdcatf = os.path.join(valpath,f"ATM_{predList[i]['name']}_catf.nii.gz")
sitk.WriteImage(mainImage,pathmain)
sitk.WriteImage(dec0Image,pathdec0)
sitk.WriteImage(catfImage,pathdcatf)
#计算metrics
if os.path.exists(inputLabelPath):
if datasetflag=="ATM22":
path = os.path.join(inputLabelPath,f"ATM_{predList[i]['name']}_0000_label.nii.gz")
parsepath = os.path.join(skepath, f"ATM_{predList[i]['name']}_0000__parse.nii.gz")
elif datasetflag=="Aeropath":
path = os.path.join(inputLabelPath, f"{predList[i]['name']}_CT_HR_labels.nii.gz")
parsepath = os.path.join(skepath, f"{predList[i]['name']}_CT_HR__parse.nii.gz")
# path = os.path.join(inputLabelPath,f"ATM_{predList[i]['name']}_0000_label.nii.gz")
# path = os.path.join(inputLabelPath, f"{predList[i]['name']}_CT_HR_labels.nii.gz")
inputLabelImage = sitk.ReadImage(path)
inputLabelImage_np = sitk.GetArrayFromImage(inputLabelImage)
inputLabelSke_np = skeletonize(inputLabelImage_np)
# parsepath = os.path.join(skepath,f"ATM_{predList[i]['name']}_0000__parse.nii.gz")
# parsepath = os.path.join(skepath, f"{predList[i]['name']}_CT_HR__parse.nii.gz")
parseImage = sitk.ReadImage(parsepath)
parse_np = sitk.GetArrayFromImage(parseImage)
td = atm22.tree_length_calculation(labelnp,inputLabelSke_np)
_,_,bd = atm22.branch_detected_calculation(labelnp,parse_np,inputLabelSke_np)
# bd=0
dcs = atm22.dice_coefficient_score_calculation(labelnp,inputLabelImage_np)
pre = atm22.precision_calculation(labelnp,inputLabelImage_np)
sen = atm22.sensitivity_calculation(labelnp,inputLabelImage_np)
spe = atm22.specificity_calculation(labelnp,inputLabelImage_np)
totalMetrics = 0.25 * td + 0.25 * bd + 0.25 * dcs + 0.25 * pre
with open(errpath, "a") as csvout:
writer = csv.writer(csvout)
row = [predList[i]['name'], totalMetrics, td, bd, dcs, pre, sen, spe]
writer.writerow(row)
csvout.close()
metricsList[0] = metricsList[0] + totalMetrics
metricsList[1] = metricsList[1] + td
metricsList[2] = metricsList[2] + bd
metricsList[3] = metricsList[3] + dcs
metricsList[4] = metricsList[4] + pre
metricsList[5] = metricsList[5] + sen
metricsList[6] = metricsList[6] + spe
else:
print('input label path is not existing')
else:
print(f"未完成完整图像")
if numoflist >0:
with open(errpath, 'a') as csvout:
writer = csv.writer(csvout)
row = [item / numoflist for item in metricsList]
row.insert(0,'meanMetrics: ')
writer.writerow(row)
csvout.close()
else:
print('预测结果列表为空')
else:
print("预测子区域结果未存入列表")
def maxConnect(preLabel):
# 闭运算
# structEle = cube(2)
# preLabel = closing(preLabel, structEle)
# 对分割结果进行标记,为每个连通分量分配一个不同的标签
labels = measure.label(preLabel, connectivity=preLabel.ndim)
# 计算每个连通分量的属性,包括面积(对于2D是像素数,对于3D是体素数)
props = measure.regionprops(labels)
# 获取图像的中心坐标
center = np.array(preLabel.shape) / 2.0
# 计算最短轴的长度
shortest_axis_length = min(preLabel.shape)
# 设置阈值为最短轴长度的四分之一
threshold = shortest_axis_length / 2.0
# 初始化最大面积和对应的标签
max_area = 0
largest_component_label = None
# 遍历每个连通分量
for prop in props:
# 计算当前连通分量质心与图像中心的距离
centroid = prop.centroid
distance = np.linalg.norm(center - centroid)
# 检查是否在距离阈值内并且面积是否最大
if distance <= threshold and prop.area > max_area:
# if distance <= threshold and prop.area > max_area:
max_area = prop.area
largest_component_label = prop.label
# 如果没有找到符合条件的连通分量,则返回原始数组
if largest_component_label is None:
return preLabel
# # 找到面积最大的连通分量的标签(假设面积越大代表连通分量越大)
# if props: # 确保有连通分量存在
# # largest_component_label = max(props, key=lambda x: x.area)['label']
# #第二大连通分量
# # 按面积排序连通分量
# sorted_regions = sorted(props, key=lambda region: region.area, reverse=True)
# largest_component_label = sorted_regions[1].label
# else:
# return preLabel # 如果没有连通分量,返回原数组
# 仅保留最大连通分量
largest_component = (labels == largest_component_label)
# if np.any(largest_component):
# print("1")
# else:
# print("0")
return largest_component.astype(dtype="uint8")
def calLoss(totallossList,lossnum =4, valpath=None,epoch = 0):
"""
:param
totallossList
tempDics = {"name":name[0], "loss":sloss, "sampleNum":1}
sloss为所有损失的列表
:return:
"""
if isinstance(totallossList, list):
print("val epoch ")
if not os.path.exists(valpath):
os.makedirs(valpath)
errpath = os.path.join(valpath,"valerror.csv")
allLossVal = [0.0 for _ in range(lossnum)]
tempLossVal = [0.0 for _ in range(lossnum)]
with open(errpath, "a") as csvout:
writer = csv.writer(csvout)
writer.writerow(["epoch: ", epoch])
row = ["index", 'totalloss', 'celoss', 'diceloss', 'edgeloss']
writer.writerow(row)
csvout.close()
for i in range(len(totallossList)):
loss = totallossList[i]["loss"]
if loss:
for j in range(lossnum):
tempLossVal[j] = loss[j].item()/totallossList[i]["sampleNum"]
print(f"{totallossList[i]['name']}: totalloss {tempLossVal}")
with open(errpath, "a") as csvout:
writer = csv.writer(csvout)
writer.writerow([totallossList[i]['name'], tempLossVal])
csvout.close()
else:
print(f"{totallossList[i]['name']}未获得损失")
break
for j in range(lossnum):
allLossVal[j] = allLossVal[j] + tempLossVal[j]
for i in range(lossnum):
allLossVal[i] = allLossVal[i] /len(totallossList)
print(f"val loss:{allLossVal}")
with open(errpath, "a") as csvout:
writer = csv.writer(csvout)
writer.writerow(['valloss', allLossVal])
csvout.close()
return allLossVal
# if lossnum == 4:
# with open(errpath, "a") as csvout:
# writer = csv.writer(csvout)
# writer.writerow(["epoch: ", epoch])
# row = ["index", 'totalloss', 'celoss', 'diceloss', 'edgeloss']
# writer.writerow(row)
# csvout.close()
# allLoss=[0.0, 0.0, 0.0, 0.0]
# for i in range(len(totallossList)):
#
# loss = totallossList[i]["loss"]
#
# tloss = 0.0
# ce = 0.0
# dice = 0.0
# edge = 0.0
#
# num = int(len(loss)/lossnum)
# if num > 0:
# for j in range(num):
# tloss += loss[j*lossnum].item()
# ce += loss[j*lossnum+1].item()
# dice += loss[j * lossnum + 2].item()
# edge += loss[j * lossnum + 3].item()
# tloss /= num
# ce /= num
# dice /= num
# edge /= num
# print(f"{totallossList[i]['name']}: totalloss {tloss}、celoss {ce}、diceloss {dice}、edgeloss{edge}")
# with open(errpath, "a") as csvout:
# writer = csv.writer(csvout)
# writer.writerow([totallossList[i]['name'], tloss, ce, dice, edge])
# csvout.close()
# else:
# print(f"{totallossList[i]['name']}未获得损失")
# allLoss[0] += tloss
# allLoss[1] += ce
# allLoss[2] += dice
# allLoss[3] += edge
#
# allLoss[0] /= len(totallossList)
# allLoss[1] /= len(totallossList)
# allLoss[2] /= len(totallossList)
# allLoss[3] /= len(totallossList)
# print(f"val loss:{allLoss}")
# with open(errpath, "a") as csvout:
# writer = csv.writer(csvout)
# writer.writerow(['valloss', allLoss])
# csvout.close()
#
# return allLoss
# elif lossnum == 3:
# with open(errpath, "a") as csvout:
# writer = csv.writer(csvout)
# row = ["index", 'totalloss', 'celoss', 'diceloss']
# writer.writerow(row)
# csvout.close()
# allLoss=[0.0, 0.0, 0.0]
# for i in range(len(totallossList)):
#
# loss = totallossList[i]["loss"]
#
# tloss = 0.0
# ce = 0.0
# dice = 0.0
# # edge = 0.0
#
# num = int(len(loss)/lossnum)
# if num > 0:
# for j in range(num):
# tloss += loss[j*lossnum].item()
# ce += loss[j*lossnum+1].item()
# dice += loss[j * lossnum + 2].item()
# # edge += loss[j * lossnum + 3].item()
# tloss /= num
# ce /= num
# dice /= num
# # edge /= num
# print(f"{totallossList[i]['name']}: totalloss {tloss}、celoss {ce}、diceloss {dice}")
# with open(errpath, "a") as csvout:
# writer = csv.writer(csvout)
# writer.writerow([totallossList[i]['name'], tloss, ce, dice])
# csvout.close()
# else:
# print(f"{totallossList[i]['name']}未获得损失")
# allLoss[0] += tloss
# allLoss[1] += ce
# allLoss[2] += dice
# # allLoss[3] += edge
#
# allLoss[0] /= len(totallossList)
# allLoss[1] /= len(totallossList)
# allLoss[2] /= len(totallossList)
# # allLoss[3] /= len(totallossList)
# print(f"val loss:{allLoss}")
# with open(errpath, "a") as csvout:
# writer = csv.writer(csvout)
# writer.writerow(['valloss', allLoss])
# csvout.close()
#
# return allLoss
else:
print("预测子区域的损失结果未存入列表")
if __name__ == "__main__":
# errpath = os.path.join("./result", "error.csv")
# a = [0,0,0]
# with open(errpath, "a") as csvout:
# writer = csv.writer(csvout)
# writer.writerow(['name', a])
# csvout.close()
inputLabelPath =''
if os.path.exists(inputLabelPath):
print("cunzai")
else:
print("bucunzai")