-
Notifications
You must be signed in to change notification settings - Fork 0
/
trait_computation_mazie_ear_upgrade.py
executable file
·2369 lines (1413 loc) · 75.7 KB
/
trait_computation_mazie_ear_upgrade.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: suxingliu@gmail.com
Created: 2022-09-29
USAGE:
time python3 trait_computation_mazie_ear_upgrade.py -p ~/example/plant_test/seeds/test/ -ft png -s Lab -c 0 -ne 5 -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.csr import skeleton_to_csgraph
from skan import 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
from rembg import remove
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 adaptive_threshold(masked_image, GaussianBlur_ksize, blockSize, weighted_mean):
"""compute thresh image using adaptive threshold Method
Inputs:
maksed_img: masked image contains only target objects
GaussianBlur_ksize: Gaussian Kernel Size
blockSize: size of the pixelneighborhood used to calculate the threshold value
weighted_mean: the constant used in the both methods (subtracted from the mean or weighted mean).
Returns:
thresh_adaptive_threshold: thresh image using adaptive thrshold Method
maksed_img_adaptive_threshold: masked image using thresh_adaptive_threshold
"""
ori = masked_image.copy()
if len(ori.shape)> 2:
# convert the image to grayscale and blur it slightly
gray = cv2.cvtColor(masked_image, cv2.COLOR_BGR2GRAY)
else:
gray = ori
# 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, blockSize, weighted_mean)
# apply individual object mask
maksed_img_adaptive_threshold = cv2.bitwise_and(ori, ori.copy(), mask = ~thresh_adaptive_threshold)
return thresh_adaptive_threshold, maksed_img_adaptive_threshold
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
def mutilple_objects_detection(orig):
"""segment mutiple objects in image, for maize ear imagem, based on the protocal, number of ears ranges form 1 to 5.
Inputs:
orig: image of plant object
Returns:
images: each image contains one maize ear on the left/right side
"""
# remove the back ground using Rembg is a tool to remove images background.
orig_mask = remove(orig.copy(), only_mask=True)
orig_forground = remove(orig.copy())
# get the dimension of the image
#height, width, channels = orig_foreground.shape
return orig_mask, orig_forground
# segment mutiple objects in image, for maize ear image, based on the protocal, shoudl be two objects.
def mutilple_objects_seg(orig, channel, size_kernel):
"""segment mutiple objects in image, for maize ear image, based on the protocal, should be less than 5 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)
#shifted = cv2.pyrMeanShiftFiltering(orig, 21, 10)
# 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_ker as the kernel
#size_kernel = 10
kernel = np.ones((size_kernel, size_kernel), 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)
# 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:n_ear]
# 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("left-to-right")
#print(len(cnts_sorted))
# initialize variables to record the centers, area of contours
center_locX = []
center_locY = []
cnt_area = [0] * n_ear
# 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)
#return left_img, right_img, mask_seg_gray, img_overlay, cnt_area
return mask_seg_gray
# 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...")
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
'''
# 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 barcode_detect(img_ori):
"""Read barcode in the image and decode barcode info
Inputs:
img_ori: image contains the barcode region
Returns:
tag_info: decoded barcode information
"""
# get the dimension of the image
height, width = img_ori.shape[:2]
# decode the barcode info
barcode_info = decode((img_ori.tobytes(), width, height))
# if barcode info was not empty
if len(barcode_info) > 0:
# get the decoded barcode info data value as string
barcode_str = str(barcode_info[0].data)
#print('Decoded data:', barcode_str)
#print(decoded_object.rect.top, decoded_object.rect.left)
#print(decoded_object.rect.width, decoded_object.rect.height)
# accquire the barcode info and remove extra characters
tag_info = re.findall(r"'(.*?)'", barcode_str, re.DOTALL)
tag_info = " ".join(str(x) for x in tag_info)
tag_info = tag_info.replace("'", "")
print("Tag info: {}\n".format(tag_info))
else:
# print warning if barcode info was empty
print("barcode information was not readable!\n")
tag_info = 'Unreadable'
return tag_info
def marker_detect(img_ori, template, method, selection_threshold):
"""Detect marker in the image
Inputs:
img_ori: image contains the marker region
template: preload marker template image
method: method used to compute template matching
selection_threshold: thresh value for accept the template matching result
Returns:
marker_img: matching region image with marker object
thresh: mask image of the marker region
coins_width_contour: computed width result based on contour of the object
coins_width_circle: computed width result based on min circle of the object
"""
# load the image, clone it for output
img_rgb = img_ori.copy()
# convert it to grayscale
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
# store width and height of template in w and h
w, h = template.shape[::-1]
# Perform match operations.
#res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
# Perform template matching operations.
res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF)
#res = cv2.matchTemplate(img_gray, template, cv2.TM_SQDIFF)
# Specify a threshold for template detection as selection_threshold
# Store the coordinates of matched area in a numpy array
loc = np.where( res >= selection_threshold)
if len(loc):
# unwarp the template mathcing result
(y,x) = np.unravel_index(res.argmax(), res.shape)
# get the template matching region coordinates
(min_val, max_val, min_loc, max_loc) = cv2.minMaxLoc(res)
(startX, startY) = max_loc
endX = startX + template.shape[1]
endY = startY + template.shape[0]
# get the sub image with matching region
marker_img = img_ori[startY:endY, startX:endX]
marker_overlay = marker_img
# load the marker image, convert it to grayscale
marker_img_gray = cv2.cvtColor(marker_img, cv2.COLOR_BGR2GRAY)
# load the image and perform pyramid mean shift filtering to aid the thresholding step
shifted = cv2.pyrMeanShiftFiltering(marker_img, 21, 51)
# convert the mean shift image to grayscale, then apply Otsu's thresholding
gray = cv2.cvtColor(shifted, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
# detect contours in the mask and grab the largest one
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
largest_cnt = max(cnts, key=cv2.contourArea)
#print("[INFO] {} unique contours found in marker_img\n".format(len(cnts)))
# compute the radius of the detected coin
# calculate the center of the contour
M = cv2.moments(largest_cnt )
x = int(M["m10"] / M["m00"])
y = int(M["m01"] / M["m00"])
# calculate the radius of the contour from area (I suppose it's a circle)
area = cv2.contourArea(largest_cnt)
radius = np.sqrt(area/math.pi)
coins_width_contour = 2* radius
# draw a circle enclosing the object
((x, y), radius) = cv2.minEnclosingCircle(largest_cnt)
coins_width_circle = 2* radius
else:
print("no matching template was found\n")
return marker_img, thresh, coins_width_contour, coins_width_circle
def adjust_gamma(image, gamma):
"""Adjust the gamma value to increase the brightness of image
Inputs:
image: image
gamma: gamma value used to adjust
Returns:
cv2.LUT(image, table): adjusted image with gamma correction
"""
# build a lookup table mapping the pixel values [0, 255] to
# their adjusted gamma values
invGamma = 1.0 / gamma
table = np.array([((i / 255.0) ** invGamma) * 255
for i in np.arange(0, 256)]).astype("uint8")
# apply gamma correction using the lookup table
return cv2.LUT(image, table)
def closest_center(pt, pt_list):
"""compute index of closest point between current point and a list of points
Inputs:
pt: coordinate of current point
pt_list: coordinates of a list of points
Returns:
min_dist_index: index of closest point