-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrait_computation_mazie_ear.py
executable file
·2620 lines (1617 loc) · 86.9 KB
/
trait_computation_mazie_ear.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 maize ear traits
Author: suxing liu
Author-email: [email protected]
Created: 2022-09-29
USAGE:
time python3 trait_computation_mazie_ear.py -p ~/example/plant_test/seeds/test_ear/ -ft png -s Lab -c 0 -min 250000
time python3 trait_computation_mazie_ear.py -p ~/example/plant_test/seeds/test_ear/ -ft png -s HSV -c 1 -min 250000
'''
# import 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 scipy.spatial.distance import pdist
from skan import skeleton_to_csgraph, Skeleton, summarize, draw
import imutils
from imutils import perspective
import numpy as np
import argparse
import cv2
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib import collections
import math
import openpyxl
import csv
from tabulate import tabulate
from pathlib import Path
from pylibdmtx.pylibdmtx import decode
import re
import psutil
import concurrent.futures
import multiprocessing
from multiprocessing import Pool
from contextlib import closing
import pandas as pd
import natsort
import warnings
warnings.filterwarnings("ignore")
MBFACTOR = float(1<<20)
def mkdir(path):
"""create folder and path to store the output results
Inputs:
path: result path
Returns:
create path and folder if not exist
"""
# 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
def sort_contours(cnts, method = "left-to-right"):
"""sort contours based on user defined method
Inputs:
cnts: contours extracted from mask image
method: user defined method, default was "left-to-right"
Returns:
sorted_cnts: list of sorted contours
"""
# initialize the reverse flag and sort index
reverse = False
i = 0
# handle if we need to sort in reverse
if method == "right-to-left" or method == "bottom-to-top":
reverse = True
# handle if we are sorting against the y-coordinate rather than
# the x-coordinate of the bounding box
if method == "top-to-bottom" or method == "bottom-to-top":
i = 1
# construct the list of bounding boxes and sort them from top to bottom
boundingBoxes = [cv2.boundingRect(c) for c in cnts]
(sorted_cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes), key=lambda b:b[1][i], reverse=reverse))
# return the list of sorted contours and bounding boxes
return sorted_cnts
# segment mutiple objects in image, for maize ear image, based on the protocal, shoudl be two objects.
def mutilple_objects_seg(orig, channel):
"""segment mutiple objects in image, for maize ear image, based on the protocal, should be only two objects.
Inputs:
orig: image of plant object
Returns:
left_img, right_img: left/right image contains each maize ear on the left/right side
mask_seg_gray:
img_overlay:
cnt_area:
"""
# apply smooth filtering of the image at the color level.
shifted = cv2.pyrMeanShiftFiltering(orig, 21, 70)
# get the dimension of the image
height, width, channels = orig.shape
'''
# 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)
'''
# Convert mean shift image from BRG color space to LAB space and extract B channel
L, A, B = cv2.split(cv2.cvtColor(shifted, cv2.COLOR_BGR2LAB))
# convert the mean shift image to grayscale, then apply Otsu's thresholding
#gray = cv2.cvtColor(shifted, cv2.COLOR_BGR2GRAY)
if channel == 'B':
thresh = cv2.threshold(B, 128, 255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
elif channel == 'A':
thresh = cv2.threshold(A, 128, 255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
elif channel == 'L':
thresh = cv2.threshold(L, 128, 255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
# Taking a matrix of size 25 as the kernel
kernel = np.ones((25,25), np.uint8)
# apply morphological operations to remove noise
thresh_dilation = cv2.dilate(thresh, kernel, iterations=1)
thresh_erosion = cv2.erode(thresh, kernel, iterations=1)
# find contours in the thresholded image
cnts = cv2.findContours(thresh_erosion.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
print("found {} contours!\n".format(len(cnts)))
if len(cnts) > 1:
# sort the contour based on area size from largest to smallest, and get the first two max contours
cnts_sorted = sorted(cnts, key = cv2.contourArea, reverse = True)[0:2]
# sort the contours from left to right
cnts_sorted = sort_contours(cnts_sorted, method = "left-to-right")
#print("cv2.contourArea(cnts_sorted[0]), cv2.contourArea(cnts_sorted[1])")
#print(cv2.contourArea(cnts_sorted[0]), cv2.contourArea(cnts_sorted[1]))
#print(len(cnts_sorted))
if len(cnts) < 2:
print("select objects failed!\n")
cnts_sorted = cnts_sorted[0]
else:
# if two contours are connectedm remove the significantly smaller one in size
if cv2.contourArea(cnts_sorted[0]) > 10*cv2.contourArea(cnts_sorted[1]):
cnts_sorted = cnts_sorted[:1]
# initialize variables to record the centera, area of contours
center_locX = []
center_locY = []
cnt_area = [0] * 2
# initialize empty mask image
img_thresh = np.zeros(orig.shape, np.uint8)
# initialize background image to draw the contours
img_overlay_bk = orig
# loop over the selected contours
for idx, c in enumerate(cnts_sorted):
# compute the center of the contour
M = cv2.moments(c)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
# record the center coordinates
center_locX.append(cX)
center_locY.append(cY)
# get the contour area
cnt_area[idx] = cv2.contourArea(c)
# draw the contour and center of the shape on the image
img_overlay = cv2.drawContours(img_overlay_bk, [c], -1, (0, 255, 0), 2)
mask_seg = cv2.drawContours(img_thresh, [c], -1, (255,255,255),-1)
#center_result = cv2.circle(img_thresh, (cX, cY), 14, (0, 0, 255), -1)
img_overlay = cv2.putText(img_overlay_bk, "{}".format(idx +1), (cX - 20, cY - 20), cv2.FONT_HERSHEY_SIMPLEX, 5.5, (255, 0, 0), 5)
# get the middle point coordinate of the two centers of the contours
divide_X = int(sum(center_locX) / len(center_locX))
divide_Y = int(sum(center_locY) / len(center_locY))
# get the left and right segmentation of the image
left_img = orig[0:height, 0:divide_X]
right_img = orig[0:height, divide_X:width]
# convert the mask image to gray format
mask_seg_gray = cv2.cvtColor(mask_seg, cv2.COLOR_BGR2GRAY)
else:
left_img=right_img=mask_seg_gray=img_overlay=cnt_area=0
return left_img, right_img, mask_seg_gray, img_overlay, cnt_area
# color clustering based object segmentation
def color_cluster_seg(image, args_colorspace, args_channels, args_num_clusters):
"""color clustering based object segmentation
Inputs:
image: image contains the plant objects
args_colorspace: user-defined color space for clustering
args_channels: user-defined color channel for clustering
args_num_clusters: number of clustering
Returns:
img_thresh: mask image with the segmentation of the plant object
"""
# 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
#image = cv2.pyrMeanShiftFiltering(image, 21, 70)
# 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)
# get the dimension of image
(width, height, n_channel) = image.shape
# 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)
# clean the border of mask image
if np.count_nonzero(thresh) > 0:
thresh_cleaned = clear_border(thresh)
else:
thresh_cleaned = thresh
# get the connected Components in the mask image
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
# get all connected Components's area value
sizes = stats[1:, cv2.CC_STAT_AREA]
# remove background component
nb_components = nb_components - 1
# create an empty mask image and fill the detected connected components
img_thresh = np.zeros([width, height], dtype=np.uint8)
#for every component in the image, keep it only if it's above min_size
for i in range(0, nb_components):
if (sizes[i] >= min_size):
img_thresh[output == i + 1] = 255
#if mask contains mutiple non-conected parts, combine them into one.
contours, hier = cv2.findContours(img_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if len(contours) > 1:
print("mask contains mutiple non-connected parts, combine them into one\n")
# create an size 10 kernel
kernel = np.ones((10,10), np.uint8)
# image dilation
dilation = cv2.dilate(img_thresh.copy(), kernel, iterations = 1)
# image closing
closing = cv2.morphologyEx(dilation, cv2.MORPH_CLOSE, kernel)
# use the final closing result as mask
img_thresh = closing
return img_thresh
def percentage(part, whole):
"""compute percentage value
Inputs:
part, whole: the part and whole value
Returns:
string type of the percentage in decimals
"""
#percentage = "{:.0%}".format(float(part)/float(whole))
percentage = "{:.2f}".format(float(part)/float(whole))
return str(percentage)
def midpoint(ptA, ptB):
"""compute middle point of two points in 2D coordinates
Inputs:
ptA, ptB: coordinates of two points
Returns:
coordinates of the middle point
"""
return ((ptA[0] + ptB[0]) * 0.5, (ptA[1] + ptB[1]) * 0.5)
def adaptive_threshold_external(img):
"""compute thresh image using adaptive threshold Method
Inputs:
img: image data
Returns:
mask_external: segmentation mask for external contours
trait_img: original image overlay with bounding rect and contours
"""
# obtain image dimension
img_height, img_width, n_channels = img.shape
orig = img.copy()
# convert the image to grayscale and blur it slightly
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# set the parameters for adoptive threshholding method
GaussianBlur_ksize = 5
blockSize = 41
weighted_mean = 10
# adoptive threshholding method to the masked image from mutilple_objects_seg
#(thresh_adaptive_threshold, maksed_img_adaptive_threshold) = adaptive_threshold(gray, GaussianBlur_ksize, blockSize, weighted_mean)
# blurring it . Applying Gaussian blurring with a GaussianBlur_ksize×GaussianBlur_ksize kernel
# helps remove some of the high frequency edges in the image that we are not concerned with and allow us to obtain a more “clean” segmentation.
blurred = cv2.GaussianBlur(gray, (GaussianBlur_ksize, GaussianBlur_ksize), 0)
# adaptive method to be used. 'ADAPTIVE_THRESH_MEAN_C' or 'ADAPTIVE_THRESH_GAUSSIAN_C'
thresh_adaptive_threshold = cv2.adaptiveThreshold(blurred, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 41, 10)
# apply individual object mask
maksed_img_adaptive_threshold = cv2.bitwise_and(orig, orig.copy(), mask = ~thresh_adaptive_threshold)
#find contours and get the external one
contours, hier = cv2.findContours(thresh_adaptive_threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# sort the contours based on area from largest to smallest
contours_sorted = sorted(contours, key = cv2.contourArea, reverse = True)
#contours_sorted = contours
#select correct contours
##########################################################################
rect_area_rec = []
# save all the boundingRect area for each contour
for index, c in enumerate(contours_sorted):
#get the bounding rect
(x, y, w, h) = cv2.boundingRect(c)
rect_area_rec.append(w*h)
# sort all contours according to the boundingRect area size in descending order
idx_sort = [i[0] for i in sorted(enumerate(rect_area_rec), key=lambda k: k[1], reverse=True)]
# initialize parametrs for first 3 biggest boundingRect
rect_center_rec = []
rect_size_rec = []
# loop to record the center and size of the three boundingRect
for index, value in enumerate(idx_sort[0:3]):
# get the contour by index
c = contours_sorted[value]
#get the bounding rect
(x, y, w, h) = cv2.boundingRect(c)
center = (x, y)
rect_center_rec.append(center)
rect_size_rec.append(w*h)
# extarct x value from center coordinates
x_center = [i[0] for i in rect_center_rec]
#######################################################################################3
# choose the adjacent center pair among all three centers
if ((abs(x_center[0] - x_center[2]) < abs(x_center[0] - x_center[1])) or (abs(x_center[1] - x_center[2]) < abs(x_center[0] - x_center[2]))) \
and ((abs(x_center[0] - x_center[1]) > abs(x_center[0] - x_center[2])) or (abs(x_center[0] - x_center[1]) > abs(x_center[1] - x_center[2]))):
print("select objects successful...\n")
else:
# compute the average distance between adjacent center pair
avg_dist = sum(pdist(rect_center_rec))/len(pdist(rect_center_rec))
# get the index of the min distance
idx_min = [i for i, j in enumerate(pdist(rect_center_rec)) if j < avg_dist]
# choose the potiential candidate from the adjacent pair
rect_size_rec_sel = rect_size_rec[idx_min[0]: int(idx_min[0]+2)]
# get the index of the false contour
idx_delete = np.argmin(rect_size_rec_sel)
# delete the index of the false contour
idx_sort.pop(idx_delete)
####################################################################################3
area_rec = []
trait_img = orig
mask = np.zeros(gray.shape, dtype = "uint8")
for index, value in enumerate(idx_sort):
if index < 2:
# visualize only the two external contours and its bounding box
c = contours_sorted[value]
# compute the convex hull of the contour
hull = cv2.convexHull(c)
# compute the area of the convex hull
hullArea = float(cv2.contourArea(hull))
# save the convex hull area
area_rec.append(hullArea)
#get the bounding rect
(x, y, w, h) = cv2.boundingRect(c)
# draw a rectangle to visualize the bounding rect
#trait_img = cv2.drawContours(orig, c, -1, (255, 255, 0), 3)
#area_c_cmax = cv2.contourArea(c)
trait_img = cv2.putText(orig, "#{0}".format(index), (int(x) - 10, int(y) - 20),cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 2)
# draw a green rectangle to visualize the bounding rect
trait_img = cv2.rectangle(orig, (x, y), (x+w, y+h), (255, 255, 0), 4)
# draw convexhull in red color
trait_img = cv2.drawContours(orig, [hull], -1, (0, 0, 255), 4)
mask_external = cv2.drawContours(mask, [hull], -1, (255, 255, 255), -1)
# compute the average area of the ear objects
#external_contour_area = sum(area_rec)/len(area_rec)
#define result path for labeled images
#result_img_path = save_path + str(filename[0:-4]) + '_ctr.png'
# save results
#cv2.imwrite(result_img_path, trait_img)
#define result path for labeled images
#result_img_path = save_path + str(filename[0:-4]) + '_mask_external.png'
# save results
#cv2.imwrite(result_img_path, mask_external)
return mask_external, trait_img
def comp_external_contour(orig, thresh, img_overlay):
"""compute the parameters of the external contour of the plant object
Inputs:
orig: image contains the plant objects
thresh: mask of the plant object
Returns:
trait_img: input image overlayed with external contour and bouding box
cnt_area: area occupied by the maize ear in the image
cnt_width, cnt_height: width and height of the tassel
"""
#contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
# get the dimension and color channel of the input image
img_height, img_width, img_channels = orig.shape
# initialize parameters
trait_img = orig.copy()
area = 0
kernel_area_ratio = 0
w=h=0
####################################################################################
#find contours and get the external one
contours, hier = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# sort the contours based on area from largest to smallest
contours = sorted(contours, key = cv2.contourArea, reverse = True)
# sort the contours from left to right
contours_sorted = sort_contours(contours, method="left-to-right")
# initialize parameters
area_c_cmax = 0
area_holes_sum = 0
cnt_area = [0] * 2
cnt_x = []
cnt_y = []
cnt_width = []
cnt_height = []
# initialize background image to draw the contours
orig = img_overlay
###########################################################################
# compute all the contours and their areas
for index, c in enumerate(contours_sorted):
# visualize only the two external contours and its bounding box
if index < 2:
#get the bounding rect
(x, y, w, h) = cv2.boundingRect(c)
# draw a rectangle to visualize the bounding rect
trait_img = cv2.drawContours(orig, c, -1, (255, 255, 0), 1)
#print("ROI {} detected ...\n".format(index+1))
# draw a green rectangle to visualize the bounding rect
trait_img = cv2.rectangle(orig, (x, y), (x+w, y+h), (255, 255, 0), 4)
# compute the center of the contour
M = cv2.moments(c)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
# draw the center of the shape on the image
#trait_img = cv2.circle(orig, (cX, cY), 7, (255, 255, 255), -1)
#trait_img = cv2.putText(orig, "center", (cX - 20, cY - 20),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
#################################################################################
# compute the four coordinates to get the center of bounding box
tl = (x, y+h*0.5)
tr = (x+w, y+h*0.5)
br = (x+w*0.5, y)
bl = (x+w*0.5, y+h)
# compute the midpoint between bottom-left and bottom-right coordinates
(tltrX, tltrY) = midpoint(tl, tr)
(blbrX, blbrY) = midpoint(bl, br)
# draw the midpoints on the image
trait_img = cv2.circle(orig, (int(tltrX), int(tltrY)), 15, (255, 0, 0), -1)
trait_img = cv2.circle(orig, (int(blbrX), int(blbrY)), 15, (255, 0, 0), -1)
# draw lines between the midpoints
trait_img = cv2.line(orig, (int(x), int(y+h*0.5)), (int(x+w), int(y+h*0.5)), (255, 0, 255), 6)
trait_img = cv2.line(orig, (int(x+w*0.5), int(y)), (int(x+w*0.5), int(y+h)), (255, 0, 255), 6)
# compute the convex hull of the contour
hull = cv2.convexHull(c)
# draw convexhull in red color
trait_img = cv2.drawContours(orig, [hull], -1, (0, 0, 255), 2)
area_c_cmax = cv2.contourArea(c)
#hull_area = cv2.contourArea(hull)
# record the traits of each contour
cnt_area[index] = (area_c_cmax)
cnt_width.append(w)
cnt_height.append(h)
cnt_x.append(x)
cnt_y.append(y)
print("Contour {0} shape info: width = {1:.2f}, height = {2:.2f}, area = {3:.2f}\n".format(index+1, w, h, area_c_cmax))
return trait_img, cnt_area, cnt_width, cnt_height, cnt_x, cnt_y
# convert RGB value to HEX format
def RGB2HEX(color):
"""convert RGB value to HEX format
Inputs:
color: color in rgb format
Returns:
color in hex format
"""
return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2]))
# get the color pallate
def get_cmap(n, name = 'hsv'):
"""get n kinds of colors from a color palette
Inputs:
n: number of colors
name: the color palette choosed
Returns:
plt.cm.get_cmap(name, n): 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.cm.get_cmap(name, n)
def color_region(image, mask, save_path, num_clusters):
"""dominant color clustering method to compute the color distribution
Inputs:
image: image contains different colors
mask: mask of the plant object
save_path: result path
num_clusters: number of clusters for computation
Returns:
rgb_colors: center color values in rgb format for every cluster
counts: percentage of each color cluster
hex_colors: center color values in hex format for every cluster
"""
# read the image
#grab image width and height
(h, w) = image.shape[:2]
#apply the mask to get the segmentation of plant
masked_image_ori = cv2.bitwise_and(image, image, mask = mask)
#define result path for labeled images
result_img_path = save_path + 'masked.png'
cv2.imwrite(result_img_path, masked_image_ori)
# convert to RGB
image_RGB = cv2.cvtColor(masked_image_ori, cv2.COLOR_BGR2RGB)
# reshape the image to a 2D array of pixels and 3 color values (RGB)
pixel_values = image_RGB.reshape((-1, 3))
# convert to float
pixel_values = np.float32(pixel_values)
# define stopping criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.2)
# number of clusters (K)
#num_clusters = 5
compactness, labels, (centers) = cv2.kmeans(pixel_values, num_clusters, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
# convert back to 8 bit values
centers = np.uint8(centers)
# flatten the labels array
labels_flat = labels.flatten()
# convert all pixels to the color of the centroids
segmented_image = centers[labels_flat]
# reshape back to the original image dimension
segmented_image = segmented_image.reshape(image_RGB.shape)
# convert image format from RGB to BGR for OpenCV
segmented_image_BRG = cv2.cvtColor(segmented_image, cv2.COLOR_RGB2BGR)
#define result path for labeled images
result_img_path = save_path + 'clustered.png'
cv2.imwrite(result_img_path, segmented_image_BRG)
#Show only one chosen cluster
#masked_image = np.copy(image)
masked_image = np.zeros_like(image_RGB)
# convert to the shape of a vector of pixel values
masked_image = masked_image.reshape((-1, 3))
# color (i.e cluster) to render
#cluster = 2
# get the color template
cmap = get_cmap(num_clusters+1)
#clrs = sns.color_palette('husl', n_colors = num_clusters) # a list of RGB tuples
# convert colors format
color_conversion = interp1d([0,1],[0,255])
# loop over all the clusters
for cluster in range(num_clusters):
print("Processing color cluster {0} ...\n".format(cluster))
# choose current label image of same cluster
masked_image[labels_flat == cluster] = centers[cluster]
#convert back to original shape
masked_image_rp = masked_image.reshape(image_RGB.shape)
# convert the maksed image from BGR to GRAY
gray = cv2.cvtColor(masked_image_rp, cv2.COLOR_BGR2GRAY)
# threshold the image,
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)[1]
# get the external contours
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
#c = max(cnts, key=cv2.contourArea)
# if no contour was found
if not cnts:
print("findContours is empty")
else:
# loop over the (unsorted) contours and draw them
for (i, c) in enumerate(cnts):
# draw contours on the masked_image_rp
result = cv2.drawContours(masked_image_rp, c, -1, color_conversion(np.random.random(3)), 2)
#result = cv2.drawContours(masked_image_rp, c, -1, color_conversion(clrs[cluster]), 2)
#result = result(np.where(result == 0)== 255)
result[result == 0] = 255