-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmart_release.py
executable file
·2329 lines (1391 loc) · 75.9 KB
/
smart_release.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, solidity, max_width, max_height, avg_curv, color_cluster) by paralell processing
Author: suxing liu
Author-email: [email protected]
Created: 2024-02-29
USAGE:
python3 smart_release.py -p ~/example/AR_data/test/ -ai 1
python3 smart_release.py -p ~/example/AR_data/test/ -ai 0
'''
# import the necessary packages
import subprocess, os, glob, sys
import utils, shutil
from collections import Counter
from collections import OrderedDict
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 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 rembg import remove
from matplotlib import collections
import matplotlib.colors
import pathlib
MBFACTOR = float(1<<20)
# check file type
def check_file_type(image_folder_path, allowed_extensions=None):
if allowed_extensions is None:
allowed_extensions = ['.jpg', '.png', '.jpeg']
no_files_in_folder = len(glob.glob(image_folder_path+"/*"))
extension_type = ""
no_files_allowed = 0
for ext in allowed_extensions:
no_files_allowed = len(glob.glob(image_folder_path+"/*"+ext))
if no_files_allowed > 0:
extension_type = ext
return extension_type
# curvature computation calss
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
# color label class
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({
"dark skin": (115, 82, 68),
"light skin": (194, 150, 130),
"blue sky": (98, 122, 157),
"foliage": (87, 108, 67),
"blue flower": (133, 128, 177),
"bluish green": (103, 189, 170),
"orange": (214, 126, 44),
"purplish blue": (8, 91, 166),
"moderate red": (193, 90, 99),
"purple": (94, 60, 108),
"yellow green": (157, 188, 64),
"orange yellow": (224, 163, 46),
"blue": (56, 61, 150),
"green": (70, 148, 73),
"red": (175, 54, 60),
"yellow": (231, 199, 31),
"magneta": (187, 86, 149),
"cyan": (8, 133, 161),
"white": (243, 243, 242),
"neutral 8": (200, 200, 200),
"neutral 6.5": (160, 160, 160),
"neutral 5": (122, 122, 121),
"neutral 3.5": (85, 85, 85),
"black": (52, 52, 52)})
# 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)
#print("color_checker values:{}\n".format(self.lab))
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)
#print("mean = {0}, row = {1}, d = {2}, i = {3}\n".format(mean, row[0], d, i))
# 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]], mean
def label_c(self, lab_color_value):
# 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], lab_color_value)
#print("mean = {0}, row = {1}, d = {2}, i = {3}\n".format(mean, row[0], d, i))
# 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
#printpath + ' folder constructed!'
# make dir
os.makedirs(path)
return True
else:
# if exists, return
shutil.rmtree(path)
os.makedirs(path)
print("{} path exists!\n".format(path))
return False
# find the closest point wihch minimize the distance between current point and the center of image
def closest_node(pt, pts):
closest_index = dist.cdist([pt], pts).argmin()
return closest_index
# gets the bounding boxes of contours and calculates the distance between two rectangles
def calculate_contour_distance(contour1, contour2):
x1, y1, w1, h1 = cv2.boundingRect(contour1)
c_x1 = x1 + w1/2
c_y1 = y1 + h1/2
x2, y2, w2, h2 = cv2.boundingRect(contour2)
c_x2 = x2 + w2/2
c_y2 = y2 + h2/2
return max(abs(c_x1 - c_x2) - (w1 + w2)/2, abs(c_y1 - c_y2) - (h1 + h2)/2)
# using numpy.concatenate because each contour is just a numpy array of points
def merge_contours(contour1, contour2):
return np.concatenate((contour1, contour2), axis=0)
#return np.vstack([contour1, contour2])
#group contours such that one contour corresponds to one object.
#when some contours that belong to the same object are detected separately
def agglomerative_cluster(contours, threshold_distance=40.0):
current_contours = contours
while len(current_contours) > 1:
min_distance = None
min_coordinate = None
for x in range(len(current_contours)-1):
for y in range(x+1, len(current_contours)):
distance = calculate_contour_distance(current_contours[x], current_contours[y])
if min_distance is None:
min_distance = distance
min_coordinate = (x, y)
elif distance < min_distance:
min_distance = distance
min_coordinate = (x, y)
if min_distance < threshold_distance:
index1, index2 = min_coordinate
current_contours[index1] = merge_contours(current_contours[index1], current_contours[index2])
del current_contours[index2]
else:
break
return current_contours
# segment foreground object using color clustering method
def color_cluster_seg(image, args_colorspace, args_channels, args_num_clusters):
image_LAB = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)
cl = ColorLabeler()
# 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)
(height, width, n_channel) = image.shape
if n_channel > 1:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
else:
gray = image
# 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, at lease 2 cluster including background
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)
'''
if args['out_boundary']:
thresh_cleaned = (thresh)
else:
if np.count_nonzero(thresh) > 0:
thresh_cleaned = clear_border(thresh)
else:
thresh_cleaned = thresh
'''
if np.count_nonzero(thresh) > 0:
thresh_cleaned = clear_border(thresh)
else:
thresh_cleaned = thresh
(numLabels, labels, 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
# extract the connected component statistics for the current label
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 = np.delete(centroids,(0), axis=0)
#print("Coord_centroids {}\n".format(centroids[1][1]))
#print("[width, height] {} {}\n".format(width, height))
numLabels = numLabels - 1
'''
################################################################################################
if args['max_size'] == 1000000:
max_size = width*height
else:
max_size = args['max_size']
# initialize an output mask
mask = np.zeros(gray.shape, dtype="uint8")
# loop over the number of unique connected component labels, skipping
# over the first label (as label zero is the background)
for i in range(1, numLabels):
# extract the connected component statistics for the current label
x = stats[i, cv2.CC_STAT_LEFT]
y = stats[i, cv2.CC_STAT_TOP]
w = stats[i, cv2.CC_STAT_WIDTH]
h = stats[i, cv2.CC_STAT_HEIGHT]
area = stats[i, cv2.CC_STAT_AREA]
# define plant object center
#x_center = int(width // 3)
#y_center = int(height // 2)
#print("x_center,y_center = {} {}".format(x_center, y_center))
#print("x,y = {} {}".format(x, y))
#distance = math.dist((x_center, y_center), (x, y))
#print("ditance = {}\n".format(distance))
#if w>img_width*0.01 and h>img_height*0.01:
# ensure the width, height, and area are all neither too small
# nor too big
keepWidth = w > width*0.01 and w < 50000
keepHeight = h > height*0.01 and h < 50000
keepArea = area > min_size and area < max_size
#keepDistance = distance < 800
if all((keepWidth, keepHeight, keepArea)):
# ensure the connected component we are examining passes all three tests
#if all((keepWidth, keepHeight)):
#if keepArea:
# construct a mask for the current connected component and
# then take the bitwise OR with the mask
print("[INFO] keeping connected component '{}'".format(i))
componentMask = (labels == i).astype("uint8") * 255
mask = cv2.bitwise_or(mask, componentMask)
img_thresh = mask
###################################################################################################
size_kernel = 5
#if mask contains mutiple non-connected 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-conected parts, combine them into one\n")
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 args["cue_color"] == 1:
img_mask = np.zeros([height, width], dtype="uint8")
#img_mask = np.zeros(gray.shape, dtype="uint8")
# filter contours by color cue
for idx, c in enumerate(contours):
# compute the center of the contour
M = cv2.moments(c)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
(color_name, color_value) = cl.label(image_LAB, c)
#img_thresh = cv2.putText(img_thresh, "{}".format(color_name), (int(cX), int(cY)), cv2.FONT_HERSHEY_SIMPLEX, 1.8, (255, 0, 0), 2)
print(color_name)
keepColor = color_name == "foliage" or color_name == "green"
#or color_name == "dark skin" or color_name == "light skin"
if keepColor:
#img_mask = cv2.drawContours(img_mask, c, -1, (255), -1)
img_mask = cv2.drawContours(image=img_mask, contours=[c], contourIdx=-1, color=(255,255,255), thickness=cv2.FILLED)
#img_mask = cv2.fillPoly(img_mask, pts = [contours], color =(255,255,255))
img_thresh = img_mask
'''
###################################################################################################
# use location based selection of plant object, keep the closest componnent to the center
'''
if args["cue_loc"] == 1:
(contours, hier) = cv2.findContours(img_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if len(contours) > 1:
# location based selection of plant object
(numLabels, labels, stats, centroids) = cv2.connectedComponentsWithStats(img_thresh, connectivity = 8)
#keep the center component
x_center = int(width // 2)
y_center = int(height // 2)
Coord_centroids = np.delete(centroids,(0), axis=0)
#print("x_center, y_center = {} {}".format(x_center,y_center))
#print("centroids = {}".format(centroids))
#finding closest point among the grid points list ot the M coordinates
idx_closest = closest_node((x_center,y_center), Coord_centroids) + 1
print("idx_closest = {} {}".format(idx_closest, Coord_centroids[idx_closest]))
for i in range(1, numLabels):
(cX, cY) = (centroids[i][0], centroids[i][1])
#print(cX, cY)
img_thresh = cv2.putText(img_thresh, "#{}".format(i), (int(cX), int(cY)), cv2.FONT_HERSHEY_SIMPLEX, 1.8, (255, 0, 0), 2)
img_thresh = cv2.putText(img_thresh, "center", (int(x_center), int(y_center)), cv2.FONT_HERSHEY_SIMPLEX, 2.8, (255, 0, 0), 2)
if numLabels > 1:
img_thresh = np.zeros([height, width], dtype=np.uint8)
img_thresh[labels == idx_closest] = 255
'''
###################################################################################################
#check adjacent contours when mutiple disconnected objects are detected
#return img_thresh
#return thresh_cleaned
return img_thresh
# compute medial axis from the mask of image
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
# compute the skeleton from the mask of image
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
# segmentation using wateshed method
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
# compute percentage as two decimals value
def percentage(part, whole):
#percentage = "{:.0%}".format(float(part)/float(whole))
percentage = "{:.2f}".format(float(part)/float(whole))
return str(percentage)
# convert image from RGB to LAB color space
def image_BRG2LAB(image_file):
# extarct path and name of the image file
abs_path = os.path.abspath(image_file)
filename, file_extension = os.path.splitext(abs_path)
# extract the base name
base_name = os.path.splitext(os.path.basename(filename))[0]
# get the image file name
image_file_name = Path(image_file).name
print("Converting image {0} from RGB to LAB color space\n".format(str(image_file_name)))
# load the input image
image = cv2.imread(image_file)
# change to RGB space
image_RGB = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
#plt.imshow(image_RGB)
#plt.show()
# get pixel color
pixel_colors = image_RGB.reshape((np.shape(image_RGB)[0]*np.shape(image_RGB)[1], 3))
norm = colors.Normalize(vmin=-1.,vmax=1.)
norm.autoscale(pixel_colors)
pixel_colors = norm(pixel_colors).tolist()
#pixel_colors_array = np.asarray(pixel_colors)
#pixel_colors = pixel_colors.ravel()
# change to lab space
image_LAB = cv2.cvtColor(image, cv2.COLOR_BGR2LAB )
(L_chanel, A_chanel, B_chanel) = cv2.split(image_LAB)
######################################################################
fig = plt.figure(figsize=(8.0, 6.0))
axis = fig.add_subplot(1, 1, 1, projection="3d")
axis.scatter(L_chanel.flatten(), A_chanel.flatten(), B_chanel.flatten(), facecolors = pixel_colors, marker = ".")
axis.set_xlabel("L:ightness")
axis.set_ylabel("A:red/green coordinate")
axis.set_zlabel("B:yellow/blue coordinate")
# save segmentation result
result_file = (result_path + base_name + '_lab' + file_extension)
plt.savefig(result_file, bbox_inches = 'tight', dpi = 1000)
# detect the circle marker in image
def circle_detection(image):
"""Detecting Circles in Images using OpenCV and Hough Circles
Inputs:
image: image loaded
Returns:
circles: detcted circles
circle_detection_img: circle overlayed with image
diameter_circle: diameter of detected circle
"""
# create background image for drawing the detected circle
output = image.copy()
circle_detection_img = image.copy()
# obtain image dimension
img_height, img_width, n_channels = image.shape
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#backup input image
circle_detection_img = image.copy()
# change image from RGB to Gray scale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# apply blur filter
blurred = cv2.medianBlur(gray, 25)
# setup parameters for circle detection
# This parameter is the inverse ratio of the accumulator resolution to the image resolution default 1.5
#(see Yuen et al. for more details). Essentially, the larger the dp gets, the smaller the accumulator array gets.
dp = 1.0
#Minimum distance between the center (x, y) coordinates of detected circles.
#If the minDist is too small, multiple circles in the same neighborhood as the original may be (falsely) detected.
#If the minDist is too large, then some circles may not be detected at all.
minDist = 100
#Gradient value used to handle edge detection in the Yuen et al. method.
#param1 = 30
#accumulator threshold value for the cv2.HOUGH_GRADIENT method.
#The smaller the threshold is, the more circles will be detected (including false circles).
#The larger the threshold is, the more circles will potentially be returned.
#param2 = 30
#Minimum/Maximum size of the radius (in pixels).
#minRadius = 80
#maxRadius = 120
# detect circles in the image
#circles = cv2.HoughCircles(blurred, cv2.HOUGH_GRADIENT, 1.2, minDist, param1=param1, param2=param2, minRadius=minRadius, maxRadius=maxRadius)
# detect circles in the image
circles = cv2.HoughCircles(blurred, cv2.HOUGH_GRADIENT, dp, minDist)
# initialize diameter of detected circle
diameter_circle = 0
circle_center_coord = []
circle_center_radius = []
idx_closest = 0
# At leaset one circle is found
if circles is not None:
# Get the (x, y, r) as integers, convert the (x, y) coordinates and radius of the circles to integers
circles = np.round(circles[0, :]).astype("int")
if len(circles) < 2:
print("Only one circle was found!\n")
else:
print("More than one circles were found!\n")
idx_closest = 0
#cv2.circle(output, (x, y), r, (0, 255, 0), 2)
# loop over the circles and the (x, y) coordinates to get radius of the circles
for (x, y, r) in circles:
coord = (x, y)
circle_center_coord.append(coord)
circle_center_radius.append(r)
if idx_closest == 0:
print("Circle marker with radius = {} was detected!\n".format(circle_center_radius[idx_closest]))
'''
# draw the circle in the output image, then draw a center
circle_detection_img = cv2.circle(circle_detection_img, circle_center_coord[idx_closest], circle_center_radius[idx_closest], (0, 255, 0), 4)
circle_detection_img = cv2.circle(circle_detection_img, circle_center_coord[idx_closest], 5, (0, 128, 255), -1)
'''
# compute the diameter of coin
diameter_circle = circle_center_radius[idx_closest]*2
# mask the detected circle with black color
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
tmp_mask = np.zeros((gray.shape), np.uint8)
#tmp_mask = np.zeros([img_width, img_height], dtype=np.uint8)
tmp_mask = cv2.circle(tmp_mask, circle_center_coord[idx_closest], circle_center_radius[idx_closest] + 50, (255, 255, 255), -1)
tmp_mask_binary = cv2.threshold(tmp_mask, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
tmp_mask_binary = cv2.bitwise_not(tmp_mask_binary)
masked_tmp = cv2.bitwise_and(image.copy(), image.copy(), mask = tmp_mask_binary)
#####################################################
# save marker part as detection results
(startX, startY) = circle_center_coord[idx_closest]
sx = startX -r*1 if startX -r*1 > 0 else 0
sy = startY -r*1 if startY -r*1 > 0 else 0
endX = startX + int(r*1.2)
endY = startY + int(r*1.2)
circle_detection_img = output[sy:endY, sx:endX]
###################################################
# crop ROI region based on the location of circle marker
offset = 1250
endX = startX + int(r*1.2) + offset
endY = startY + int(r*1.2) + offset
sx = startX -r*4 if startX -r*4 > 0 else 0
sy = startY -r*4 if startY -r*4 > 0 else 0
ROI_region = masked_tmp[sy:endY, sx:endX]
#sticker_crop_img = output
else:
print("No circle was found!\n")
ROI_region = output
masked_tmp = output
diameter_circle = 0
return diameter_circle, ROI_region, circle_detection_img
'''
# Detect stickers in the image
def sticker_detect(img_ori):
# load the image, clone it for output, and then convert it to grayscale
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)
#(minVal, maxVal, minLoc, maxLoc) = cv2.minMaxLoc(res)
# Specify a threshold
threshold = 0.6
if np.amax(res) > threshold:
flag = True
else:
flag = False
print(flag)
# Store the coordinates of matched area in a numpy array
loc = np.where( res >= threshold)
if len(loc):
(y,x) = np.unravel_index(res.argmax(), res.shape)
(min_val, max_val, min_loc, max_loc) = cv2.minMaxLoc(res)
#print(y,x)
#print(min_val, max_val, min_loc, max_loc)
(startX, startY) = max_loc
endX = startX + template.shape[0] + 1050 + 110
endY = startY + template.shape[1] + 1050 + 110
# Draw a rectangle around the matched region.
for pt in zip(*loc[::-1]):
sticker_overlay = cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,255,255), 2)
sticker_crop_img = img_rgb[startY:endY, startX:endX]
return sticker_crop_img, sticker_overlay
'''
# compute the size and shape info of the foreground
def comp_external_contour(orig, thresh):