-
Notifications
You must be signed in to change notification settings - Fork 9
/
tkintercorestat.py
2430 lines (2237 loc) · 92.2 KB
/
tkintercorestat.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 numpy
#import math
#import gdal #geospatial data abstraction
#import osr
#import ogr #simple features library, vector data access, pawrt of GDAL
#from pyproj import Proj, transform
#foldername='../drondata/alfalfa'
import csv
#import time
from skimage.feature import corner_fast,corner_peaks,corner_harris,corner_shi_tomasi
#import cv2
#import matplotlib.pyplot as plt
global lastlinecount,misslabel
from sklearn.cluster import KMeans
#from sklearn.mixture import GaussianMixture as GMM
from scipy.stats import shapiro
from scipy import ndimage as ndi
from skimage.segmentation import watershed
from skimage.feature import peak_local_max
import lm_method
tinyareas=[]
colortable={}
colormatch={}
labellist=[]
elesize=[]
avgarea=None
greatareas=[]
exceptions=[]
miniarea=0
# residual related components
oldM=None
oldstd=None
oldeigenvector=None
oldcoef=None
oldintercept=None
class node:
def __init__(self,i,j):
self.i=i
self.j=j
self.label=0
self.check=False
def renamelabels(area):
res=area
unique=numpy.unique(res)
i=202501.0
for uni in unique[1:]:
res=numpy.where(res==uni,i,res)
i+=1.0
unique = numpy.unique(res)
i=1.0
for uni in unique[1:]:
res=numpy.where(res==uni,i,res)
i+=1.0
return res
def get_residual(labeledarea,all=False): #for divideloop and combineloop
unique,counts=numpy.unique(labeledarea,return_counts=True)
unique=unique[1:]
counts=counts[1:]
hist=dict(zip(unique,counts))
sortedlist=sorted(hist,key=hist.get,reverse=True)
lenlist=[]
widlist=[]
data=[]
itemlist=[]
for item in sortedlist:
itemlocs=numpy.where(labeledarea==item)
ulx,uly=min(itemlocs[1]),min(itemlocs[0])
rlx,rly=max(itemlocs[1]),max(itemlocs[0])
itemlength=rly-uly
itemwidth=rlx-ulx
lenlist.append(itemlength)
widlist.append(itemwidth)
data.append(hist[item])
itemlist.append(item)
if all==False:
# residual,area=lm_method.lm_method_fit(lenlist,widlist,data,oldM,oldstd,oldeigenvector,oldcoef,oldintercept)
residual,area=lm_method.lm_method_fit(lenlist,widlist,data,oldcoef,oldintercept)
lenwid=list(residual)
data=list(area)
areahist={}
residualhist={}
for i in range(len(itemlist)):
item=itemlist[i]
itemarea=data[i]
itemresdisual=lenwid[i]
areahist.update({item:itemarea})
residualhist.update({item:itemresdisual})
return areahist,residualhist
else:
# residual,area,M,tablestd,pcabands,coef,intercept=lm_method.lm_method(lenlist,widlist,data,all)
residual,area,coef,intercept=lm_method.lm_method(lenlist,widlist,data,all)
lenwid=list(residual)
data=list(area)
areahist={}
residualhist={}
# pcalist=list(pcabands)
for i in range(len(itemlist)):
item=itemlist[i]
itemarea=data[i]
itemresdisual=lenwid[i]
areahist.update({item:itemarea})
residualhist.update({item:itemresdisual})
# return areahist,residualhist,M,tablestd,pcabands,coef,intercept
return areahist,residualhist,coef,intercept
def combinecrops(area,subarea,i,ele,ulx,uly,rlx,rly):
print('combinecrops: i='+str(i)+' ele='+str(ele))
localarea=numpy.asarray(area)
if i==ele:
return localarea
if i<ele:
localarea=numpy.where(localarea==ele,i,localarea)
else:
subarealocs=numpy.where(area==i)
subulx,subuly=min(subarealocs[1]),min(subarealocs[0])
subrlx,subrly=max(subarealocs[1]),max(subarealocs[0])
subarea=numpy.where(subarea==i,ele,subarea)
try:
localarea[uly:rly+1,ulx:rlx+1]=subarea
except:
localarea[subuly:subrly+1,subulx:subrlx+1]=subarea
unique = numpy.unique(localarea)
print(unique)
return localarea
def sortline(linelist,midx,midy,linenum,labellist=labellist,elesize=elesize):
localy={}
localx={}
for ele in linelist:
localy.update({ele:midy[ele]})
localx.update({ele:midx[ele]})
i=0
for ele in sorted(localx,key=localx.get):
try:
tempcolordict={ele:labellist[i+sum(elesize[:linenum])]}
colortable.update(tempcolordict)
print(tempcolordict)
i+=1
except IndexError:
pass
def relabel(area,elesize=elesize,labellist=labellist):
unique=numpy.unique(area).tolist()
unique=unique[1:]
midx={}
midy={}
colortable.clear()
misslabel=0
colorarea = numpy.zeros(area.shape)
colorarea = colorarea.tolist()
for ele in unique:
eleloc=numpy.where(area==ele)
ylist=eleloc[0].tolist()
xlist=eleloc[1].tolist()
y=ylist[int(len(ylist)/2)]
x=xlist[int(len(xlist)/2)]
txdict={ele:x}
tydict={ele:y}
midx.update(txdict)
midy.update(tydict)
linelist=[]
linecount=0
if len(elesize)!=0:
for ele in sorted(midy,key=midy.get):
linelist.append(ele)
print(ele,midy[ele],midx[ele])
#if len(linelist)%23==0:
if linecount<len(elesize):
if len(linelist)%elesize[linecount]==0:
#sortline(linelist,midx,midy,linecount-1)
sortline(linelist,midx,midy,linecount,labellist=labellist,elesize=elesize)
linelist[:]=[]
#colcount=1
linecount+=1
print(linecount)
misslabel=0
continue
else:
misslabel=elesize[linecount]-len(linelist)
if misslabel==0:
misslabel=sum(elesize[:linecount])-sum(elesize)
else:
misslabel=0
misslabel-=len(linelist)
for i in range(len(area)):
for j in range(len(area[0])):
if area[i][j] != 0:
try:
colorarea[i][j] = colormatch[colortable[area[i][j]]]
except KeyError:
pass
colorarea = numpy.asarray(colorarea)
else:
i=1
colorarea=numpy.zeros(area.shape)
for ele in sorted(midy,key=midy.get):
tempdict={ele:i}
colortable.update(tempdict)
elelocs=numpy.where(area==ele)
colorarea[elelocs]=i
i+=1
print(colortable)
if misslabel==0 and len(labellist)>0:
misslabel=len(labellist)-len(unique)
return colorarea,misslabel,colortable
def labelgapnp(area):
x=[0,-1,-1,-1,0,1,1,1]
y=[1,1,0,-1,-1,-1,0,1]
nodearea=numpy.where(area!=0)
labelnum=2
nodelist={}
for k in range(len(nodearea[0])):
tnode=node(nodearea[0][k],nodearea[1][k])
tempdict={(nodearea[0][k],nodearea[1][k]):tnode}
nodelist.update(tempdict)
nodekeys=list(nodelist.keys())
for key in nodekeys:
if nodelist[key].check==False:
nodelist[key].check=True
nodelist[key].label=labelnum
offspringlist=[]
for m in range(len(y)):
i=key[0]
j=key[1]
if (i+y[m],j+x[m]) in nodelist:
newkey=(i+y[m],j+x[m])
if nodelist[newkey].check==False:
nodelist[newkey].check=True
offspringlist.append(newkey)
if len(offspringlist)==0:
nodelist[key].label=0
while(len(offspringlist)>0):
currnodekey=offspringlist.pop(0)
curri=currnodekey[0]
currj=currnodekey[1]
nodelist[currnodekey].label=labelnum
for m in range(len(y)):
if (curri+y[m],currj+x[m]) in nodelist:
if nodelist[(curri+y[m],currj+x[m])].check==False:
nodelist[(curri+y[m],currj+x[m])].check=True
offspringlist.append((curri+y[m],currj+x[m]))
labelnum+=1
area=numpy.zeros(area.shape)
for key in nodekeys:
area[key[0],key[1]]=nodelist[key].label
return area
def tempbanddenoicecommentout(area,labelname):
subarea=numpy.copy(area)
tempsubarea=subarea/labelname
newtempsubarea=numpy.where(tempsubarea!=1.,0,1)
newsubarea=boundarywatershed(newtempsubarea,1,'inner')
labelunique,labcounts=numpy.unique(newsubarea,return_counts=True)
labelunique=labelunique.tolist()
if len(labelunique)>2:
hist=dict(zip(labelunique[1:],labcounts[1:]))
sortedlabels=sorted(hist,key=hist.get,reverse=True)
copylabels=numpy.copy(area)
copylabels=numpy.where(copylabels==labelname,0,copylabels)
toplabels=numpy.where(newsubarea==sortedlabels[0])
copylabels[toplabels]=labelname
return copylabels
else:
return subarea
def tempbanddenoice(area,labelname,benchmark):
print(benchmark)
gaps={}
last=None
copyarea=numpy.copy(area)
nodearea=numpy.where(copyarea==labelname)
print(nodearea)
yloc=nodearea[0].tolist()
for i in range(len(yloc)):
curry=yloc[i]
if last==None:
last=curry
continue
else:
diff=curry-last
if diff>1:
gaps.update({i:diff})
last=curry
#sortedgaps=sorted(gaps,key=gaps.get,reverse=True)
print(gaps)
keys=list(gaps.keys())
if len(keys)>0:
gap=keys[0]
noisey=nodearea[0][gap:]
noisex=nodearea[1][gap:]
noiselocs=(noisey,noisex)
print(noiselocs)
copyarea[noiselocs]=0
return copyarea
else:
return area
def labelgap(area):
x=[0,-1,-1,-1,0,1,1,1]
y=[1,1,0,-1,-1,-1,0,1]
nodearea=area.tolist()
labelnum=2
nodelist=[]
for i in range(len(nodearea)):
tempnodelist=[]
for j in range(len(nodearea[0])):
tnode=node(i,j)
tempnodelist.append(tnode)
nodelist.append(tempnodelist)
for i in range(len(nodelist)):
for j in range(len(nodelist[i])):
if nodelist[i][j].check==False and nodearea[i][j]!=0:
nodelist[i][j].check=True
#print('nodelisti,j='+str(i)+','+str(j))
nodelist[i][j].label=labelnum
offspringlist=[]
for k in range(len(y)):
if i+y[k]<len(nodelist) and i+y[k]>=0 and j+x[k]<len(nodelist[i]) and j+x[k]>=0:
if nodelist[i+y[k]][j+x[k]].check==False and nodearea[i+y[k]][j+x[k]]!=0:
nodelist[i+y[k]][j+x[k]].check=True
#print('nodelist i+ym,j+xn='+str(i+y[m])+','+str(j+x[n]))
offspringlist.append(nodelist[i+y[k]][j+x[k]])
if len(offspringlist)==0:
nodelist[i][j].label=0
while(len(offspringlist)>0):
currnode=offspringlist.pop(0)
curri=currnode.i
currj=currnode.j
nodelist[curri][currj].label=labelnum
for k in range(len(y)):
if curri+y[k]>=0 and curri+y[k]<len(nodelist) and currj+x[k]<len(nodelist[i]) and currj+x[k]>=0:
if nodelist[curri+y[k]][currj+x[k]].check==False and nodearea[curri+y[k]][currj+x[k]]!=0:
nodelist[curri+y[k]][currj+x[k]].check=True
#print('nodelist i+ym,j+xn='+str(i+y[m])+','+str(j+x[n]))
offspringlist.append(nodelist[curri+y[k]][currj+x[k]])
labelnum+=1
for i in range(len(nodearea)):
for j in range(len(nodearea[0])):
nodearea[i][j]=nodelist[i][j].label
area=numpy.asarray(nodearea)
return area
def get_boundary(area):
contentlocs=numpy.where(area!=0)
boundaryres=numpy.zeros(area.shape)
x=[0,-1,-1,-1,0,1,1,1]
y=[1,1,0,-1,-1,-1,0,1]
for m in range(len(contentlocs[0])):
for k in range(len(y)):
i=contentlocs[0][m]+y[k]
j=contentlocs[1][m]+x[k]
if i>=0 and i<area.shape[0] and j>=0 and j<area.shape[1]:
if area[i,j]==0:
boundaryres[contentlocs[0][m],contentlocs[1][m]]=1
break
#localarea=area
#distance=ndi.distance_transform_edt(localarea)
#boundaryres=numpy.zeros(localarea.shape)
#boundaryres=numpy.where(distance==1.0,1,boundaryres)
return boundaryres
def get_boundaryloc(area,labelvalue):
contentlocs=numpy.where(area==labelvalue)
boundaryloc=([],[])
x = [0, -1, -1, -1, 0, 1, 1, 1]
y = [1, 1, 0, -1, -1, -1, 0, 1]
for m in range(len(contentlocs[0])):
for k in range(len(y)):
i = contentlocs[0][m] + y[k]
j = contentlocs[1][m] + x[k]
if i >= 0 and i < area.shape[0] and j >= 0 and j < area.shape[1]:
if area[i, j] == 0:
boundaryloc[0].append(contentlocs[0][m])
boundaryloc[1].append(contentlocs[1][m])
break
return boundaryloc
def boundarywatershedcoin(area,segbondtimes,boundarytype):
if avgarea is not None and numpy.count_nonzero(area)<avgarea/2:
return area
x=[0,-1,-1,-1,0,1,1,1]
y=[1,1,0,-1,-1,-1,0,1]
#x=[0,-1,0,1]
#y=[1,0,-1,0]
#
#temptif=cv2.GaussianBlur(area,(3,3),0,0,cv2.BORDER_DEFAULT)
#areaboundary=cv2.Laplacian(area,cv2.CV_8U,ksize=5)
#plt.imshow(areaboundary)
#areaboundary=find_boundaries(area,mode=boundarytype)
#areaboundary=get_boundary(area)
#areaboundary=areaboundary*1 #boundary = 1's, nonboundary=0's
#temparea=area-areaboundary
arealabels=labelgapnp(area)
unique, counts = numpy.unique(arealabels, return_counts=True)
if segbondtimes>1:
return area
if(len(unique)>2):
res=arealabels
res=numpy.asarray(res)-1
res=numpy.where(res<0,0,res)
return res
else:
return area
def label_boundary(res,areaboundary,arealabels):
area=res.copy()
x=[0,-1,-1,-1,0,1,1,1]
y=[1,1,0,-1,-1,-1,0,1]
boundaryspots=numpy.where(areaboundary==1)
leftboundaryspots=[]
for i in range(len(boundaryspots[0])):
leftboundaryspots.append((boundaryspots[0][i],boundaryspots[1][i]))
unique, counts = numpy.unique(arealabels, return_counts=True)
# leftboundary_y=leftboundaryspots[0].tolist()
# leftboundary_x=leftboundaryspots[1].tolist()
for uni in unique[1:]:
labelboundaryloc=get_boundaryloc(arealabels,uni)
for m in range(len(labelboundaryloc[0])):
for k in range(len(y)):
li=labelboundaryloc[0][m]+y[k]
lj=labelboundaryloc[1][m]+x[k]
if li>=0 and li<area.shape[0] and lj>=0 and lj<area.shape[1]:
if area[li,lj]==1:
area[li,lj]=uni
bindex=leftboundaryspots.index((li,lj))
leftboundaryspots.pop(bindex)
while len(leftboundaryspots)>0:
for loc in leftboundaryspots:
bi=loc[0]
bj=loc[1]
maxlabel=1
for k in range(len(y)):
ni=bi+y[k]
nj=bj+x[k]
if ni>=0 and ni<area.shape[0] and nj>=0 and nj<area.shape[1]:
if area[ni,nj]>maxlabel:
maxlabel=area[ni,nj]
area[bi,bj]=maxlabel
#locindex=leftboundaryspots.index(loc)
leftboundaryspots.pop(0)
return area
def boundarywatershed_origin(area,itertime=20):
if avgarea is not None and numpy.count_nonzero(area)<avgarea/2:
return area
x=[0,-1,-1,-1,0,1,1,1]
y=[1,1,0,-1,-1,-1,0,1]
#x=[0,-1,0,1]
#y=[1,0,-1,0]
#
#temptif=cv2.GaussianBlur(area,(3,3),0,0,cv2.BORDER_DEFAULT)
#areaboundary=cv2.Laplacian(area,cv2.CV_8U,ksize=5)
#plt.imshow(areaboundary)
#areaboundary=find_boundaries(area,mode=boundarytype)
# areaboundary=get_boundary(area)
#areaboundary=areaboundary*1 #boundary = 1's, nonboundary=0's
# temparea=area-areaboundary
arealabels=labelgapnp(area)
unique, counts = numpy.unique(arealabels, return_counts=True)
# if segbondtimes>=itertime:
# return area
if(len(unique)>2):
res=arealabels#+areaboundary
# leftboundaryspots=numpy.where(areaboundary==1)
# res=label_boundary(res,areaboundary,arealabels)
# res=numpy.asarray(res)-1
# res=numpy.where(res<0,0,res)
return res
else:
temparea=numpy.copy(area)
newarea=boundarywatershed(temparea,1,'inner')
res=newarea
# leftboundaryspots=numpy.where(res==1)
# res=label_boundary(res,areaboundary,newarea)
# res=numpy.asarray(res)/2
# res=numpy.where(res<1,0,res)
return res
def boundarywatershed(area,segbondtimes,boundarytype,itertime=20): #area = 1's
if avgarea is not None and numpy.count_nonzero(area)<avgarea/2:
return area
x=[0,-1,-1,-1,0,1,1,1]
y=[1,1,0,-1,-1,-1,0,1]
#x=[0,-1,0,1]
#y=[1,0,-1,0]
#
#temptif=cv2.GaussianBlur(area,(3,3),0,0,cv2.BORDER_DEFAULT)
#areaboundary=cv2.Laplacian(area,cv2.CV_8U,ksize=5)
#plt.imshow(areaboundary)
#areaboundary=find_boundaries(area,mode=boundarytype)
areaboundary=get_boundary(area)
#areaboundary=areaboundary*1 #boundary = 1's, nonboundary=0's
temparea=area-areaboundary
arealabels=labelgapnp(temparea)
unique, counts = numpy.unique(arealabels, return_counts=True)
#if(segbondtimes>=itertime) or len(unique)==1:
if len(unique)==1:
return area
if(len(unique)>2):
res=arealabels+areaboundary
# leftboundaryspots=numpy.where(areaboundary==1)
res=label_boundary(res,areaboundary,arealabels)
res=numpy.asarray(res)-1
res=numpy.where(res<0,0,res)
return res
else:
newarea=boundarywatershed(temparea,segbondtimes+1,boundarytype)*2
res=newarea+areaboundary
# leftboundaryspots=numpy.where(res==1)
res=label_boundary(res,areaboundary,newarea)
res=numpy.asarray(res)/2
res=numpy.where(res<1,0,res)
return res
def manualboundarywatershed(area,avgarea):
'''
if numpy.count_nonzero(area)<avgarea/2:
return area
x=[0,-1,-1,-1,0,1,1,1]
y=[1,1,0,-1,-1,-1,0,1]
leftboundaryspots=numpy.where(area==1)
pixelcount=1
label=1
for k in range(len(leftboundaryspots[0])):
i=leftboundaryspots[0][k]
j=leftboundaryspots[1][k]
area[i][j]=label
pixelcount+=1
if pixelcount==int(avgarea):
pixelcount=1
label+=1
unique,count=numpy.unique(area,return_counts=True)
for i in range(1,len(count)):
if count[i]<avgarea/2:
area=numpy.where(area==unique[i],unique[i-1],area)
'''
maskpara=0.5
possiblecount=round(numpy.count_nonzero(area)/avgarea)
print('possiblecount',possiblecount)
distance=ndi.distance_transform_edt(area)
masklength=int((avgarea*maskpara)**0.5)-1
#masklength=int(((avgarea*maskpara)**0.5)/2)
local_maxi=peak_local_max(distance,indices=False,footprint=numpy.ones((masklength,masklength)),labels=area)
markers=ndi.label(local_maxi)[0]
unique=numpy.unique(markers)
print(len(unique)-1)
# while(len(unique)-1>possiblecount):
# maskpara+=0.1
# masklength=int((avgarea*maskpara)**0.5)-1
# print('masklength',masklength)
# #masklength=int(((avgarea*maskpara)**0.5)/2)
# local_maxi=peak_local_max(distance,indices=False,footprint=numpy.ones((masklength,masklength)),labels=area)
# markers=ndi.label(local_maxi)[0]
# unique=numpy.unique(markers)
# print('uniquelength',len(unique)-1)
# lastlength=0
while(len(unique)-1<possiblecount and masklength>1):
maskpara-=0.1
try:
masklength=int((avgarea*maskpara)**0.5)-1
#masklength=int(((avgarea*maskpara)**0.5)/2)
except:
masklength=lastlength
local_maxi=peak_local_max(distance,indices=False,footprint=numpy.ones((masklength,masklength)),labels=area)
markers=ndi.label(local_maxi)[0]
print('masklength',masklength)
break
if masklength<0:
masklength=2
#masklength=1
lastlength=masklength
try:
print('masklength recover',masklength)
local_maxi=peak_local_max(distance,indices=False,footprint=numpy.ones((masklength,masklength)),labels=area)
except:
maskpara+=0.1
masklength=int((avgarea*maskpara)**0.5)-1
local_maxi=peak_local_max(distance,indices=False,footprint=numpy.ones((masklength,masklength)),labels=area)
# markers=ndi.label(local_maxi)[0]
# break
markers=ndi.label(local_maxi)[0]
unique=numpy.unique(markers)
print('manual unique',unique)
localarea=watershed(-distance,markers,mask=area)
return localarea
def cornerdivide(area,greatareas):
global exceptions
unique, counts = numpy.unique(area, return_counts=True)
hist=dict(zip(unique,counts))
del hist[0]
meanpixel=sum(counts[1:])/len(counts[1:])
bincounts=numpy.bincount(counts[1:])
#meanpixel=numpy.argmax(bincounts)
while len(greatareas)>0:
topkey=greatareas.pop(0)
if topkey not in exceptions:
locs=numpy.where(area==topkey)
ulx,uly=min(locs[1]),min(locs[0])
rlx,rly=max(locs[1]),max(locs[0])
subarea=area[uly:rly+1,ulx:rlx+1]
edges=get_boundary(subarea)
tempsubarea=subarea/topkey
newtempsubarea=numpy.where(tempsubarea!=1.,0,1)
antitempsubarea=numpy.where((tempsubarea!=1.) & (tempsubarea!=0),tempsubarea,0)
antitempsubarea=antitempsubarea*topkey.astype(int)
corners=corner_peaks(corner_harris(edges),min_distance=1)
times=len(locs[0])/meanpixel
roundthreshold=0.6
times=round(times-roundthreshold+0.5)
cornerpoints=[]
for item in corners:
if tempsubarea[item[0],item[1]]==0:
cornerpoints.append(item)
print(cornerpoints)
def manualdivide(area,greatareas):
global exceptions
unique, counts = numpy.unique(area, return_counts=True)
hist=dict(zip(unique,counts))
del hist[0]
for i in range(len(unique)):
if unique[i] in greatareas:
counts.pop(i)
meanpixel=sum(counts[1:])/len(counts[1:])
bincounts=numpy.bincount(counts[1:])
#meanpixel=numpy.argmax(bincounts)
countseed=numpy.asarray(counts[1:])
stdpixel=numpy.std(countseed)
sortedkeys=list(sorted(hist,key=hist.get,reverse=True))
#dimension=getdimension(area)
#values=list(dimension.values())
#meandimension=sum(values)/len(values)
#stddimension=numpy.std(numpy.array(values))
#updimention=min(meandimension+stddimension,meandimension*1.25)
#lowdimention=meandimension-stddimension
while len(greatareas)>0:
topkey=greatareas.pop(0)
#if topkey not in dimension:
# continue
#topkeydimension=dimension[topkey]
if topkey not in exceptions:
locs=numpy.where(area==topkey)
ulx,uly=min(locs[1]),min(locs[0])
rlx,rly=max(locs[1]),max(locs[0])
subarea=area[uly:rly+1,ulx:rlx+1]
subarea=subarea.astype(float)
tempsubarea=subarea/topkey
newtempsubarea=numpy.where(tempsubarea!=1.,0,1).astype(int)
antitempsubarea=numpy.where((tempsubarea!=1.) & (tempsubarea!=0),subarea,0)
#antitempsubarea=antitempsubarea*topkey.astype(int)
times=len(locs[0])/meanpixel
#roundthreshold=0.6
#times=round(times-roundthreshold+0.5)
averagearea=len(locs[0])/times
#newsubarea=manualboundarywatershed(newtempsubarea,meanpixel+stdpixel)#,windowsize)
newsubarea=manualboundarywatershed(newtempsubarea,averagearea)
labelunique,labcounts=numpy.unique(newsubarea,return_counts=True)
labelunique=labelunique.tolist()
labcounts=labcounts.tolist()
#origin=labcounts[1]
#if topkeydimension<updimention:
# for i in range(2,len(labcounts)):
# if labcounts[i]<origin/2:
# labelunique.pop(i)
# labcounts.pop(i)
# exceptions.append(topkey)
#else:
if len(labelunique)>2:
keepdevide=True
newlabelavgarea=sum(labcounts[1:])/len(labcounts[1:])
#if newlabelavgarea<=lowrange:
#if newlabelavgarea<=avgarea:
# keepdevide=False
#if keepdevide:
newsubarea=newsubarea*topkey
newlabel=labelunique.pop(-1)
maxlabel=area.max()
add=1
while newlabel>1:
newsubarea=numpy.where(newsubarea==topkey*newlabel,maxlabel+add,newsubarea)
print('new label: '+str(maxlabel+add))
newlabelcount=len(numpy.where(newsubarea==maxlabel+add)[0].tolist())
#if newlabelcount>=meanpixel and newlabelcount<uprange:
#if (maxlabel+add) not in exceptions: 07102019
#exceptions.append(maxlabel+add) 07102019
print('add '+'label: '+str(maxlabel+add)+' count='+str(newlabelcount))
newlabel=labelunique.pop(-1)
add+=1
newsubarea=newsubarea+antitempsubarea.astype(int)
area[uly:rly+1,ulx:rlx+1]=newsubarea
#labels=relabel(labels)
#unique, counts = numpy.unique(area, return_counts=True)
#for i in range(len(unique)):
# if unique[i] in greatareas:
# counts.pop(i)
#hist=dict(zip(unique,counts))
#del hist[0]
#print('hist length='+str(len(counts)-1))
#print('max label='+str(area.max()))
#sortedkeys=list(sorted(hist,key=hist.get,reverse=True))
#meanpixel=sum(counts[1:])/len(counts[1:])
#meanpixel=numpy.argmax(bincounts)
#countseed=numpy.asarray(counts[1:])
#stdpixel=numpy.std(countseed)
#uprange=meanpixel+minisigma*stdpixel
#lowrange=meanpixel-minisigma*stdpixel
#zscore=(hist[topkey]-meanpixel)/stdpixel
#dimension=getdimension(area)
#values=list(dimension.values())
#meandimension=sum(values)/len(values)
#stddimension=numpy.std(numpy.array(values))
#updimention=min(meandimension+stddimension,meandimension*1.25)
def divideloop(area,misslabel,avgarea,layers,par):
global greatareas
#while hist[topkey]>meanpixel*1.1 and topkey not in exceptions:
unique, counts = numpy.unique(area, return_counts=True)
hist=dict(zip(unique,counts))
del hist[0]
#print('hist length='+str(len(counts)-1))
#print('max label='+str(labels.max()))
meanpixel=sum(counts[1:])/len(counts[1:])
bincounts=numpy.bincount(counts[1:])
#meanpixel=numpy.argmax(bincounts)
countseed=numpy.asarray(counts[1:])
stdpixel=numpy.std(countseed)
leftsigma=(meanpixel-min(countseed))/stdpixel
rightsigma=(max(countseed)-meanpixel)/stdpixel
if leftsigma>rightsigma:
minisigma=min(leftsigma,rightsigma)-0.5
else:
minisigma=min(leftsigma,rightsigma)
uprange=meanpixel+minisigma*stdpixel
lowrange=meanpixel-minisigma*stdpixel
sortedkeys=list(sorted(hist,key=hist.get,reverse=True))
topkey=sortedkeys.pop(0)
#while len(sortedkeys)>0 and hist[topkey]>uprange and topkey in exceptions:
halflength=0.5*len(sortedkeys)
zscore=(hist[topkey]-meanpixel)/stdpixel
#while len(sortedkeys)>halflength and hist[topkey]>uprange:
maxareacount=misslabel
greatareas=[]
#while maxareacount>0: #or hist[topkey]>min(avgarea*1.25,uprange):
#while len(sortedkeys)>halflength and zscore>=2.5:
while len(sortedkeys)>0:
print('topkey='+str(topkey),hist[topkey])
#if topkey not in greatareas and topkey not in exceptions:
if topkey!=0 and hist[topkey]>uprange and topkey not in exceptions:
#topkey=sortedkeys.pop(0)
#for i in sorted(hist,key=hist.get,reverse=True):
#if j<firstfivepercent:
#if hist[topkey]>meanpixel*1.5 and topkey not in exceptions:
locs=numpy.where(area==topkey)
ulx,uly=min(locs[1]),min(locs[0])
rlx,rly=max(locs[1]),max(locs[0])
width=rlx-ulx
height=rly-uly
#windowsize=min(width,height)
#dividen=2
subarea=area[uly:rly+1,ulx:rlx+1]
tempsubarea=subarea/topkey
newtempsubarea=numpy.where(tempsubarea!=1.,0,1)
antitempsubarea=numpy.where((tempsubarea!=1.) & (tempsubarea!=0),subarea,0)
#antitempsubarea=antitempsubarea*topkey.astype(int)
newsubarea=boundarywatershed(newtempsubarea,1,'inner')#,windowsize)
#newsubarea=manualboundarywatershed(newtempsubarea,meanpixel)
labelunique,labcounts=numpy.unique(newsubarea,return_counts=True)
labelunique=labelunique.tolist()
if len(labelunique)>2:
keepdevide=True
newlabelavgarea=sum(labcounts[1:])/len(labcounts[1:])
#if newlabelavgarea<=lowrange:
#if newlabelavgarea<=avgarea:
# keepdevide=False
#if keepdevide:
newsubarea=newsubarea*topkey
newlabel=labelunique.pop(-1)
maxlabel=area.max()
add=1
while newlabel>1:
newsubarea=numpy.where(newsubarea==topkey*newlabel,maxlabel+add,newsubarea)
print('new label: '+str(maxlabel+add))
newlabelcount=len(numpy.where(newsubarea==maxlabel+add)[0].tolist())
#if newlabelcount>=meanpixel and newlabelcount<uprange:
#if (maxlabel+add) not in exceptions: 07102019
#if (maxlabel+add) not in exceptions: 07102019
#exceptions.append(maxlabel+add) 07102019
print('add '+'label: '+str(maxlabel+add)+' count='+str(newlabelcount))
newlabel=labelunique.pop(-1)
add+=1
newsubarea=newsubarea+antitempsubarea.astype(int)
area[uly:rly+1,ulx:rlx+1]=newsubarea
#labels=relabel(labels)
unique, counts = numpy.unique(area, return_counts=True)
hist=dict(zip(unique,counts))
del hist[0]
print('hist length='+str(len(counts)-1))
print('max label='+str(area.max()))
sortedkeys=list(sorted(hist,key=hist.get,reverse=True))
meanpixel=sum(counts[1:])/len(counts[1:])
bincounts=numpy.bincount(counts[1:])
#meanpixel=numpy.argmax(bincounts)
countseed=numpy.asarray(counts[1:])
stdpixel=numpy.std(countseed)
leftsigma=(meanpixel-min(countseed))/stdpixel
rightsigma=(max(countseed)-meanpixel)/stdpixel
minisigma=min(leftsigma,rightsigma)
uprange=meanpixel+minisigma*stdpixel
lowrange=meanpixel-minisigma*stdpixel
#zscore=(hist[topkey]-meanpixel)/stdpixel
topkey=sortedkeys.pop(0)
maxareacount-=1
else:
if hist[topkey]>uprange:
if topkey not in greatareas:
greatareas.append(topkey)
topkey=sortedkeys.pop(0)
else:
break
else:
topkey=sortedkeys.pop(0)
#zscore=(hist[topkey]-meanpixel)/stdpixel
#maxareacount-=1
return area
def combineloop(area,misslabel,par):
global tinyareas
localarea=numpy.asarray(area)
unique, counts = numpy.unique(localarea, return_counts=True)
hist=dict(zip(unique,counts))
del hist[0]
#print('hist length='+str(len(counts)-1))
#print('max label='+str(labels.max()))
meanpixel=sum(counts[1:])/len(counts[1:])
bincounts=numpy.bincount(counts[1:])
#meanpixel=numpy.argmax(bincounts)
countseed=numpy.asarray(counts[1:])
stdpixel=numpy.std(countseed)
leftsigma=(meanpixel-min(countseed))/stdpixel
rightsigma=(max(countseed)-meanpixel)/stdpixel
minisigma=min(leftsigma,rightsigma)
uprange=meanpixel+minisigma*stdpixel
lowrange=meanpixel-minisigma*stdpixel
sortedkeys=list(sorted(hist,key=hist.get))
topkey=sortedkeys.pop(0)
tinyareas=[]
while misslabel<=0:# or gocombine==True:
#while hist[topkey]<max(avgarea*0.75,lowrange):
#topkey=sortedkeys.pop(0)
print('uprange='+str(uprange))
print('lowrange='+str(lowrange))
print('combine part')
i=topkey
print(i,hist[i])
if i not in tinyareas and hist[i]<lowrange:
#if hist[i]<meanpixel:
locs=numpy.where(localarea==i)
ulx,uly=min(locs[1]),min(locs[0])
rlx,rly=max(locs[1]),max(locs[0])
width=rlx-ulx
height=rly-uly
#windowsize=min(width,height)
#dividen=2
subarea=localarea[uly:rly+1,ulx:rlx+1]
tempsubarea=subarea/i
#four direction searches
stop=False
poscombines=[]
for j in range(1,11):
up_unique=[]
down_unique=[]
left_unique=[]
right_unique=[]
maxlabel={}
tempcombines=[]
if uly-j>=0 and stop==False and len(up_unique)<2:
uparray=localarea[uly-j:uly,ulx:rlx+1]
up_unique=numpy.unique(uparray)
for x in range(len(up_unique)):
if up_unique[x]>0:
tempdict={up_unique[x]:hist[up_unique[x]]}
maxlabel.update(tempdict)
if rly+j<localarea.shape[0] and stop==False and len(down_unique)<2:
downarray=localarea[rly+1:rly+j+1,ulx:rlx+1]
down_unique=numpy.unique(downarray)
for x in range(len(down_unique)):
if down_unique[x]>0:
tempdict={down_unique[x]:hist[down_unique[x]]}
maxlabel.update(tempdict)
if ulx-j>=0 and stop==False and len(left_unique)<2:
leftarray=localarea[uly:rly+1,ulx-j:ulx]
left_unique=numpy.unique(leftarray)
for x in range(len(left_unique)):
if left_unique[x]>0:
tempdict={left_unique[x]:hist[left_unique[x]]}
maxlabel.update(tempdict)
if ulx+j<localarea.shape[1] and stop==False and len(right_unique)<2:
rightarray=localarea[uly:rly+1,rlx+1:rlx+j+1]
right_unique=numpy.unique(rightarray)
for x in range(len(right_unique)):
if right_unique[x]>0:
tempdict={right_unique[x]:hist[right_unique[x]]}
maxlabel.update(tempdict)
print(up_unique,down_unique,left_unique,right_unique)
tempcombines.append(up_unique)
tempcombines.append(down_unique)
tempcombines.append(left_unique)
tempcombines.append(right_unique)
poscombines.append(tempcombines)
tinylist=[]
while(len(poscombines)>0 and stop==False):
top=poscombines.pop(0)
tinylist.append(top)
toplist=[]
for j in range(4):
toparray=top[j]
topunique=numpy.unique(toparray)
for ele in topunique:
toplist.append(ele)
toplist=numpy.array(toplist)
combunique,combcount=numpy.unique(toplist,return_counts=True)
toplist=dict(zip(combunique,combcount))
toplist=list(sorted(toplist,key=toplist.get,reverse=True))
while(len(toplist)>0):
top=toplist.pop(0)
if top!=0:
topcount=hist[top]
if hist[i]+topcount>lowrange and hist[i]+topcount<uprange:
localarea=combinecrops(localarea,subarea,i,top,ulx,uly,rlx,rly)
stop=True
if len(poscombines)==0 and stop==False: #combine to the closest one
tinyareas.append(topkey)
#misslabel+=1
unique, counts = numpy.unique(localarea, return_counts=True)
hist=dict(zip(unique,counts))
sortedkeys=list(sorted(hist,key=hist.get))
meanpixel=sum(counts[1:])/len(counts[1:])
bincounts=numpy.bincount(counts[1:])
#meanpixel=numpy.argmax(bincounts)
countseed=numpy.asarray(counts[1:])
stdpixel=numpy.std(countseed)
leftsigma=(meanpixel-min(countseed))/stdpixel
rightsigma=(max(countseed)-meanpixel)/stdpixel
minisigma=min(leftsigma,rightsigma)
uprange=meanpixel+minisigma*stdpixel
lowrange=meanpixel-minisigma*stdpixel
#if stop==False and leftsigma>rightsigma:
# localarea=numpy.where(localarea==topkey,0,localarea)
topkey=sortedkeys.pop(0)
print('hist leng='+str(len(unique[1:])))
else:
if len(sortedkeys)>0:
topkey=sortedkeys.pop(0)
else:
misslabel+=1
return localarea