-
Notifications
You must be signed in to change notification settings - Fork 0
/
skeleton_analyze.py
executable file
·2026 lines (1248 loc) · 63.5 KB
/
skeleton_analyze.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
"""
Version: 1.5
Summary: compute the cross section plane based on 3d model
Author: suxing liu
Author-email: suxingliu@gmail.com
USAGE
python3 skeleton_analyze.py -p ~/example/ -m1 test_skeleton.ply -m2 test_aligned.ply -m3 ~/example/slices/ --min_dis 12 --visualize_model 0
python3 /opt/code/skeleton_analyze.py -p /srv/test/ -m1 test_skeleton.ply -m2 test_aligned.ply -m3 /srv/test/slices/ --min_dis 12 --visualize_model 0
argument:
("-p", "--path", required=True, help="path to *.ply model file")
("-m", "--model", required=True, help="file name")
"""
#!/usr/bin/env python
import math
# import the necessary packages
from plyfile import PlyData, PlyElement
import numpy as np
from numpy import interp
from sklearn import preprocessing
from sklearn.preprocessing import MinMaxScaler
from sklearn.cluster import KMeans
from operator import itemgetter
from skimage.segmentation import watershed
from skimage.feature import peak_local_max
from skimage.morphology import convex_hull_image
from skimage.measure import regionprops
#from scipy.spatial import KDTree
from scipy import ndimage
import cv2
from pathlib import Path
import glob
import os
import sys
import open3d as o3d
import copy
import shutil
import argparse
#from dev_code import par_config
import openpyxl
from openpyxl import Workbook
from openpyxl import load_workbook
import csv
from findpeaks import findpeaks
import graph_tool.all as gt
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
import math
import itertools
#from tabulate import tabulate
from rdp import rdp
# import warnings filter
from warnings import simplefilter
# ignore all future warnings
simplefilter(action='ignore', category=FutureWarning)
# generate foloder to store the output results
def mkdir(path):
# import module
import os
# remove space at the beginning
path=path.strip()
# remove slash at the end
path=path.rstrip("\\")
# path exist? # True # False
isExists=os.path.exists(path)
# process
if not isExists:
# construct the path and folder
#print path + ' folder constructed!'
# make dir
os.makedirs(path)
return True
else:
# if exists, return
#print path+' path exists!'
#shutil.rmtree(path)
#os.makedirs(path)
return False
#calculate length of a 3D path or curve
def path_length(X, Y, Z):
n = len(X)
lv = [math.sqrt((X[i]-X[i-1])**2 + (Y[i]-Y[i-1])**2 + (Z[i]-Z[i-1])**2) for i in range (1,n)]
L = sum(lv)
return L
#compute angle between two vectors(works for n-dimensional vector),
def dot_product_angle(v1,v2):
if np.linalg.norm(v1) == 0 or np.linalg.norm(v2) == 0:
print("Zero magnitude vector!")
return 0
else:
vector_dot_product = np.dot(v1,v2)
arccos = np.arccos(vector_dot_product / (np.linalg.norm(v1) * np.linalg.norm(v2)))
angle = np.degrees(arccos)
#return angle
if angle > 0 and angle < 45:
return (90 - angle)
elif angle < 90:
return angle
else:
return (180- angle)
#coordinates transformation from cartesian coords to sphere coord system
def cart2sph(x, y, z):
hxy = np.hypot(x, y)
r = np.hypot(hxy, z)
elevation = np.arctan2(z, hxy)*180/math.pi
azimuth = np.arctan2(y, x)*180/math.pi
return r[2], azimuth[2], elevation[2]
'''
if azimuth > 90:
angle = 180 - azimuth
elif azimuth < 0:
angle = 90 + azimuth
else:
angle = azimuth
'''
# median-absolute-deviation (MAD) based outlier detection
def mad_based_outlier(points, thresh):
if len(points.shape) == 1:
points = points[:,None]
median = np.median(points, axis=0)
diff = np.sum((points - median)**2, axis=-1)
diff = np.sqrt(diff)
med_abs_deviation = np.median(diff)
if med_abs_deviation == 0:
modified_z_score = 0.6745 * diff / 1
else:
modified_z_score = 0.6745 * diff / med_abs_deviation
return modified_z_score > thresh
'''
# compute nearest neighbors of the anchor_pt_idx in point cloud by building KDTree
def get_neighbors(Data_array_pt, anchor_pt_idx, search_radius):
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(Data_array_pt)
#pcd.paint_uniform_color([0.5, 0.5, 0.5])
#o3d.visualization.draw_geometries([pcd])
# Build KDTree from point cloud for fast retrieval of nearest neighbors
pcd_tree = o3d.geometry.KDTreeFlann(pcd)
#print("Paint the 00th point red.")
#pcd.colors[anchor_pt_idx] = [1, 0, 0]
#print("Find its 50 nearest neighbors, paint blue.")
[k, idx, _] = pcd_tree.search_knn_vector_3d(pcd.points[anchor_pt_idx], search_radius)
#print("nearest neighbors = {}\n".format(sorted(np.asarray(idx[1:]))))
return idx
'''
def get_pt_sel(Data_array_pt):
####################################################################
# load skeleton coordinates and radius
Z_pt_sorted = np.sort(Data_array_pt[:,2])
idx_sel = int(len(Z_pt_sorted)*0.08)
Z_mid = Z_pt_sorted[idx_sel]
# mask
Z_mask = (Data_array_pt[:,2] <= Z_mid) & (Data_array_pt[:,2] >= Z_pt_sorted[0])
Z_pt_sel = Data_array_pt[Z_mask]
'''
############################################################
pcd_Z_mask = o3d.geometry.PointCloud()
pcd_Z_mask.points = o3d.utility.Vector3dVector(Z_pt_sel)
Z_mask_ply = result_path + "Z_mask.ply"
o3d.visualization.draw_geometries([pcd_Z_mask])
o3d.io.write_point_cloud(Z_mask_ply, pcd_Z_mask)
############################################################
'''
return Z_pt_sel
# compute dimensions of point cloud and nearest neighbors by KDTree
def get_pt_parameter(Data_array_pt, n_paths):
####################################################################
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(Data_array_pt)
#pcd.paint_uniform_color([0.5, 0.5, 0.5])
# get convex hull of a point cloud is the smallest convex set that contains all points.
#hull, _ = pcd.compute_convex_hull()
#hull_ls = o3d.geometry.LineSet.create_from_triangle_mesh(hull)
#hull_ls.paint_uniform_color((1, 0, 0))
# get AxisAlignedBoundingBox
aabb = pcd.get_axis_aligned_bounding_box()
#aabb.color = (0, 1, 0)
#Get the extent/length of the bounding box in x, y, and z dimension.
aabb_extent = aabb.get_extent()
aabb_extent_half = aabb.get_half_extent()
# get OrientedBoundingBox
#obb = pcd.get_oriented_bounding_box()
#obb.color = (1, 0, 0)
#visualize the convex hull as a red LineSet
#o3d.visualization.draw_geometries([pcd, aabb, obb, hull_ls])
pt_diameter_max = max(aabb_extent[0], aabb_extent[1])
pt_diameter_min = min(aabb_extent_half[0], aabb_extent_half[1])
pt_length = (aabb_extent[2])
pt_volume = np.pi * ((pt_diameter_max + pt_diameter_min)*0.5) ** 2 * pt_length
pt_density = n_paths/(pt_diameter_max)**2
pt_diameter = (pt_diameter_max + pt_diameter_min)*0.5
return pt_diameter_max, pt_diameter_min, pt_diameter, pt_length, pt_volume, pt_density
#find the closest points from a points sets to a fix point using Kdtree, O(log n)
def closest_point(point_set, anchor_point):
kdtree = KDTree(point_set)
(d, i) = kdtree.query(anchor_point)
#print("closest point:", point_set[i])
return i, point_set[i]
def find_nearest(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
#return array[idx]
return idx
#colormap mapping
def get_cmap(n, name = 'hsv'):
"""get the color mapping"""
#viridis, BrBG, hsv, copper, Spectral
#Returns a function that maps each index in 0, 1, ..., n-1 to a distinct
#RGB color; the keyword argument name must be a standard mpl colormap name
return plt.get_cmap(name,n+1)
# smooth 1d list
def smooth_data_convolve_average(arr, span):
re = np.convolve(arr, np.ones(span * 2 + 1) / (span * 2 + 1), mode="same")
# The "my_average" part: shrinks the averaging window on the side that
# reaches beyond the data, keeps the other side the same size as given
# by "span"
re[0] = np.average(arr[:span])
for i in range(1, span + 1):
re[i] = np.average(arr[:i + span])
re[-i] = np.average(arr[-i - span:])
return re
# Find closest number to k in given list
def closest(lst, K):
v_closet = lst[min(range(len(lst)), key = lambda i: abs(lst[i]-K))]
idx_list = [i for i, value in enumerate(lst) if value == v_closet]
return idx_list, v_closet
#cluster 1D list using Kmeans
def cluster_list(list_array, n_clusters):
data = np.array(list_array)
if data.ndim == 1:
data = data.reshape(-1,1)
#kmeans = KMeans(n_clusters).fit(data.reshape(-1,1))
kmeans = KMeans(n_clusters, init='k-means++', random_state=0).fit(data)
#kmeans = KMeans(n_clusters).fit(data)
labels = kmeans.labels_
centers = kmeans.cluster_centers_
center_labels = kmeans.predict(centers)
#print(kmeans.cluster_centers_)
'''
#visualzie data clustering
######################################################
y_kmeans = kmeans.predict(data)
plt.scatter(data[:, 0], data[:, 1], c=y_kmeans, s=50, cmap='viridis')
centers = kmeans.cluster_centers_
plt.scatter(centers[:, 0], centers[:, 1], c='black', s=200, alpha=0.5)
#plt.legend()
plt.show()
'''
'''
from sklearn.metrics import silhouette_score
range_n_clusters = [2, 3, 4, 5, 6, 7, 8]
silhouette_avg = []
for num_clusters in range_n_clusters:
# initialize kmeans
kmeans = KMeans(n_clusters=num_clusters)
kmeans.fit(data)
cluster_labels = kmeans.labels_
# silhouette score
silhouette_avg.append(silhouette_score(data, cluster_labels))
plt.plot(range_n_clusters,silhouette_avg,'bx-')
plt.xlabel('Values of K')
plt.ylabel('Silhouette score')
plt.title('Silhouette analysis For Optimal k')
plt.show()
Sum_of_squared_distances = []
K = range(2,8)
for num_clusters in K :
kmeans = KMeans(n_clusters=num_clusters)
kmeans.fit(data)
Sum_of_squared_distances.append(kmeans.inertia_)
plt.plot(K,Sum_of_squared_distances,'bx-')
plt.xlabel('Values of K')
plt.ylabel('Sum of squared distances/Inertia')
plt.title('Elbow Method For Optimal k')
plt.show()
'''
######################################################
return labels, centers, center_labels
#remove outliers
def outlier_remove(data_list):
#find index of k biggest elements in list
####################################################
k = int(len(data_list) * 0.8)
#print(k)
#k biggest
idx_dominant = np.argsort(data_list)[-k:]
#k smallest
#idx_dominant_dis_closest_pts = np.argsort(dis_closest_pts)[:k]
#print("idx_dominant_dis_closest_pts = {}".format(idx_dominant_dis_closest_pts))
#print(idx_dominant_dis_closest_pts)
outlier_remove_list = [data_list[index] for index in idx_dominant]
#print("outlier_remove_list = {}".format(outlier_remove_list))
return outlier_remove_list, idx_dominant
####################################################
# save point cloud data from numpy array as ply file, open3d compatiable format
def write_ply(path, data_numpy_array):
#data_range = 100
#Normalize data range for generate cross section level set scan
#min_max_scaler = preprocessing.MinMaxScaler(feature_range = (0, data_range))
#point_normalized = min_max_scaler.fit_transform(data_numpy_array)
#initialize pcd object for open3d
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(data_numpy_array)
# get the model center postion
model_center = pcd.get_center()
# geometry points are translated directly to the model_center position
pcd.translate(-1*(model_center))
#write out point cloud file
o3d.io.write_point_cloud(path, pcd, write_ascii = True)
# check saved file
if os.path.exists(path):
print("Converted 3d model was saved at {0}".format(path))
return True
else:
return False
print("Model file converter failed !")
#sys.exit(0)
# compute diameter from area
def area_radius(area_of_circle):
radius = ((area_of_circle/ math.pi)** 0.5)
#note: return diameter instead of radius
return 2*radius
# segmentation of overlapping components
def watershed_seg(orig, thresh, min_distance_value):
# compute the exact Euclidean distance from every binary
# pixel to the nearest zero pixel, then find peaks in this
# distance map
D = ndimage.distance_transform_edt(thresh)
localMax = peak_local_max(D, indices = False, min_distance = min_distance_value, labels = thresh)
#localMax = peak_local_max(D, min_distance = min_distance_value, labels = thresh)
# perform a connected component analysis on the local peaks,
# using 8-connectivity, then appy the Watershed algorithm
markers = ndimage.label(localMax, structure = np.ones((3, 3)))[0]
#print("markers")
#print(type(markers))
labels = watershed(-D, markers, mask = thresh)
#print("[INFO] {} unique segments found\n".format(len(np.unique(labels)) - 1))
return labels
# analyze cross section paramters
def crosssection_analysis(image_file):
# load the image
imgcolor = cv2.imread(image_file)
# if cross scan images are white background and black foreground
#imgcolor = ~imgcolor
# accquire image dimensions
height, width, channels = imgcolor.shape
#shifted = cv2.pyrMeanShiftFiltering(image, 5, 5)
#Image binarization by apltying otsu threshold
img = cv2.cvtColor(imgcolor, cv2.COLOR_BGR2GRAY)
# Convert BGR to GRAY
img_lab = cv2.cvtColor(imgcolor, cv2.COLOR_BGR2LAB)
gray = cv2.cvtColor(img_lab, cv2.COLOR_BGR2GRAY)
#Obtain the threshold image using OTSU adaptive filter
thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
#Obtain the threshold image using OTSU adaptive filter
ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
#find contours and fill contours
####################################################################
#container version
contours, hier = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
#local version
#_, contours, hier = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours_img = []
#define image morphology operation kernel
#kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
#draw all the filled contours
for c in contours:
#fill the connected contours
contours_img = cv2.drawContours(binary, [c], -1, (255, 255, 255), cv2.FILLED)
#contours_img = cv2.erode(contours_img, kernel, iterations = 5)
#Obtain the threshold image using OTSU adaptive filter
thresh_filled = cv2.threshold(contours_img, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
#Obtain the threshold image using OTSU adaptive filter
ret, binary_filled = cv2.threshold(contours_img, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
# process filled contour images to extract connected Components
####################################################################
contours, hier = cv2.findContours(binary_filled, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
#local version
#_, contours, hier = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
#draw all the filled contours
for c in contours:
#fill the connected contours
contours_img = cv2.drawContours(binary, [c], -1, (255, 255, 255), cv2.FILLED)
# define kernel
connectivity = 8
#find connected components
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(contours_img, connectivity , cv2.CV_32S)
#find the component with largest area
largest_label = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])
#collection of all component area
areas = [s[4] for s in stats]
# average of component area
area_avg = sum(areas)/len(np.unique(labels))
#area_avg = sum(areas)
###################################################################
# segment overlapping components
#make backup image
orig = imgcolor.copy()
#watershed based segmentaiton
labels = watershed_seg(contours_img, thresh_filled, min_distance_value)
#labels = watershed_seg(contours_img, thresh_filled, 20)
N_seg = len(np.unique(labels))-1
#Map component labels to hue val
label_hue = np.uint8(128*labels/np.max(labels))
#label_hue[labels == largest_label] = np.uint8(15)
blank_ch = 255*np.ones_like(label_hue)
labeled_img = cv2.merge([label_hue, blank_ch, blank_ch])
# cvt to BGR for display
labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR)
# set background label to black
labeled_img[label_hue==0] = 0
# save label results
#result_file = (save_path_label + base_name + '_label.png')
#print(result_file)
#cv2.imwrite(result_file, labeled_img)
return N_seg, labeled_img
#compute angle
def angle(directions):
"""Return the angle between vectors"""
vec2 = directions[1:]
vec1 = directions[:-1]
norm1 = np.sqrt((vec1 ** 2).sum(axis=1))
norm2 = np.sqrt((vec2 ** 2).sum(axis=1))
cos = (vec1 * vec2).sum(axis=1) / (norm1 * norm2)
return np.arccos(cos)
#first derivative function
def first_derivative(x) :
return x[2:] - x[0:-2]
#second derivative function
def second_derivative(x) :
return x[2:] - 2 * x[1:-1] + x[:-2]
#compute curvature
def curvature(x, y) :
x_1 = first_derivative(x)
x_2 = second_derivative(x)
y_1 = first_derivative(y)
y_2 = second_derivative(y)
return np.abs(x_1 * y_2 - y_1 * x_2) / np.sqrt((x_1**2 + y_1**2)**3)
#define angle computation for turing points detection
def turning_points(x, y, turning_points, smoothing_radius,cluster_radius):
if smoothing_radius:
weights = np.ones(2 * smoothing_radius + 1)
new_x = ndimage.convolve1d(x, weights, mode='constant', cval=0.0)
new_x = new_x[smoothing_radius:-smoothing_radius] / np.sum(weights)
new_y = ndimage.convolve1d(y, weights, mode='constant', cval=0.0)
new_y = new_y[smoothing_radius:-smoothing_radius] / np.sum(weights)
else :
new_x, new_y = x, y
k = curvature(new_x, new_y)
turn_point_idx = np.argsort(k)[::-1]
t_points = []
while len(t_points) < turning_points and len(turn_point_idx) > 0:
t_points += [turn_point_idx[0]]
idx = np.abs(turn_point_idx - turn_point_idx[0]) > cluster_radius
turn_point_idx = turn_point_idx[idx]
t_points = np.array(t_points)
t_points += smoothing_radius + 1
return t_points.astype(int)
# visualize CDF curve
def CDF_visualization(radius_avg_rec):
trait_file = (label_path + '/CDF.xlsx')
'''
if os.path.exists(trait_file):
# update values
#Open an xlsx for reading
wb = load_workbook(trait_file, read_only = False)
sheet = wb.active
'''
if os.path.isfile(trait_file):
# update values
#Open an xlsx for reading
wb = openpyxl.load_workbook(trait_file)
#Get the current Active Sheet
sheet = wb.active
sheet.delete_rows(1, sheet.max_row+1) # for entire sheet
else:
# Keep presets
wb = Workbook()
sheet = wb.active
for row in enumerate(radius_avg_rec):
sheet.append(row)
#save the csv file
wb.save(trait_file)
num_bins = 10
#counts, bin_edges = np.histogram(list(zip(*result)[0]), bins = num_bins, normed = True)
counts, bin_edges = np.histogram(radius_avg_rec, bins = num_bins)
# compute CDF curve
cdf = np.cumsum(counts)
#cdf = cdf / cdf[-1] #normalize
x = bin_edges[1:]
y = cdf
# assembly points of CDF curve
trajectory = np.vstack((x, y)).T
index_turning_pt = turning_points(x, y, turning_points = 4, smoothing_radius = 2, cluster_radius = 2)
#Ramer-Douglas-Peucker Algorithm
#simplify points et using rdp library
simplified_trajectory = rdp(trajectory, epsilon = 0.00200)
#simplified_trajectory = rdp(trajectory)
sx, sy = simplified_trajectory.T
#print(sx)
#print(sy)
#compute plateau in curve
dis_sy = [j-i for i, j in zip(sy[:-1], sy[1:])]
#get index of plateau location
index_sy = [i for i in range(len(dis_sy)) if dis_sy[i] <= 1.3]
dis_index_sy = [j-i for i, j in zip(index_sy[:-1], index_sy[1:])]
for idx, value in enumerate(dis_index_sy):
if idx < len(index_sy)-2:
if value == dis_index_sy[idx+1]:
index_sy.remove(index_sy[idx+1])
# Define a minimum angle to treat change in direction
# as significant (valuable turning point).
#min_angle = np.pi / 36.0
min_angle = np.pi / 180.0
#min_angle = np.pi /1800.0
# Compute the direction vectors on the simplified_trajectory.
directions = np.diff(simplified_trajectory, axis = 0)
theta = angle(directions)
# Select the index of the points with the greatest theta.
# Large theta is associated with greatest change in direction.
idx = np.where(theta > min_angle)[0] + 1
index_turning_pt = sorted(idx)
Turing_points = np.unique(sy[idx].astype(int))
#max_idx = max(max_idx)
#print("Turing points: {0} \n".format(Turing_points))
# plot CDF
#fig = plt.plot(bin_edges[1:], cdf, '-r', label = 'CDF')
fig = plt.figure(1)
#ax = fig.add_subplot(111)
plt.grid(True)
#plt.legend(loc = 'right')
plt.title('CDF curve')
plt.xlabel('Root area, unit:pixel')
plt.ylabel('Depth of level-set, unit:pixel')
plt.plot(sx, sy, 'gx-', label = 'simplified trajectory')
plt.plot(bin_edges[1:], cdf, '-b', label = 'CDF')
#plt.plot(sx[idx], sy[idx], 'ro', markersize = 7, label='turning points')
plt.plot(sx[index_sy], sy[index_sy], 'ro', markersize = 7, label = 'plateau points')
#plt.plot(sx[index_turning_pt], sy[index_turning_pt], 'bo', markersize = 7, label='turning points')
#plt.vlines(sx[index_turning_pt], sy[index_turning_pt]-100, sy[index_turning_pt]+100, color='b', linewidth = 2, alpha = 0.3)
#plt.legend(loc='best')
result_file_CDF = label_path + '/' + 'cdf.png'
plt.savefig(result_file_CDF)
plt.close()
return sy
# compute number of whorls
def wholr_number_count(imgList):
area_avg_rec = []
density_rec = []
for img in imgList:
#(area_avg, area_sum, n_unique_labels) = root_area_label(img)
(radius_avg, area_avg, density) = crosssection_analysis(img)
area_avg_rec.append(area_avg)
density_rec.append(density)
#visualzie the CDF graph of first return value
list_thresh = sorted(CDF_visualization(area_avg_rec))
#compute plateau in curve
dis_array = [j-i for i, j in zip(list_thresh[:-1], list_thresh[1:])]
#get index of plateau location
index = [i for i in range(len(dis_array)) if dis_array[i] <= 1.3]
dis_index = [j-i for i, j in zip(index[:-1], index[1:])]
for idx, value in enumerate(dis_index):
if idx < len(index)-2:
if value == dis_index[idx+1]:
index.remove(index[idx+1])
reverse_index = sorted(index, reverse = True)
#count = sum(1 for x in dis_array if float(x) <= 1.3)
#get whorl number count
count_wholrs = int(math.ceil(len(index)))
#compute wholr location
#compute whorl location
whorl_dis = []
whorl_loc = []
for idx, value in enumerate(reverse_index, start=1):
#dis_value = list_thresh[value+1] - list_thresh[value-1]
loc_value = int(len(imgList) - list_thresh[value+1])
whorl_loc.append(loc_value)
#print("adding value : {0} \n".format(str(loc_value)))
#compute whorl distance
whorl_dis_array = [j-i for i, j in zip(whorl_loc[:-1], whorl_loc[1:])]
whorl_loc.extend([0, len(imgList)])
whorl_loc = list(dict.fromkeys(whorl_loc))
whorl_loc_ex = sorted(whorl_loc)
#print("list_thresh : {0} \n".format(str(list_thresh)))
return count_wholrs, whorl_loc_ex, sum(density_rec)/len(density_rec)
# compute parameters from cross section scan
def crosssection_scan(imgList, result_path):
List_N_seg = []
####################################################################
for image_file in imgList:
path, filename = os.path.split(image_file)
base_name = os.path.splitext(os.path.basename(filename))[0]
(n_seg, labeled_img) = crosssection_analysis(image_file)
print("{} N_labels = {}".format(base_name, n_seg))
#result_file = (result_path + base_name + '_label.png')
#cv2.imwrite(result_file, labeled_img)
List_N_seg.append(n_seg)
#List_N_seg_ori = List_N_seg
#########################################################################
# find the first 1 in list
idx_f = List_N_seg.index(1)
print("first index {}\n".format(idx_f))
# adjust the list values
if idx_f > 0:
List_N_seg[0:idx_f] = [1 for x in List_N_seg[0:idx_f]]
# find the index of peak max value
if np.argmax(List_N_seg) > 0:
List_N_seg = List_N_seg[0: np.argmax(List_N_seg)]
###################################################################
span = 3
List_N_seg_smooth = smooth_data_convolve_average(np.array(List_N_seg), span)
#List_N_seg_smooth = List_N_seg
####################################################################
# peak detection
# Data
X = List_N_seg_smooth