-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdemo_trait_extract_parallel_val.py
executable file
·1836 lines (1213 loc) · 59.9 KB
/
demo_trait_extract_parallel_val.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
'''
Name: trait_extract_parallel.py
Version: 1.0
Summary: Extract plant shoot traits (larea, temp_index, max_width, max_height, avg_curv, color_cluster) by paralell processing
Author: suxing liu
Author-email: [email protected]
Created: 2019-04-29
USAGE:
time python3 demo_trait_extract_parallel_val.py -p ~/example/test/ -ft jpg
time python3 demo_trait_extract_parallel_val.py -p ~/plant-image-analysis/demo_test/16-1_6-25/ -ft jpg
time python3 demo_trait_extract_parallel_val.py -p ~/example/pi_images/22-4_6-27/mask_reverse/ -ft jpg -min 500 -tp ~/example/pi_images/marker_template/16-1_6-23_sticker_match.jpg
'''
# import the necessary packages
import os
import glob
import utils
from collections import Counter
import argparse
from sklearn.cluster import KMeans
from sklearn.cluster import MiniBatchKMeans
from skimage.feature import peak_local_max
from skimage.morphology import medial_axis
from skimage import img_as_float, img_as_ubyte, img_as_bool, img_as_int
from skimage import measure
from skimage.color import rgb2lab, deltaE_cie76
from skimage import morphology
from skimage.segmentation import clear_border, watershed
from skimage.measure import regionprops
from scipy.spatial import distance as dist
from scipy import optimize
from scipy import ndimage
from scipy.interpolate import interp1d
from skan import skeleton_to_csgraph, Skeleton, summarize, draw
import networkx as nx
import imutils
import numpy as np
import argparse
import cv2
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib as mpl
import matplotlib.cm as mtpltcm
import math
import openpyxl
import csv
from tabulate import tabulate
import warnings
warnings.filterwarnings("ignore")
import psutil
import concurrent.futures
import multiprocessing
from multiprocessing import Pool
from contextlib import closing
from pathlib import Path
from matplotlib import collections
from collections import OrderedDict
MBFACTOR = float(1<<20)
# define class for curvature computation
class ComputeCurvature:
def __init__(self,x,y):
""" Initialize some variables """
self.xc = 0 # X-coordinate of circle center
self.yc = 0 # Y-coordinate of circle center
self.r = 0 # Radius of the circle
self.xx = np.array([]) # Data points
self.yy = np.array([]) # Data points
self.x = x # X-coordinate of circle center
self.y = y # Y-coordinate of circle center
def calc_r(self, xc, yc):
""" calculate the distance of each 2D points from the center (xc, yc) """
return np.sqrt((self.xx-xc)**2 + (self.yy-yc)**2)
def f(self, c):
""" calculate the algebraic distance between the data points and the mean circle centered at c=(xc, yc) """
ri = self.calc_r(*c)
return ri - ri.mean()
def df(self, c):
""" Jacobian of f_2b
The axis corresponding to derivatives must be coherent with the col_deriv option of leastsq"""
xc, yc = c
df_dc = np.empty((len(c), self.x.size))
ri = self.calc_r(xc, yc)
df_dc[0] = (xc - self.x)/ri # dR/dxc
df_dc[1] = (yc - self.y)/ri # dR/dyc
df_dc = df_dc - df_dc.mean(axis=1)[:, np.newaxis]
return df_dc
def fit(self, xx, yy):
self.xx = xx
self.yy = yy
center_estimate = np.r_[np.mean(xx), np.mean(yy)]
center = optimize.leastsq(self.f, center_estimate, Dfun=self.df, col_deriv=True)[0]
self.xc, self.yc = center
ri = self.calc_r(*center)
self.r = ri.mean()
return 1 / self.r # Return the curvature
class ColorLabeler:
def __init__(self):
# initialize the colors dictionary, containing the color
# name as the key and the RGB tuple as the value
colors = OrderedDict({
"red": (255, 0, 0),
"green": (0, 255, 0),
"blue": (0, 0, 255)})
# allocate memory for the L*a*b* image, then initialize
# the color names list
self.lab = np.zeros((len(colors), 1, 3), dtype="uint8")
self.colorNames = []
# loop over the colors dictionary
for (i, (name, rgb)) in enumerate(colors.items()):
# update the L*a*b* array and the color names list
self.lab[i] = rgb
self.colorNames.append(name)
# convert the L*a*b* array from the RGB color space
# to L*a*b*
self.lab = cv2.cvtColor(self.lab, cv2.COLOR_RGB2LAB)
def label(self, image, c):
# construct a mask for the contour, then compute the
# average L*a*b* value for the masked region
mask = np.zeros(image.shape[:2], dtype="uint8")
cv2.drawContours(mask, [c], -1, 255, -1)
mask = cv2.erode(mask, None, iterations=2)
mean = cv2.mean(image, mask=mask)[:3]
# initialize the minimum distance found thus far
minDist = (np.inf, None)
# loop over the known L*a*b* color values
for (i, row) in enumerate(self.lab):
# compute the distance between the current L*a*b*
# color value and the mean of the image
d = dist.euclidean(row[0], mean)
# if the distance is smaller than the current distance,
# then update the bookkeeping variable
if d < minDist[0]:
minDist = (d, i)
# return the name of the color with the smallest distance
return self.colorNames[minDist[1]]
# 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!'
return False
# color cluster based object segmentation
def color_cluster_seg(image, args_colorspace, args_channels, args_num_clusters, min_size):
orig_image = image.copy
# Change image color space, if necessary.
colorSpace = args_colorspace.lower()
if colorSpace == 'hsv':
image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
elif colorSpace == 'ycrcb' or colorSpace == 'ycc':
image = cv2.cvtColor(image, cv2.COLOR_BGR2YCrCb)
elif colorSpace == 'lab':
image = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)
else:
colorSpace = 'bgr' # set for file naming purposes
# Keep only the selected channels for K-means clustering.
if args_channels != 'all':
channels = cv2.split(image)
channelIndices = []
for char in args_channels:
channelIndices.append(int(char))
image = image[:,:,channelIndices]
if len(image.shape) == 2:
image.reshape(image.shape[0], image.shape[1], 1)
(width, height, n_channel) = image.shape
#print("image shape: \n")
#print(width, height, n_channel)
# Flatten the 2D image array into an MxN feature vector, where M is the number of pixels and N is the dimension (number of channels).
reshaped = image.reshape(image.shape[0] * image.shape[1], image.shape[2])
# Perform K-means clustering.
if args_num_clusters < 2:
print('Warning: num-clusters < 2 invalid. Using num-clusters = 2')
#define number of cluster
numClusters = max(2, args_num_clusters)
# clustering method
kmeans = KMeans(n_clusters = numClusters, n_init = 40, max_iter = 500).fit(reshaped)
# get lables
pred_label = kmeans.labels_
# Reshape result back into a 2D array, where each element represents the corresponding pixel's cluster index (0 to K - 1).
clustering = np.reshape(np.array(pred_label, dtype=np.uint8), (image.shape[0], image.shape[1]))
# Sort the cluster labels in order of the frequency with which they occur.
sortedLabels = sorted([n for n in range(numClusters)],key = lambda x: -np.sum(clustering == x))
# Initialize K-means grayscale image; set pixel colors based on clustering.
kmeansImage = np.zeros(image.shape[:2], dtype=np.uint8)
for i, label in enumerate(sortedLabels):
kmeansImage[clustering == label] = int(255 / (numClusters - 1)) * i
ret, thresh = cv2.threshold(kmeansImage,0,255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)
#thresh_cleaned = clear_border(thresh)
if np.count_nonzero(thresh) > 0:
thresh_cleaned = clear_border(thresh)
if cv2.countNonZero(thresh_cleaned) == 0:
thresh_cleaned = thresh
else:
thresh_cleaned = thresh
thresh_cleaned = thresh
nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(thresh_cleaned, connectivity = 8)
# stats[0], centroids[0] are for the background label. ignore
# cv2.CC_STAT_LEFT, cv2.CC_STAT_TOP, cv2.CC_STAT_WIDTH, cv2.CC_STAT_HEIGHT
sizes = stats[1:, cv2.CC_STAT_AREA]
Coord_left = stats[1:, cv2.CC_STAT_LEFT]
Coord_top = stats[1:, cv2.CC_STAT_TOP]
Coord_width = stats[1:, cv2.CC_STAT_WIDTH]
Coord_height = stats[1:, cv2.CC_STAT_HEIGHT]
Coord_centroids = centroids
#print("Coord_centroids {}\n".format(centroids[1][1]))
#print("[width, height] {} {}\n".format(width, height))
nb_components = nb_components - 1
#min_size = 2000*1
img_thresh = np.zeros([width, height], dtype=np.uint8)
#max_label = 1
#max_size = sizes[1]
if len(sizes) > 2:
max_label = 1
max_size = sizes[1]
else:
max_size = width*height*0.1
#for every component in the image, keep it only if it's above min_size
for i in range(0, nb_components):
'''
#print("{} nb_components found".format(i))
if (sizes[i] >= min_size) and (Coord_left[i] > 1) and (Coord_top[i] > 1) and (Coord_width[i] - Coord_left[i] > 0) and (Coord_height[i] - Coord_top[i] > 0) and (centroids[i][0] - width*0.5 < 10) and ((centroids[i][1] - height*0.5 < 10)) and ((sizes[i] <= max_size)):
img_thresh[output == i + 1] = 255
print("Foreground center found ")
elif ((Coord_width[i] - Coord_left[i])*0.5 - width < 15) and (centroids[i][0] - width*0.5 < 15) and (centroids[i][1] - height*0.5 < 15) and ((sizes[i] <= max_size)):
imax = max(enumerate(sizes), key=(lambda x: x[1]))[0] + 1
img_thresh[output == imax] = 255
print("Foreground max found ")
'''
if (sizes[i] >= min_size):
img_thresh[output == i + 1] = 255
'''
if len(sizes) > 2:
max_label = i
max_size = sizes[i]
img_thresh[output == max_label] = 255
else:
img_thresh[output == i + 1] = 255
'''
'''
if cv2.countNonZero(clear_border(img_thresh)) == 0:
img_thresh = img_thresh
else:
img_thresh = clear_border(img_thresh)
'''
#max_label, max_size = max([(i, stats[i, cv2.CC_STAT_AREA]) for i in range(1, nb_components)], key=lambda x: x[1])
#img_thresh[output == max_label] = 255
#from skimage import img_as_ubyte
#img_thresh = img_as_ubyte(img_thresh)
#print("img_thresh.dtype")
#print(img_thresh.dtype)
contours, hier = cv2.findContours(img_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
size_kernel = 10
if len(contours) > 1:
kernel = np.ones((size_kernel,size_kernel), np.uint8)
dilation = cv2.dilate(img_thresh.copy(), kernel, iterations = 1)
closing = cv2.morphologyEx(dilation, cv2.MORPH_CLOSE, kernel)
img_thresh = closing
if cv2.countNonZero(img_thresh) == 0:
img_thresh[:] = 0
#return img_thresh
return img_thresh
#return thresh_cleaned
# extract medial_axis for binary mask
def medial_axis_image(thresh):
#convert an image from OpenCV to skimage
thresh_sk = img_as_float(thresh)
image_bw = img_as_bool((thresh_sk))
image_medial_axis = medial_axis(image_bw)
return image_medial_axis
# extract skeleton for binary mask
def skeleton_bw(thresh):
# Convert mask to boolean image, rather than 0 and 255 for skimage to use it
#convert an image from OpenCV to skimage
thresh_sk = img_as_float(thresh)
image_bw = img_as_bool((thresh_sk))
#skeleton = morphology.skeletonize(image_bw)
skeleton = morphology.thin(image_bw)
skeleton_img = skeleton.astype(np.uint8) * 255
return skeleton_img, skeleton
#watershed based individual leaf segmentation
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)
# 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
# computation of percentage
def percentage(part, whole):
percentage = "{:.0%}".format(float(part)/float(whole))
return str(percentage)
'''
# extract individual leaf object
def individual_object_seg(orig, labels, save_path, base_name, file_extension):
num_clusters = 5
(width, height, n_channel) = orig.shape
for label in np.unique(labels):
# if the label is zero, we are examining the 'background'
# so simply ignore it
if label == 0:
continue
# otherwise, allocate memory for the label region and draw
# it on the mask
mask = np.zeros((width, height), dtype="uint8")
mask[labels == label] = 255
# apply individual object mask
masked = cv2.bitwise_and(orig, orig, mask = mask)
# detect contours in the mask and grab the largest one
#cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
#contours, hierarchy = cv2.findContours(mask.copy(),cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#c = max(contours, key = cv2.contourArea)
#if len(c) >= 5 :
#label_img = cv2.drawContours(masked, [c], -1, (255, 0, 0), 2)
mkpath_leaf = os.path.dirname(save_path) + '/leaf' + str(label)
mkdir(mkpath_leaf)
save_path_leaf = mkpath_leaf + '/'
#define result path
result_img_path = (save_path_leaf + 'leaf_' + str(label) + file_extension)
cv2.imwrite(result_img_path, masked)
#save color quantization result
#rgb_colors = color_quantization(image, thresh, save_path, num_clusters)
rgb_colors, counts = color_region(masked, mask, save_path_leaf, num_clusters)
list_counts = list(counts.values())
#print(type(list_counts))
for value in list_counts:
print(percentage(value, np.sum(list_counts)))
'''
'''
# watershed segmentation with marker
def watershed_seg_marker(orig, thresh, min_distance_value, img_marker):
# 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)
gray = cv2.cvtColor(img_marker, cv2.COLOR_BGR2GRAY)
img_marker = cv2.threshold(gray, 128, 255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
#localMax = peak_local_max(D, indices = False, 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(img_marker, structure = np.ones((3, 3)))[0]
labels = watershed(-D, markers, mask = thresh)
props = regionprops(labels)
areas = [p.area for p in props]
import statistics
#outlier_list = outlier_doubleMAD(areas, thresh = 1.0)
#indices = [i for i, x in enumerate(outlier_list) if x]
print(areas)
print(statistics.mean(areas))
#
#print(outlier_list)
#print(indices)
print("[INFO] {} unique segments found\n".format(len(np.unique(labels)) - 1))
return labels
'''
# computation of external traits like contour, convelhull, area, ,max width and height
def comp_external_contour(orig,thresh):
#find contours and get the external one
contours, hier = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
img_height, img_width, img_channels = orig.shape
index = 1
for c in contours:
#get the bounding rect
x, y, w, h = cv2.boundingRect(c)
if w>img_width*0.01 and h>img_height*0.01:
trait_img = cv2.drawContours(orig, contours, -1, (255, 255, 0), 1)
# draw a green rectangle to visualize the bounding rect
roi = orig[y:y+h, x:x+w]
print("ROI {} detected ...\n".format(index))
#result_file = (save_path + str(index) + file_extension)
#cv2.imwrite(result_file, roi)
trait_img = cv2.rectangle(orig, (x, y), (x+w, y+h), (255, 255, 0), 3)
index+= 1
'''
#get the min area rect
rect = cv2.minAreaRect(c)
box = cv2.boxPoints(rect)
# convert all coordinates floating point values to int
box = np.int0(box)
#draw a red 'nghien' rectangle
trait_img = cv2.drawContours(orig, [box], 0, (0, 0, 255))
'''
# get convex hull
hull = cv2.convexHull(c)
# draw it in red color
trait_img = cv2.drawContours(orig, [hull], -1, (0, 0, 255), 3)
# compute the center of the contour
M = cv2.moments(c)
center_X = int(M["m10"] / M["m00"])
center_Y = int(M["m01"] / M["m00"])
'''
# calculate epsilon base on contour's perimeter
# contour's perimeter is returned by cv2.arcLength
epsilon = 0.01 * cv2.arcLength(c, True)
# get approx polygons
approx = cv2.approxPolyDP(c, epsilon, True)
# draw approx polygons
trait_img = cv2.drawContours(orig, [approx], -1, (0, 255, 0), 1)
# hull is convex shape as a polygon
hull = cv2.convexHull(c)
trait_img = cv2.drawContours(orig, [hull], -1, (0, 0, 255))
'''
'''
#get the min enclosing circle
(x, y), radius = cv2.minEnclosingCircle(c)
# convert all values to int
center = (int(x), int(y))
radius = int(radius)
# and draw the circle in blue
trait_img = cv2.circle(orig, center, radius, (255, 0, 0), 2)
'''
area = cv2.contourArea(c)
print("Leaf area = {0:.2f}... \n".format(area))
hull = cv2.convexHull(c)
hull_area = cv2.contourArea(hull)
index = float(area)/hull_area
extLeft = tuple(c[c[:,:,0].argmin()][0])
extRight = tuple(c[c[:,:,0].argmax()][0])
extTop = tuple(c[c[:,:,1].argmin()][0])
extBot = tuple(c[c[:,:,1].argmax()][0])
trait_img = cv2.circle(orig, extLeft, 3, (255, 0, 0), -1)
trait_img = cv2.circle(orig, extRight, 3, (255, 0, 0), -1)
trait_img = cv2.circle(orig, extTop, 3, (255, 0, 0), -1)
trait_img = cv2.circle(orig, extBot, 3, (255, 0, 0), -1)
max_width = dist.euclidean(extLeft, extRight)
max_height = dist.euclidean(extTop, extBot)
if max_width > max_height:
trait_img = cv2.line(orig, extLeft, extRight, (0,255,0), 2)
else:
trait_img = cv2.line(orig, extTop, extBot, (0,255,0), 2)
print("Width and height are {0:.2f},{1:.2f}... \n".format(w, h))
return trait_img, area, index, w, h, center_X, center_Y
# scale contour for tracking
def scale_contour(cnt, scale):
M = cv2.moments(cnt)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
cnt_norm = cnt - [cx, cy]
cnt_scaled = cnt_norm * scale
cnt_scaled = cnt_scaled + [cx, cy]
cnt_scaled = cnt_scaled.astype(np.int32)
return cnt_scaled
# individual leaf object segmentation and traits computation
def leaf_traits_computation(orig, labels, center_X, center_Y, save_path, base_name, file_extension):
gray = cv2.cvtColor(orig, cv2.COLOR_BGR2GRAY)
leaf_index_rec = []
contours_rec = []
area_rec = []
curv_rec = []
temp_index_rec = []
major_axis_rec = []
minor_axis_rec = []
color_ratio_rec = []
count = 0
num_clusters = 5
# curvature computation
# loop over the unique labels returned by the Watershed algorithm
for index, label in enumerate(np.unique(labels), start = 1):
# if the label is zero, we are examining the 'background'
# so simply ignore it
if label == 0:
continue
# otherwise, allocate memory for the label region and draw
# it on the mask
mask = np.zeros(gray.shape, dtype = "uint8")
mask[labels == label] = 255
#get the medial axis of the contour
image_skeleton, skeleton = skeleton_bw(mask)
# apply individual object mask
masked = cv2.bitwise_and(orig, orig, mask = mask)
'''
#individual leaf segmentation and color analysis
################################################################################
mkpath_leaf = os.path.dirname(save_path) + '/leaf' + str(label)
mkdir(mkpath_leaf)
save_path_leaf = mkpath_leaf + '/'
#define result path
result_img_path = (save_path_leaf + 'leaf_' + str(label) + file_extension)
cv2.imwrite(result_img_path, masked)
# save _skeleton result
result_file = (save_path_leaf + 'leaf_skeleton_' + str(label) + file_extension)
cv2.imwrite(result_file, img_as_ubyte(image_skeleton))
#save color quantization result
#rgb_colors = color_quantization(image, thresh, save_path, num_clusters)
rgb_colors, counts = color_region(masked, mask, save_path_leaf, num_clusters)
list_counts = list(counts.values())
#print(type(list_counts))
color_ratio = []
for value in list_counts:
#print(percentage(value, np.sum(list_counts)))
color_ratio.append(percentage(value, np.sum(list_counts)))
color_ratio_rec.append(color_ratio)
'''
# detect contours in the mask and grab the largest one
#cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
contours, hierarchy = cv2.findContours(mask.copy(),cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
c = max(contours, key = cv2.contourArea)
if len(c) >= 10 :
contours_rec.append(c)
area_rec.append(cv2.contourArea(c))
else:
# optional to "delete" the small contours
#label_trait = cv2.drawContours(orig, [c], -1, (0, 0, 255), 2)
print("lack of enough points to fit ellipse")
#sort contours based on its area size
contours_rec_sorted = [x for _, x in sorted(zip(area_rec, contours_rec), key=lambda pair: pair[0])]
#sort contour area for tracking
#normalized_area_rec = preprocessing.normalize(sorted(area_rec))
normalized_area_rec = [float(i)/sum(sorted(area_rec)) for i in sorted(area_rec)]
#normalized_area_rec = sorted(area_rec)
#cmap = get_cmap(len(contours_rec_sorted))
cmap = get_cmap(len(contours_rec_sorted)+1)
tracking_backgd = np.zeros(gray.shape, dtype = "uint8")
#backgd.fill(128)
#backgd = orig
#clean area record list
area_rec = []
#individual leaf traits sorting based on area order
################################################################################
for i in range(len(contours_rec_sorted)):
c = contours_rec_sorted[i]
#assign unique color value in opencv format
color_rgb = tuple(reversed(cmap(i)[:len(cmap(i))-1]))
color_rgb = tuple([255*x for x in color_rgb])
# draw a circle enclosing the object
((x, y), r) = cv2.minEnclosingCircle(c)
#label_trait = cv2.circle(orig, (int(x), int(y)), 3, (0, 255, 0), 2)
#track_trait = cv2.circle(tracking_backgd, (int(x), int(y)), int(normalized_area_rec[i]*200), (255, 255, 255), -1)
#draw filled contour
#label_trait = cv2.drawContours(orig, [c], -1, color_rgb, -1)
label_trait = cv2.drawContours(orig, [c], -1, color_rgb, 2)
label_trait = cv2.putText(orig, "#{}".format(i+1), (int(x) - 10, int(y)), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color_rgb, 1)
#label_trait = cv2.putText(backgd, "#{}".format(i+1), (int(x) - 10, int(y)), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color_rgb, 1)
#######################################individual leaf curvature computation
#Get rotated bounding ellipse of contour
ellipse = cv2.fitEllipse(c)
#get paramters of ellipse
((xc,yc), (d1,d2), angle) = ellipse
# draw circle at ellipse center
#label_trait = cv2.ellipse(orig, ellipse, color_rgb, 2)
#label_trait = cv2.circle(backgd, (int(xc),int(yc)), 10, color_rgb, -1)
#simplify each leaf as a dot, its size was proportional to leaf area
#track_trait = cv2.circle(tracking_backgd, (int(xc),int(yc)), int(normalized_area_rec[i]*50), (255, 255, 255), -1)
#track_trait = cv2.drawContours(tracking_backgd, [scale_contour(c,0.7)], -1, (255, 255, 255), -1)
#draw major radius
#compute major radius
rmajor = max(d1,d2)/2
rminor = min(d1,d2)/2
if angle > 90:
angle = angle - 90
else:
angle = angle + 90
#print(angle)
xtop = xc + math.cos(math.radians(angle))*rmajor
ytop = yc + math.sin(math.radians(angle))*rmajor
xbot = xc + math.cos(math.radians(angle+180))*rmajor
ybot = yc + math.sin(math.radians(angle+180))*rmajor
label_trait = cv2.line(orig, (int(xtop),int(ytop)), (int(xbot),int(ybot)), color_rgb, 1)
#track_trait = cv2.line(tracking_backgd, (int(xtop),int(ytop)), (int(center_X),int(center_Y)), (255, 255, 255), 3)
c_np = np.vstack(c).squeeze()
x = c_np[:,0]
y = c_np[:,1]
comp_curv = ComputeCurvature(x, y)
curvature = comp_curv.fit(x, y)
#compute temp_index
temp_index = float(cv2.contourArea(c))/cv2.contourArea(cv2.convexHull(c))
#print("temp_index = {0:.2f}... \n".format(temp_index))
#record all traits
leaf_index_rec.append(i)
area_rec.append(cv2.contourArea(c))
curv_rec.append(curvature)
temp_index_rec.append(temp_index)
major_axis_rec.append(rmajor)
minor_axis_rec.append(rminor)
################################################################################
#print('unique labels={0}, len(contours_rec)={1}, len(leaf_index_rec)={2}'.format(np.unique(labels),len(contours_rec),len(leaf_index_rec)))
n_contours = len(contours_rec_sorted)
if n_contours > 0:
print('average curvature = {0:.2f}\n'.format(sum(curv_rec)/n_contours))
else:
n_contours = 1.0
#print(normalized_area_rec)
#print(area_rec)
#return sum(curv_rec)/n_contours, label_trait, track_trait, leaf_index_rec, contours_rec, area_rec, curv_rec, temp_index_rec, major_axis_rec, minor_axis_rec, color_ratio_rec
return sum(curv_rec)/n_contours, label_trait, leaf_index_rec
# convert RGB value to HEX value
def RGB2HEX(color):
return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2]))
'''
def color_quantization(image, mask, save_path, num_clusters):
#grab image width and height
(h, w) = image.shape[:2]
#change the color storage order
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
#apply the mask to get the segmentation of plant
masked_image = cv2.bitwise_and(image, image, mask = mask)
# reshape the image to be a list of pixels
pixels = masked_image.reshape((masked_image.shape[0] * masked_image.shape[1], 3))
############################################################
#Clustering process
###############################################################
# cluster the pixel intensities
clt = MiniBatchKMeans(n_clusters = num_clusters)
#clt = KMeans(n_clusters = args["clusters"])
clt.fit(pixels)
#assign labels to each cluster
labels = clt.fit_predict(pixels)
#obtain the quantized clusters using each label
quant = clt.cluster_centers_.astype("uint8")[labels]
# reshape the feature vectors to images
quant = quant.reshape((h, w, 3))
image_rec = pixels.reshape((h, w, 3))
# convert from L*a*b* to RGB
quant = cv2.cvtColor(quant, cv2.COLOR_RGB2BGR)
image_rec = cv2.cvtColor(image_rec, cv2.COLOR_RGB2BGR)
# display the images
#cv2.imshow("image", np.hstack([image_rec, quant]))
#cv2.waitKey(0)
#define result path for labeled images
result_img_path = save_path + 'cluster_out.png'
# save color_quantization results
cv2.imwrite(result_img_path,quant)
#Get colors and analze them from masked image
counts = Counter(labels)
# sort to ensure correct color percentage
counts = dict(sorted(counts.items()))
center_colors = clt.cluster_centers_
#print(type(center_colors))
# We get ordered colors by iterating through the keys
ordered_colors = [center_colors[i] for i in counts.keys()]
hex_colors = [RGB2HEX(ordered_colors[i]) for i in counts.keys()]
rgb_colors = [ordered_colors[i] for i in counts.keys()]
#######################################################################################
threshold = 60
selected_color = rgb2lab(np.uint8(np.asarray([[rgb_colors[0]]])))
for i in range(num_clusters):
curr_color = rgb2lab(np.uint8(np.asarray([[rgb_colors[i]]])))
diff = deltaE_cie76(selected_color, curr_color)
if (diff < threshold):
print("Color difference value is : {0} \n".format(str(diff)))
###########################################################################################
#print(hex_colors)
index_bkg = [index for index in range(len(hex_colors)) if hex_colors[index] == '#000000']