-
Notifications
You must be signed in to change notification settings - Fork 0
/
medulla_cortex_extract_gh.py
1584 lines (1227 loc) · 66.8 KB
/
medulla_cortex_extract_gh.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
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import os
from os import path
import numpy as np
np.seterr(divide='ignore', invalid='ignore')
import pandas as pd
import matplotlib
# matplotlib.axes.Axes.plot
# matplotlib.pyplot.plot
# matplotlib.axes.Axes.legend
# matplotlib.pyplot.legend
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.image as mpimg
import scipy
from scipy.ndimage import zoom
from scipy import signal
from scipy.interpolate import interp1d
import scipy.ndimage as ndi
from scipy import ndimage
from sklearn.datasets import load_sample_image
from sklearn.feature_extraction.image import extract_patches_2d
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.metrics import precision_recall_curve
from skimage import morphology
from skimage import measure
from skimage import io, filters
from skimage import data
from skimage.filters import threshold_otsu
from skimage import data, color, io, img_as_float
from sklearn import cluster
from sklearn.feature_extraction import image
from sklearn.cluster import spectral_clustering
import cv2
import math
from PIL import Image, ImageEnhance
import nibabel as nib
import pickle
import funcs_mc
def computeNew4DAfterBasline(im, baseline):
vol4D = np.array(im);
xl = vol4D.shape[0];
yl = vol4D.shape[1];
sl = vol4D.shape[2];
#tl = vol4D.shape[3];
baselineIntensities = np.array(vol4D[:,:,:,1:baseline-1]);
reshapeBaseline = np.reshape(baselineIntensities,[xl*yl*sl,baselineIntensities.shape[3]]);
fid = np.mean(reshapeBaseline,axis=0);
maxMean = max(fid);
newVol4D = np.copy(vol4D);
oldVol4D = np.copy(vol4D);
newVol4D[:,:,:,baseline:] = np.subtract(oldVol4D[:,:,:,baseline:],maxMean)
#newVol4D[:,:,:,:] = np.subtract(oldVol4D[:,:,:,:],maxMean)
return newVol4D
def computeNew4D(im):
vol4D = np.array(im);
xl = vol4D.shape[0];
yl = vol4D.shape[1];
sl = vol4D.shape[2];
tl = vol4D.shape[3];
reshapedVol4D = np.reshape(vol4D,[xl*yl*sl,tl]);
fid = np.mean(reshapedVol4D,axis=0)
diffFid = np.diff(fid,n=1,axis=0)
absDiffFid = np.absolute(diffFid)
maxAbsDiffFid = max(absDiffFid)
jumpTimeSample, = np.where(absDiffFid == maxAbsDiffFid)
jumpTimeSample = max(jumpTimeSample)
# check1 = fid[jumpTimeSample-1]
# check2 = fid[jumpTimeSample]
# check3 = fid[jumpTimeSample+1]
# check4 = vol4D[:,:,:,jumpTimeSample+1:];
difference = fid[jumpTimeSample+1]-fid[jumpTimeSample];
newVol4D = np.copy(vol4D);
oldVol4D = np.copy(vol4D);
# before = vol4D[:,:,1,jumpTimeSample:jumpTimeSample+1]
# mB = np.mean(before);
# after = vol4D[:,:,1,jumpTimeSample:jumpTimeSample+1]-difference;
# mA = np.mean(after);
newVol4D[:,:,:,jumpTimeSample+1:] = np.subtract(oldVol4D[:,:,:,jumpTimeSample+1:],(difference*2))
return newVol4D,difference
def processSingleSubjects_ha(patientName,subjectInfo,baselineTime):
reconMethod='SCAN';
numPC=5;
pca = PCA(n_components=numPC)
dx=64;dy=64;dz=32;
print(patientName)
vol4D00, KM, Box, rkmOri, lkmOri = funcs_mc.readData4(patientName,subjectInfo,reconMethod,1);
copyKM = np.copy(KM);
BoxCopy = np.copy(Box)
#numSlicesVol = vol4D00.shape[2];
# timeRes0=subjectInfo['timeRes'][patientName];
timeRes00 = subjectInfo.loc[subjectInfo['Unnamed: 0'] == patientName, 'timeRes']
index = timeRes00.index.values
index = index[0]
timeRes0 = timeRes00.loc[index]
# timeRes0 = timeRes00[0]
if not isinstance(timeRes0, (int, float)):
timeRes=float(timeRes0.split("[")[1].split(",")[0]);
else:
timeRes=np.copy(timeRes0);
im = np.copy(vol4D00);
medianFind = np.median(im);
if medianFind == 0:
medianFind = 1.0;
im=im[:,:,:,baselineTime:];
im=im/medianFind;
vol4D0 = np.copy(im);
copyVol4D0 = vol4D0
origTimeResVec=np.arange(0,vol4D0.shape[3]*timeRes,timeRes);
resamTimeResVec=np.arange(0,50*6,6); # resample to 50 data point
if origTimeResVec[-1]<resamTimeResVec[-1]:
print(patientName)
Box=Box.astype(int)
kidneyNone=np.nonzero(np.sum(Box,axis=1)==0); #right/left
if kidneyNone[0].size!=0:
kidneyNone=np.nonzero(np.sum(Box,axis=1)==0)[0][0]; #right/left
KM[KM>1]=1;
if Box[0,2]+Box[0,5]+3 >= KM.shape[2] or Box[0,2]+Box[0,5]-3 <0:
Box[:,[3,4,5]]=Box[:,[3,4,5]]+[10,10,0];
else:
Box[:,[3,4,5]]=Box[:,[3,4,5]]+[10,10,3];
# Box[:,[3,4,5]]=Box[:,[3,4,5]]+[15,15,3];
vol4Dvecs=np.reshape(vol4D0, (vol4D0.shape[0]*vol4D0.shape[1]*vol4D0.shape[2], vol4D0.shape[3]));
PCs=pca.fit_transform(vol4Dvecs)
vol4Dpcs=np.reshape(PCs, (vol4D0.shape[0],vol4D0.shape[1],vol4D0.shape[2], numPC))
if kidneyNone!=0:
croppedData4DR_pcs=vol4Dpcs[Box[0,0]-int(Box[0,3]/2):Box[0,0]+int(Box[0,3]/2),\
Box[0,1]-int(Box[0,4]/2):Box[0,1]+int(Box[0,4]/2),\
Box[0,2]-int(Box[0,5]/2):Box[0,2]+int(Box[0,5]/2),:];
croppedData4DR=vol4D0[Box[0,0]-int(Box[0,3]/2):Box[0,0]+int(Box[0,3]/2),\
Box[0,1]-int(Box[0,4]/2):Box[0,1]+int(Box[0,4]/2),\
Box[0,2]-int(Box[0,5]/2):Box[0,2]+int(Box[0,5]/2),:];
KMR=KM[Box[0,0]-int(Box[0,3]/2):Box[0,0]+int(Box[0,3]/2),\
Box[0,1]-int(Box[0,4]/2):Box[0,1]+int(Box[0,4]/2),\
Box[0,2]-int(Box[0,5]/2):Box[0,2]+int(Box[0,5]/2)];
croppedData4DR_pcs=zoom(croppedData4DR_pcs,(dx/np.size(croppedData4DR_pcs,0),dy/np.size(croppedData4DR_pcs,1),dz/np.size(croppedData4DR_pcs,2),1),order=0);
croppedData4DR=zoom(croppedData4DR,(dx/np.size(croppedData4DR,0),dy/np.size(croppedData4DR,1),dz/np.size(croppedData4DR,2),1),order=0);
f_out = interp1d(origTimeResVec,croppedData4DR, axis=3,bounds_error=False,fill_value=0)
croppedData4DR = f_out(resamTimeResVec);
KMR=zoom(KMR,(dx/np.size(KMR,0),dy/np.size(KMR,1),dz/np.size(KMR,2)),order=0);
# croppedData4DR_pcs[KMR<=0] = 0;
# croppedData4DR[KMR<=0] = 0;
if kidneyNone!=1:
croppedData4DL_pcs=vol4Dpcs[Box[1,0]-int(Box[1,3]/2):Box[1,0]+int(Box[1,3]/2),\
Box[1,1]-int(Box[1,4]/2)+10:Box[1,1]+int(Box[1,4]/2)-10,\
Box[1,2]-int(Box[1,5]/2):Box[1,2]+int(Box[1,5]/2),:];
croppedData4DL=vol4D0[Box[1,0]-int(Box[1,3]/2):Box[1,0]+int(Box[1,3]/2),\
Box[1,1]-int(Box[1,4]/2)+10:Box[1,1]+int(Box[1,4]/2)-10,\
Box[1,2]-int(Box[1,5]/2):Box[1,2]+int(Box[1,5]/2),:];
KML=KM[Box[1,0]-int(Box[1,3]/2):Box[1,0]+int(Box[1,3]/2),\
Box[1,1]-int(Box[1,4]/2)+10:Box[1,1]+int(Box[1,4]/2)-10,\
Box[1,2]-int(Box[1,5]/2):Box[1,2]+int(Box[1,5]/2)];
croppedData4DL_pcs=zoom(croppedData4DL_pcs,(dx/np.size(croppedData4DL_pcs,0),dy/np.size(croppedData4DL_pcs,1),dz/np.size(croppedData4DL_pcs,2),1),order=0);
croppedData4DL=zoom(croppedData4DL,(dx/np.size(croppedData4DL,0),dy/np.size(croppedData4DL,1),dz/np.size(croppedData4DL,2),1),order=0);
f_out = interp1d(origTimeResVec,croppedData4DL, axis=3,bounds_error=False,fill_value=0)
croppedData4DL = f_out(resamTimeResVec);
KML=zoom(KML,(dx/np.size(KML,0),dy/np.size(KML,1),dz/np.size(KML,2)),order=0);
# croppedData4DL_pcs[KML<=0] = 0;
# croppedData4DL[KML<=0] = 0;
if kidneyNone==0:
print('No right kidney')
croppedData4DR = [];
croppedData4DR_pcs = [];
KMR = [];
d=np.concatenate((croppedData4DL[np.newaxis,:,:,:,:],croppedData4DL[np.newaxis,:,:,:,:]),axis=0);
dpcs=np.concatenate((croppedData4DL_pcs[np.newaxis,:,:,:,:],croppedData4DL_pcs[np.newaxis,:,:,:,:]),axis=0);
#KM2=np.concatenate((KML[np.newaxis,:,:,:],KML[np.newaxis,:,:,:]),axis=0);
elif kidneyNone==1:
print('No left kidney')
croppedData4DL = [];
croppedData4DL_pcs = [];
KML = [];
d=np.concatenate((croppedData4DR[np.newaxis,:,:,:,:],croppedData4DR[np.newaxis,:,:,:,:]),axis=0);
dpcs=np.concatenate((croppedData4DR_pcs[np.newaxis,:,:,:,:],croppedData4DR_pcs[np.newaxis,:,:,:,:]),axis=0);
#KM2=np.concatenate((KMR[np.newaxis,:,:,:],KMR[np.newaxis,:,:,:]),axis=0);
else:
d=np.concatenate((croppedData4DR[np.newaxis,:,:,:,:],croppedData4DL[np.newaxis,:,:,:,:]),axis=0);
dpcs=np.concatenate((croppedData4DR_pcs[np.newaxis,:,:,:,:],croppedData4DL_pcs[np.newaxis,:,:,:,:]),axis=0);
#KM2=np.concatenate((KMR[np.newaxis,:,:,:],KML[np.newaxis,:,:,:]),axis=0);
#d[d<0]=0;
d = d/d.max()
dpcs = dpcs/dpcs.max()
Box = Box/Box.max()
f_out = interp1d(origTimeResVec,copyVol4D0, axis=3,bounds_error=False,fill_value=0)
copyVol4D0 = f_out(resamTimeResVec);
vol4Dvecs=np.reshape(copyVol4D0, (copyVol4D0.shape[0]*copyVol4D0.shape[1]*copyVol4D0.shape[2], copyVol4D0.shape[3]));
PCs=pca.fit_transform(vol4Dvecs)
#copyVol4Dpcs=np.reshape(PCs, (copyVol4D0.shape[0],copyVol4D0.shape[1],copyVol4D0.shape[2], numPC))
#da0_pcs=copyVol4Dpcs.T/copyVol4Dpcs.max();
#da0=copyVol4D0.T/copyVol4D0.max();
return kidneyNone, croppedData4DL, croppedData4DR, croppedData4DL_pcs, croppedData4DR_pcs, KML,KMR, copyVol4D0, rkmOri, lkmOri, BoxCopy, copyKM
#processSingleSubjects_ha(patientName,subjectInfo,baselineTime):
def to_rgb3a(im):
return np.dstack([im.astype(np.uint8)] * 3)
def to_rgb1(im):
w, h = im.shape
ret = np.empty((w, h, 3), dtype=np.uint8)
ret[:, :, 0] = im
ret[:, :, 1] = im
ret[:, :, 2] = im
return ret
def to_binary(img, lower, upper):
return (lower < img) & (img < upper)
# def mask_color_img(img, mask, color=[0, 255, 255], alpha=0.3):
# out = img.copy()
# img_layer = img.copy()
# img_layer[mask] = color
# out = cv2.addWeighted(img_layer, alpha, out, 1 - alpha, 0, out)
# return(out)
def save_image(array, name):
array = array*255.
fig = plt.figure()
plt.imsave(name, array.astype('uint8'), cmap=matplotlib.cm.gray, vmin=0, vmax=255)
plt.close(fig)
# begin medulla and cortex segmentation #
# array containing 4D volume filenames and
# baselines of respective 4D volumes
subjectNames=np.array([
#['image_name001',5],
#['image_name002',8],
#['image_name007',10],
]);
# extract filenames (pNameList) and (baseLineList)
pNameList = subjectNames[:,0];
baseLineList = subjectNames[:,1];
# path to excel sheet containing temporal information
# about 4D volumes in subjectNames
fileAddress='path-to/subjectDicomInfo_gh.xlsx';
subjectInfo=pd.read_excel(fileAddress, sheet_name = 'subjects',engine='openpyxl');
reconMethod='SCAN';
dx=64;dy=64;dz=32;
# ttSNAP = 23;
# ssSNAP = 16;
for s in range(len(pNameList)):
# for s in range(1):
patientName = pNameList[s];
print('Processing ' + patientName);
baselineTime = baseLineList[s];
kidneyNone, croppedData4DL, croppedData4DR, croppedData4DL_pcs, croppedData4DR_pcs, KML, KMR, copyVol4D0, rkmOri, lkmOri, BoxCopy, copyKM = processSingleSubjects_ha(patientName,subjectInfo,int(baselineTime));
# check if left or right kidney is missing
noLeft = 0;
noRight = 0;
if croppedData4DL == []:
noLeft = 1;
elif croppedData4DR == []:
noRight = 1;
if 1:
if croppedData4DL == []:
croppedData4DL2 = np.copy(croppedData4DR);
croppedData4DL = np.copy(croppedData4DR);
croppedData4DR2 = np.copy(croppedData4DR);
KML = np.copy(KMR);
print('No left kidney')
elif croppedData4DR == []:
croppedData4DR2 = np.copy(croppedData4DL);
croppedData4DR = np.copy(croppedData4DL);
croppedData4DL2 = np.copy(croppedData4DL);
KMR = np.copy(KML);
print('No right kidney')
else:
print('Left and right kidneys exists')
# if kidneyNone!=1 and kidneyNone!=0:
# croppedData4DL2 = np.copy(croppedData4DL);
# croppedData4DR2 = np.copy(croppedData4DR);
gatherRabel = np.zeros(croppedData4DR.shape);
gatherLabel = np.zeros(croppedData4DL.shape);
# keepBin = np.zeros(croppedData4DR.shape);
# keepBinL = np.zeros(croppedData4DL.shape);
keepBinL2 = np.zeros(croppedData4DL.shape);
closedKMR = np.zeros(KMR.shape);
closedKML = np.zeros(KML.shape);
closed_labels = np.zeros(croppedData4DL.shape);
closed_rabels = np.zeros(croppedData4DR.shape);
getRangei = croppedData4DL.shape[2];
first30P = int(0.30*getRangei);
last70P = int(0.70*getRangei);
for tt in range(croppedData4DL.shape[3]):
# for tt in range(7,13):
for ss in range(croppedData4DL.shape[2]):
# for ss in range(15,18):
# working on the left
imageL = croppedData4DL[:,:,ss,tt]
whilei = 1;
while whilei < int(croppedData4DL.shape[3]):
if (imageL.max() == 0 and imageL.min() == 0):
print('came into left kidney')
imageL = croppedData4DL[:,:,ss,(whilei+1)]
else:
break
whilei += 1;
# left kidney thresholding test
imageL1 = np.copy(imageL);
# sort the flattened array
intensitiesL = np.sort(imageL1, axis=None);
intensitiesL = intensitiesL[intensitiesL !=0];
intensitiesLU = np.unique(intensitiesL);
totLenL = len(intensitiesLU);
totLenL25 = int(0.25*totLenL);
if totLenL25 == 0:
totLenL25 = 2;
intensitiesLCopy = np.copy(intensitiesLU)
intensitiesLMins = intensitiesLCopy[0:totLenL25];
minL = np.min(intensitiesLMins);
maxL = np.max(intensitiesLMins);
imageL2C = np.copy(imageL1);
for ii in range(64):
for jj in range(64):
if imageL1[ii,jj] >= minL and imageL1[ii,jj] <= maxL and ss >= first30P and ss <= last70P: # fine-tune
imageL1[ii,jj] = imageL2C[ii,jj] - (minL);
elif imageL1[ii,jj] >= minL and imageL1[ii,jj] <= maxL and (ss < first30P or ss > last70P): # fine-tune
imageL1[ii,jj] = imageL2C[ii,jj] - (minL);
# if tt == ttSNAP and ss == ssSNAP:
# # fig, ((ax0, ax1)) = plt.subplots(nrows=1, ncols=2, figsize=(4, 4))
# # axes = ax0, ax1
# #
# # ax0.imshow(imageL)
# #
# # ax0.set_title('Original slice')
# # ax1.imshow(imageL1)
# # ax1.set_title('Minimum subtracted slice')
# #
# # for ax in axes:
# # ax.axis('off')
# #
# # plt.gray()
# # plt.show()
# # plt.draw()
# plt.figure(figsize=(3, 3))
# plt.imshow(imageL)
# plt.gray()
# plt.title('Original slice')
# #plt.show()
# #plt.draw()
# pathToSave = '/home/usr/Documents/stepsMedCortex' + '/' + patientName + '_' + str(tt) + '_' + str(ss) + '_O'
# #plt.savefig(pathToSave + '.png')
# plt.savefig(pathToSave + '.pdf')
# plt.figure(figsize=(3, 3))
# plt.imshow(imageL1)
# plt.gray()
# plt.title('Minimum subtracted slice')
# #plt.show()
# #plt.draw()
# pathToSave = '/home/usr/Documents/stepsMedCortex' + '/' + patientName + '_' + str(tt) + '_' + str(ss) +'_S'
# #plt.savefig(pathToSave + '.png')
# plt.savefig(pathToSave + '.pdf')
if np.isnan(imageL1).any() == 1:
imageL1Temp = np.copy(imageL);
imageL1 = np.copy(imageL1Temp);
print("checking: left NaN")
if ss < first30P or ss > last70P:
xs1,ys1 = np.where(imageL1 != 0)
imageL20 = np.copy(imageL1)
imageL2 = imageL20[min(xs1):max(xs1)+1,min(ys1):max(ys1)+1]
imageL2 = cv2.pow(imageL2,1.5)
imageL1[min(xs1):max(xs1)+1,min(ys1):max(ys1)+1]= imageL2
imageL3 = imageL1-np.min(np.min(imageL1));
imageL30 = imageL3/np.max(np.max(imageL3));
imageL31 = imageL30.copy();
if np.isnan(imageL31).any() == 1:
imageL31 = np.copy(imageL1);
print("checking: left NaN")
gain = 2; cutOff = 1.5;
xLeft = gain*(cutOff-imageL31)
left_imagex = 1/(1 + np.exp(xLeft));
# if tt==ttSNAP and ss==ssSNAP:
# plt.figure(figsize=(3, 3))
# plt.imshow(imageL31)
# plt.gray()
# plt.title('imageL30 - cv2POW')
# #plt.show()
# #plt.draw()
# pathToSave = '/home/usr/Documents/stepsMedCortex' + '/' + patientName + '_' + str(tt) + '_' + str(ss) +'_L_cv2POW'
# #plt.savefig(pathToSave + '.png')
# plt.savefig(pathToSave + '.pdf')
# plt.figure(figsize=(3, 3))
# plt.imshow(left_imagex)
# plt.gray()
# plt.title('left_imagex - CE')
# #plt.show()
# #plt.draw()
# pathToSave = '/home/usr/Documents/stepsMedCortex' + '/' + patientName + '_' + str(tt) + '_' + str(ss) +'_L_CE'
# #plt.savefig(pathToSave + '.png')
# plt.savefig(pathToSave + '.pdf')
global_thresh = threshold_otsu(left_imagex)
binary_global = left_imagex > global_thresh
binary_global = binary_global.astype(int)
label_im = np.copy(binary_global)
# if tt==ttSNAP and ss==ssSNAP:
# plt.figure(figsize=(3, 3))
# plt.imshow(label_im)
# plt.gray()
# plt.title('label_im')
# #plt.show()
# #plt.draw()
# pathToSave = '/home/usr/Documents/stepsMedCortex' + '/' + patientName + '_' + str(tt) + '_' + str(ss) + '_label_im'
# #plt.savefig(pathToSave + '.png')
# plt.savefig(pathToSave + '.pdf')
if kidneyNone == 1 or kidneyNone == 0:
# right kidney thresholding test
imageR = croppedData4DR2[:,:,ss,tt];
whilei = 1;
while whilei < int(croppedData4DR2.shape[3]):
if (imageR.max() == 0 and imageR.min() == 0):
imageR = croppedData4DR2[:,:,ss,(whilei+1)]
else:
break
whilei += 1;
else:
# right kidney thresholding test
imageR = croppedData4DR[:,:,ss,tt];
whilei = 1;
while whilei < int(croppedData4DR.shape[3]):
if (imageR.max() == 0 and imageR.min() == 0):
imageR = croppedData4DR[:,:,ss,(whilei+1)]
else:
break
whilei += 1;
# if(imageR.max() == 0 and imageR.min() == 0):
# print("came right");
# #imageR[1:32:,1:32] = imageR[1:32:,1:32] + 0.5;
# imageR = croppedData4DR2[:,:,ss,(tt-1)]
#imageR1 = cv2.pow(imageR,1.5)
imageR1 = np.copy(imageR);
#imageR = (255.0 / imageR.max() * (imageR - imageR.min())).astype(np.uint8)
# imageR = imageR-np.min(np.min(imageR));
# imageR = imageR/np.max(np.max(imageR));
# if np.isnan(imageR1).any() == 1:
# imageR1 = imageR;
# print("nan");
# imageR1 = np.copy(imageR);
# intensitiesR = imageR2.flatten();
intensitiesR = np.sort(imageR1, axis=None);
#intensitiesR = sorted_array[::-1];
intensitiesR = intensitiesR[intensitiesR !=0];
intensitiesRU = np.unique(intensitiesR);
totLenR = len(intensitiesRU);
totLenR25 = int(0.25*totLenR);
if totLenR25 == 0:
totLenR25 = 2;
intensitiesRCopy = np.copy(intensitiesRU)
intensitiesRMins = intensitiesRCopy[0:totLenR25];
minR = np.min(intensitiesRMins);
maxR = np.max(intensitiesRMins);
imageR2C = np.copy(imageR1);
for ii in range(64):
for jj in range(64):
if imageR1[ii,jj] >= minR and imageR1[ii,jj] <= maxR and ss >= first30P and ss <= last70P: # fine-tune
imageR1[ii,jj] = imageR2C[ii,jj] - (minR);
elif imageR1[ii,jj] >= minR and imageR1[ii,jj] <= maxR and (ss < first30P or ss > last70P): # fine-tune
imageR1[ii,jj] = imageR2C[ii,jj] - (minR);
# if ss < first30P or ss > last70P:
# imageR1 = cv2.pow(imageR1,1.5)
# if tt==ttSNAP and ss==ssSNAP:
# plt.figure(figsize=(3, 3))
# plt.imshow(imageR)
# plt.gray()
# plt.title('imageR - original')
# #plt.show()
# #plt.draw()
# pathToSave = '/home/usr/Documents/stepsMedCortex' + '/' + patientName + '_' + str(tt) + '_' + str(ss) + '_OR'
# #plt.savefig(pathToSave + '.png')
# plt.savefig(pathToSave + '.pdf')
# plt.figure(figsize=(3, 3))
# plt.imshow(imageR1)
# plt.gray()
# plt.title('imageR1 - subtracted')
# #plt.show()
# #plt.draw()
# pathToSave = '/home/usr/Documents/stepsMedCortex' + '/' + patientName + '_' + str(tt) + '_' + str(ss) + '_SR'
# #plt.savefig(pathToSave + '.png')
# plt.savefig(pathToSave + '.pdf')
if ss < first30P or ss > last70P:
xr1,yr1 = np.where(imageR1 !=0)
imageR11 = np.copy(imageR1)
imageR0 = imageR11[min(xr1):max(xr1)+1,min(yr1):max(yr1)+1]
imageR2 = cv2.pow(imageR0,1.5)
imageR1[min(xr1):max(xr1)+1,min(yr1):max(yr1)+1]= imageR2
#imageR1 = np.copy(imageR);
right_image40 = imageR1-np.min(np.min(imageR1));
right_image41 = right_image40/np.max(np.max(right_image40));
right_image42 = right_image41.copy();
if np.isnan(right_image42).any() == 1:
right_image42 = np.copy(imageR1);
gain = 3; cutOff = 1.5;
yRight = gain*(cutOff-right_image42)
imageR2 = 1/(1 + np.exp(yRight));
# if tt==ttSNAP and ss==ssSNAP:
# plt.figure(figsize=(3, 3))
# plt.imshow(right_image41)
# plt.gray()
# plt.title('right_image41 - cv2POW')
# #plt.show()
# #plt.draw()
# pathToSave = '/home/usr/Documents/stepsMedCortex' + '/' + patientName + '_' + str(tt) + '_' + str(ss) +'_Rcv2POW'
# #plt.savefig(pathToSave + '.png')
# plt.savefig(pathToSave + '.pdf')
# plt.figure(figsize=(3, 3))
# plt.imshow(imageR2)
# plt.gray()
# plt.title('imageR2 - CE')
# #plt.show()
# #plt.draw()
# pathToSave = '/home/usr/Documents/stepsMedCortex' + '/' + patientName + '_' + str(tt) + '_' + str(ss) +'_RCE'
# #plt.savefig(pathToSave + '.png')
# plt.savefig(pathToSave + '.pdf')
global_threshR = threshold_otsu(imageR2);
binary_globalR = imageR2 > global_threshR;
binary_globalR = binary_globalR.astype(int);
rabel_im = np.copy(binary_globalR);
# if tt==ttSNAP and ss==ssSNAP:
# plt.figure(figsize=(3, 3))
# plt.imshow(rabel_im)
# plt.gray()
# plt.title('rabel_im')
# #plt.show()
# #plt.draw()
# pathToSave = '/home/usr/Documents/stepsMedCortex' + '/' + patientName + '_' + str(tt) + '_' + str(ss) +'_rabel_im'
# #plt.savefig(pathToSave + '.png')
# plt.savefig(pathToSave + '.pdf')
# closing the labels
closed_label_im = ndimage.binary_fill_holes(label_im).astype(int);
closed_rabel_im = ndimage.binary_fill_holes(rabel_im).astype(int)
closed_labels[:,:,ss,tt] = closed_label_im;
closed_rabels[:,:,ss,tt] = closed_rabel_im;
# if tt==ttSNAP and ss==ssSNAP:
# plt.figure(figsize=(3, 3))
# plt.imshow(closed_label_im)
# plt.gray()
# plt.title('closed_label_im')
# #plt.show()
# #plt.draw()
# pathToSave = '/home/usr/Documents/stepsMedCortex' + '/' + patientName + '_' + str(tt) + '_' + str(ss) +'_closed_label_im'
# #plt.savefig(pathToSave + '.png')
# plt.savefig(pathToSave + '.pdf')
# plt.figure(figsize=(3, 3))
# plt.imshow(closed_rabel_im)
# plt.gray()
# plt.title('closed_rabel_im')
# #plt.show()
# #plt.draw()
# pathToSave = '/home/usr/Documents/stepsMedCortex' + '/' + patientName + '_' + str(tt) + '_' + str(ss) +'_closed_rabel_im'
# #plt.savefig(pathToSave + '.png')
# plt.savefig(pathToSave + '.pdf')
maskL = KML[:,:,ss]
maskL = maskL.astype(int)
maskR = KMR[:,:,ss];
maskR = maskR.astype(int)
# if tt==ttSNAP and ss==ssSNAP:
# plt.figure(figsize=(3, 3))
# plt.imshow(maskL)
# plt.gray()
# plt.title('maskL')
# #plt.show()
# #plt.draw()
# pathToSave = '/home/usr/Documents/stepsMedCortex' + '/' + patientName + '_' + str(tt) + '_' + str(ss) +'_maskL'
# #plt.savefig(pathToSave + '.png')
# plt.savefig(pathToSave + '.pdf')
# plt.figure(figsize=(3, 3))
# plt.imshow(maskR)
# plt.gray()
# plt.title('maskR')
# #plt.show()
# #plt.draw()
# pathToSave = '/home/usr/Documents/stepsMedCortex' + '/' + patientName + '_' + str(tt) + '_' + str(ss) +'_maskR'
# #plt.savefig(pathToSave + '.png')
# plt.savefig(pathToSave + '.pdf')
# closing the masks
# kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(1,1))
# closedL = cv2.morphologyEx(maskL,cv2.MORPH_OPEN,kernel)
closedL = ndimage.binary_fill_holes(maskL).astype(int)
closedKML[:,:,ss] = closedL;
#closedR = cv2.morphologyEx(maskR,cv2.MORPH_OPEN,kernel)
closedR = ndimage.binary_fill_holes(maskR).astype(int)
closedKMR[:,:,ss] = closedR;
# if tt==ttSNAP and ss==ssSNAP:
# plt.figure(figsize=(3, 3))
# plt.imshow(closedL)
# plt.gray()
# plt.title('closedL - mask')
# #plt.show()
# #plt.draw()
# pathToSave = '/home/usr/Documents/stepsMedCortex' + '/' + patientName + '_' + str(tt) + '_' + str(ss) +'_closed MaskL'
# #plt.savefig(pathToSave + '.png')
# plt.savefig(pathToSave + '.pdf')
# plt.figure(figsize=(3, 3))
# plt.imshow(closedR)
# plt.gray()
# plt.title('closedR - mask')
# #plt.show()
# #plt.draw()
# pathToSave = '/home/usr/Documents/stepsMedCortex' + '/' + patientName + '_' + str(tt) + '_' + str(ss) +'_closed MaskR'
# #plt.savefig(pathToSave + '.png')
# plt.savefig(pathToSave + '.pdf')
# experimenting with k-means clustering
# imageR2[maskR==0]=0.0
# imageR2 = (255.0 / imageR2.max() * (imageR2 - imageR2.min())).astype(np.uint8)
#imageR2 = to_rgb1(imageR2)
# Z = imageR2.reshape((-1,2))
# Z = np.float32(Z)
# criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
# K = 6
# ret,label,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)
# center = np.uint8(center)
# res = center[label.flatten()]
# res2 = res.reshape((imageR2.shape))
# res2 = res2.astype(int)
# keepBin[:,:,ss,tt] = res2;
# closed_label_im = ndimage.binary_fill_holes(label_im).astype(int);
# closed_rabel_im = ndimage.binary_fill_holes(rabel_im).astype(int)
# closed_labels[:,:,ss] = closed_label_im;
# closed_rabels[:,:,ss] = closed_rabel_im;
# experimenting with k-means clustering for the left kidney
# left_imagex = (255.0 / left_imagex.max() * (left_imagex - left_imagex.min())).astype(np.uint8)
# left_imagex2 = np.copy(left_imagex);
# Z1 = left_imagex.reshape((-1,2))
# Z1 = np.float32(Z1)
# criteria1 = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
# K1 = 6
# ret1,label1,center1 = cv2.kmeans(Z1,K1,None,criteria1,10,cv2.KMEANS_RANDOM_CENTERS)
# # re-convert into uint8
# center1 = np.uint8(center1)
# res1 = center1[label1.flatten()]
# res11 = res1.reshape((left_imagex.shape))
# res11 = res11.astype(int)
# res11[maskL == 0]= 0.0
# keepBinL[:,:,ss,tt] = res11;
# left_imagex2[maskL==0]=0.0
# Z2 = left_imagex2.reshape((-1,2))
# Z2 = np.float32(Z2)
# criteria1 = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
# K2 = 6
# ret2,label2,center2=cv2.kmeans(Z2,K2,None,criteria1,10,cv2.KMEANS_RANDOM_CENTERS)
# re-convert into uint8
# center2 = np.uint8(center2)
# res22 = center2[label2.flatten()]
# res22 = res22.reshape((left_imagex2.shape))
# res22x = res22.astype(int)
# res22x = res22x-np.min(np.min(res22x));
# res22x = res22x/np.max(np.max(res22x));
label_im[maskL==0]= 0 # mask out background
rabel_im[maskR==0]= 0 # mask out background
# if tt==ttSNAP and ss==ssSNAP:
# plt.figure(figsize=(3, 3))
# plt.imshow(label_im)
# plt.gray()
# plt.title('label_im - masked back')
# #plt.show()
# #plt.draw()
# pathToSave = '/home/usr/Documents/stepsMedCortex' + '/' + patientName + '_' + str(tt) + '_' + str(ss) +'_label_im_masked'
# #plt.savefig(pathToSave + '.png')
# plt.savefig(pathToSave + '.pdf')
# plt.figure(figsize=(3, 3))
# plt.imshow(rabel_im)
# plt.gray()
# plt.title('rabel_im - masked back')
# #plt.show()
# #plt.draw()
# pathToSave = '/home/usr/Documents/stepsMedCortex' + '/' + patientName + '_' + str(tt) + '_' + str(ss) +'_rabel_im_masked'
# #plt.savefig(pathToSave + '.png')
# plt.savefig(pathToSave + '.pdf')
for ii in range(64):
for jj in range(64):
if maskL[ii,jj] == 1 and label_im[ii,jj] == 0:
label_im[ii,jj] = 2; # medulla
for ii in range(64):
for jj in range(64):
if maskR[ii,jj] == 1 and rabel_im[ii,jj] == 0:
rabel_im[ii,jj] = 2; # medulla
label_im2 = np.copy(label_im);
rabel_im2 = np.copy(rabel_im);
label_im2[closedL==0]= 3 # background changed
rabel_im2[closedR==0]= 3 # background changed
# if tt==ttSNAP and ss==ssSNAP:
# plt.figure(figsize=(3, 3))
# plt.imshow(label_im2)
# plt.gray()
# plt.title('label_im2 - labels')
# #plt.show()
# #plt.draw()
# pathToSave = '/home/usr/Documents/stepsMedCortex' + '/' + patientName + '_' + str(tt) + '_' + str(ss) +'_label_im2'
# #plt.savefig(pathToSave + '.png')
# plt.savefig(pathToSave + '.pdf')
# plt.figure(figsize=(3, 3))
# plt.imshow(rabel_im2)
# plt.gray()
# plt.title('rabel_im2 - labels')
# #plt.show()
# #plt.draw()
# pathToSave = '/home/usr/Documents/stepsMedCortex' + '/' + patientName + '_' + str(tt) + '_' + str(ss) +'_rabel_im2'
# #plt.savefig(pathToSave + '.png')
# plt.savefig(pathToSave + '.pdf')
label_im = np.copy(label_im2);
rabel_im = np.copy(rabel_im2);
# closed_label_im2 = np.copy(closed_label_im)
# closed_label_im2[closed_label_im2<=0]=0
# closed_label_im2[closed_label_im2>=1]=1
#
# closedL2 = np.copy(closedL)
# closedL2[closedL2<=0]=0
# closedL2[closedL2>=1]=1
# uniqueX, countsX = np.unique(label_im, return_counts=True)
# ccX = len(countsX);
#
# if ccX == 4:
# for ii in range(64):
# for jj in range(64):
# if closedL[ii,jj] == 1 and closed_label_im[ii,jj] == 0:
# label_im[ii,jj] = 1;
#
# uniqueXR, countsXR = np.unique(rabel_im, return_counts=True)
# ccXR = len(countsXR);
# if ccXR == 4:
# for ii in range(64):
# for jj in range(64):
# if closedR[ii,jj] == 1 and closed_rabel_im[ii,jj] == 0:
# rabel_im[ii,jj] = 1;
# keepBinL2[:,:,ss,tt] = res22x;
# kernel = np.ones((3,3),np.uint8);
# closedRM = closedKMR[:,:,ss];
# gClosedRM2 = cv2.morphologyEx(closedRM, cv2.MORPH_GRADIENT, kernel)
# rabel_im[gClosedRM2==1]=1;
#
# closedLM = closedKML[:,:,ss];
# gClosedLM2 = cv2.morphologyEx(closedLM, cv2.MORPH_GRADIENT, kernel)
# label_im[gClosedLM2==1]=1;
label_im = ~label_im;
rabel_im = ~rabel_im;
# if tt==ttSNAP and ss==ssSNAP:
# plt.figure(figsize=(3, 3))
# plt.imshow(label_im)
# plt.gray()
# plt.title('label_im - labels inversed')
# #plt.show()
# #plt.draw()
# pathToSave = '/home/usr/Documents/stepsMedCortex' + '/' + patientName + '_' + str(tt) + '_' + str(ss) +'_label_iv'
# #plt.savefig(pathToSave + '.png')
# plt.savefig(pathToSave + '.pdf')
# plt.figure(figsize=(3, 3))
# plt.imshow(rabel_im)
# plt.gray()
# plt.title('rabel_im - labels inversed')
# #plt.show()
# #plt.draw()
# pathToSave = '/home/usr/Documents/stepsMedCortex' + '/' + patientName + '_' + str(tt) + '_' + str(ss) +'_rabel_iv'
# #plt.savefig(pathToSave + '.png')
# plt.savefig(pathToSave + '.pdf')
gatherLabel[:,:,ss,tt] = label_im
gatherRabel[:,:,ss,tt] = rabel_im
gatherLabel[gatherLabel == -4]= 0
gatherLabel[gatherLabel == -3]= 1
gatherLabel[gatherLabel == -2]= 2
gatherLabel[gatherLabel == -1]= 3
gatherRabel[gatherRabel == -4]= 0
gatherRabel[gatherRabel == -3]= 1
gatherRabel[gatherRabel == -2]= 2
gatherRabel[gatherRabel == -1]= 3
gatherRabel2 = np.copy(gatherRabel)
gatherLabel2 = np.copy(gatherLabel)
testLeft = np.zeros(KML.shape)
testRight = np.zeros(KMR.shape)
"""
#### experiment: new find ratio area and number of medulla over time
for slaX in range(1):
#for sla in range(gatherLabel.shape[2]):
sla = 16
numCels = []; numCelsR = [];
ratios = []; ratiosR = [];
for stt in range(gatherLabel.shape[3]):
lSlice = np.copy(gatherLabel2[:,:,int(sla),int(stt)]);
lSlice2 = np.copy(gatherLabel2[:,:,int(sla),int(stt)]);
lSlice3 = np.copy(gatherLabel2[:,:,int(sla),int(stt)]);
rSlice = np.copy(gatherRabel2[:,:,int(sla),int(stt)]);
rSlice2 = np.copy(gatherRabel2[:,:,int(sla),int(stt)]);
rSlice3 = np.copy(gatherRabel2[:,:,int(sla),int(stt)]);