-
Notifications
You must be signed in to change notification settings - Fork 0
/
forcestamp.py
1635 lines (1386 loc) · 62.7 KB
/
forcestamp.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
import numpy as np
from scipy.ndimage.filters import maximum_filter, minimum_filter
import itertools
import bch
import ellipses
import forcestamp_c
import time
import cv2
from scipy.spatial import distance as dist
import copy
def findLocalPeaks(img, threshold=0.5, kernal=3):
# apply the local maximum filter; all pixel of maximum value
# in their neighborhood are set to 1
local_max_g = maximum_filter(img, kernal)
local_min_g = minimum_filter(img, kernal)
# store local maxima
local_max = (local_max_g == img)
# difference between local maxima and minima
diff = ((local_max_g - local_min_g) > threshold)
# insert 0 where maxima do not exceed threshold
local_max[diff == 0] = 0
return local_max
def isDotIncluded(dot, rows=185, cols=105):
# check if the dot is in the pad area
if dot[0] > 0 and dot[0] < rows and dot[1] > 0 and dot[1] < cols:
return True
else:
return False
def findCircles(dots, radius):
# find circle center candidates from two dots on the circle
# extract coordinates from dots
x1 = dots[0][0]
x2 = dots[1][0]
y1 = dots[0][1]
y2 = dots[1][1]
# distance between pt1 and pt2
q = np.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)))
# middle point
x3 = (x1 + x2) / 2
y3 = (y1 + y2) / 2
# print(radius ** 2 - (q / 2) ** 2)
a = radius ** 2 - (q / 2) ** 2
if a < 0:
a = 0
cnt1_x = x3 + np.sqrt(a) * (y1 - y2) / q
cnt1_y = y3 + np.sqrt(a) * (x2 - x1) / q
cnt1 = (cnt1_x, cnt1_y)
cnt2_x = x3 - np.sqrt(a) * (y1 - y2) / q
cnt2_y = y3 - np.sqrt(a) * (x2 - x1) / q
cnt2 = (cnt2_x, cnt2_y)
return cnt1, cnt2
def distance(pt1, pt2):
# calculate distance between two points
return np.sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
def findPeakCoord(img):
# return peak coordinates from input peak image
peaks = [tuple(coords) for coords in zip(*np.where(img == True))]
# print(peaks)
return peaks
def findSubpixelPeaks(peaks, img, n=7):
# prepare an empty array of kernal size
# n = 7
subPeaks = []
for pk in peaks:
r = np.floor(n / 2)
# crop region around peak coord with the kernal size
cropped = cropImage(img, pk, radius=r, margin=0)
# project values to x axis and y axis each
x = np.sum(cropped, axis=0)
y = np.sum(cropped, axis=1)
# perform CoM peak detection
# x_CoM7 = (3 * x[6] + 2 * x[5] + x[4] - x[2] - 2 * x[1] - 3 * x[0]) / (np.sum(x))
# y_CoM7 = (3 * y[6] + 2 * y[5] + y[4] - y[2] - 2 * y[1] - 3 * y[0]) / (np.sum(y))
if n == 7:
x_CoM = (3 * x[6] + 2 * x[5] + x[4] - x[2] - 2 * x[1] - 3 * x[0]) / (np.sum(x))
y_CoM = (3 * y[6] + 2 * y[5] + y[4] - y[2] - 2 * y[1] - 3 * y[0]) / (np.sum(y))
elif n == 5:
x_CoM = (2 * x[4] + 1 * x[3] - 1 * x[1] - 2 * x[0]) / (np.sum(x))
y_CoM = (2 * y[4] + 1 * y[3] - 1 * y[1] - 2 * y[0]) / (np.sum(y))
# print(x_CoM, y_CoM)
subPeaks.append((pk[0] + x_CoM, pk[1] + y_CoM))
return subPeaks
'''
def findMarker(peaks, markerRadius=20, distanceTolerance=1, cMode=True):
# find marker pin peaks from the peak image
# distanceTolerance: tolerance when finding marker center candidates
# peaks = findPeakCoord(img)
circleCenters = []
# make combination of two to find circle peaks
for peaks_comb in itertools.combinations(peaks, 2):
if distance(peaks_comb[0], peaks_comb[1]) < markerRadius * 2.0:
circleCenter1, circleCenter2 = findCircles(
peaks_comb, markerRadius)
# parse the obtained center candidates
if isDotIncluded(circleCenter1):
circleCenters.append(circleCenter1)
if isDotIncluded(circleCenter2):
circleCenters.append(circleCenter2)
# print(len(circleCenters))
# print(circleCenters)
# print(peaks)
if cMode:
markerCentersFiltered = forcestamp_c.findMarkerCenters(circleCenters, peaks, markerRadius, distanceTolerance)
else:
# find marker center candidates by given radius
markerCenters = []
for cnt in circleCenters:
distanceCount = 0
inboundPeakCount = 0
for peak in peaks:
if distance(cnt, peak) < markerRadius + distanceTolerance and \
distance(cnt, peak) > markerRadius - distanceTolerance:
distanceCount += 1
if distance(cnt, peak) < markerRadius - distanceTolerance:
inboundPeakCount += 1
# if there are less than 3 dots on the circle
# and less than 3 dots inside the circle
# print(distanceCount)
if distanceCount > 4 and inboundPeakCount < 4:
markerCenters.append(cnt)
# cluster and average marker center candidates to find accurate centers
markerCentersClustered = []
numCluster = 0
for cnt in markerCenters:
# for first marker, just add a new cluster
if numCluster == 0:
markerCentersClustered.append([cnt])
numCluster += 1
else:
currentCluster = 0
isNew = True
minDist = 1000
for i in range(len(markerCentersClustered)):
# check distance from existing cluster centers
dist = distance(cnt, markerCentersClustered[i][0])
minDist = np.minimum(minDist, dist)
if dist < markerRadius / 2:
# add the center point to current cluster
isNew = False
currentCluster = i
break
if isNew:
# if the point does not belong to any existing clusters
if minDist > markerRadius * 2.1: # do not overlap with others
numCluster += 1
markerCentersClustered.append([])
markerCentersClustered[numCluster - 1].append(cnt)
else:
markerCentersClustered[currentCluster].append(cnt)
# average marker center candidates to get accurate centers
markerCentersFiltered = []
for cluster in markerCentersClustered:
averageCoordX = 0
averageCoordY = 0
for coord in cluster:
averageCoordX += coord[0]
averageCoordY += coord[1]
averageCoordX /= len(cluster)
averageCoordY /= len(cluster)
markerCentersFiltered.append((averageCoordX, averageCoordY))
return markerCentersFiltered
'''
def findMarkerCenter(blobs, markerRadii, distanceTolerance):
for blobs_two in itertools.combinations(blobs, 2):
dist = distance(blobs_two[0].c, blobs_two[1].c)
# print(dist)
for radius in markerRadii:
if dist < radius * 2.0:
center1, center2 = findCircles((blobs_two[0].c, blobs_two[1].c), radius)
centers = [center1, center2]
# print('centers:', centers)
for cnt in centers:
if isDotIncluded(cnt):
temp_marker = marker(radius)
innerBlobCount = 0
# print('counting blobs')
for b in blobs:
dist = distance(center1, b.c)
# print(dist)
if dist < radius + distanceTolerance and \
dist > radius - distanceTolerance:
temp_marker.addBlob(b)
elif dist < radius - distanceTolerance:
innerBlobCount += 1
# print(len(temp_marker.blobs))
if len(temp_marker.blobs) > 6 and innerBlobCount < 3:
blobs_unused = [blob for blob in blobs if blob not in temp_marker.blobs]
# print(blobs_unused)
temp_marker.pos = tuple(cnt)
return temp_marker, blobs_unused
return None, blobs
def findMarker(blobs, markerRadii=[20], distanceTolerance=1):
# distanceTolerance: tolerance when finding marker center candidates
# for combination of two blobs, find circle center
# for the circle center, calculate distance from any other blobs
# if there are at least 7 blobs with matching distance, confirm it as a center
markers = []
while len(blobs) > 1: # while there are more than 2 blobs
marker, blobs = findMarkerCenter(blobs, markerRadii, distanceTolerance)
# print(marker, blobs)
if marker is None:
break
else:
markers.append(marker)
return markers, blobs
'''
for blobs_comb in itertools.combinations(blobs, 2):
if distance(blobs_comb[0].c, blobs_comb[1].c) < markerRadius * 2.0:
center1, center2 = findCircles((blobs_comb[0].c, blobs_comb[0].c), markerRadius)
# check for coordinate validness
if isDotIncluded(center1):
# calculate distance from other blobs
distanceCount = 0
innerBlobCount = 0
for b in blobs:
dist = distance(center1, b.c)
if dist < markerRadius + distanceTolerance and \
dist > markerRadius - distanceTolerance:
distanceCount += 1
elif dist < markerRadius - distanceTolerance:
innerBlobCount += 1
if distanceCount > 7 and innerBlobCount < 2:
markers.append(marker(img, imgpeak, radius))
circleCenters = []
# make combination of two to find circle peaks
for peaks_comb in itertools.combinations(peaks, 2):
if distance(peaks_comb[0], peaks_comb[1]) < markerRadius * 2.0:
circleCenter1, circleCenter2 = findCircles(
peaks_comb, markerRadius)
# parse the obtained center candidates
if isDotIncluded(circleCenter1):
circleCenters.append(circleCenter1)
if isDotIncluded(circleCenter2):
circleCenters.append(circleCenter2)
# print(len(circleCenters))
# print(circleCenters)
# print(peaks)
if cMode:
markerCentersFiltered = forcestamp_c.findMarkerCenters(circleCenters, peaks, markerRadius, distanceTolerance)
else:
# find marker center candidates by given radius
markerCenters = []
for cnt in circleCenters:
distanceCount = 0
inboundPeakCount = 0
for peak in peaks:
if distance(cnt, peak) < markerRadius + distanceTolerance and \
distance(cnt, peak) > markerRadius - distanceTolerance:
distanceCount += 1
if distance(cnt, peak) < markerRadius - distanceTolerance:
inboundPeakCount += 1
# if there are less than 3 dots on the circle
# and less than 3 dots inside the circle
# print(distanceCount)
if distanceCount > 4 and inboundPeakCount < 4:
markerCenters.append(cnt)
# cluster and average marker center candidates to find accurate centers
markerCentersClustered = []
numCluster = 0
for cnt in markerCenters:
# for first marker, just add a new cluster
if numCluster == 0:
markerCentersClustered.append([cnt])
numCluster += 1
else:
currentCluster = 0
isNew = True
minDist = 1000
for i in range(len(markerCentersClustered)):
# check distance from existing cluster centers
dist = distance(cnt, markerCentersClustered[i][0])
minDist = np.minimum(minDist, dist)
if dist < markerRadius / 2:
# add the center point to current cluster
isNew = False
currentCluster = i
break
if isNew:
# if the point does not belong to any existing clusters
if minDist > markerRadius * 2.1: # do not overlap with others
numCluster += 1
markerCentersClustered.append([])
markerCentersClustered[numCluster - 1].append(cnt)
else:
markerCentersClustered[currentCluster].append(cnt)
# average marker center candidates to get accurate centers
markerCentersFiltered = []
for cluster in markerCentersClustered:
averageCoordX = 0
averageCoordY = 0
for coord in cluster:
averageCoordX += coord[0]
averageCoordY += coord[1]
averageCoordX /= len(cluster)
averageCoordY /= len(cluster)
markerCentersFiltered.append((averageCoordX, averageCoordY))
return markerCentersFiltered
'''
def constraint(input, const_floor, const_ceil):
# make input to be
# const_floor < input < const_ceil
if input < const_floor:
input = const_floor
elif input > const_ceil:
input = const_ceil
else:
input = input
return input
def detectDots(img, coords, area=4):
# detect if there are peaks in dot candidates with kernals
# for i in range(area):
# for j in range(area):
x_start = coords[0] - int(area / 2)
y_start = coords[1] - int(area / 2)
x_end = coords[0] + int(area / 2) + 1
y_end = coords[1] + int(area / 2) + 1
x_start = constraint(x_start, 0, np.shape(img)[0])
y_end = constraint(y_end, 0, np.shape(img)[1])
x_start = constraint(x_start, 0, np.shape(img)[0])
y_end = constraint(y_end, 0, np.shape(img)[1])
kernal = img[x_start:x_end, y_start:y_end]
# print(kernal)
# print(np.sum(kernal))
if np.sum(kernal) >= 1:
return 1
else:
return 0
def extractCode(img, markerRadius, distTolerance=3):
n = 15
# find marker pin peaks from the peak image
peakImg = findLocalPeaks(img, threshold=0.3)
peaks = findPeakCoord(peakImg)
peaks = findSubpixelPeaks(peaks, img)
# print(peaks)
# calculate temporary marker center
centerPX = np.floor(np.shape(img)[0] / 2)
centerPY = np.floor(np.shape(img)[1] / 2)
markerCenter = (centerPX, centerPY)
# find dots which are included in the marker
trueDots = []
for peak in peaks:
dist = distance(markerCenter, peak)
if dist < markerRadius + distTolerance and \
dist > markerRadius - distTolerance:
trueDots.append(peak)
# print(trueDots)
# find marker center from the true dots
data = [[], []]
for i in trueDots:
data[0].append(i[0])
data[1].append(i[1])
try:
lsqe = ellipses.LSqEllipse()
lsqe.fit(data)
center, width, height, phi = lsqe.parameters()
except(IndexError):
center = markerCenter
except(np.linalg.linalg.LinAlgError):
center = markerCenter
# print('circle center: ', tuple(center))
# make the dots as vectors from center point
vecDots = []
for dot in trueDots:
vec = (dot[0] - center[0], dot[1] - center[1])
vecMag = distance((0, 0), vec)
# print(vec)
try:
vecPhs = np.arctan2(vec[1], vec[0])
except TypeError:
vecPhs = np.arctan2(np.real(vec[1]), np.real(vec[0]))
vecDots.append((vecMag, vecPhs))
# print(np.rad2deg(vecPhs) % (360 / 15))
# 15th power to remove phase shifts
# print(vecDots[1])
phaseError = 0
phaseErrorArray = []
for i in vecDots:
# i_error = i[1] % (2 * np.pi / n)
# if i_error < (2 * np.pi / n) / 2:
# i_error += (2 * np.pi / n)
# phaseError += i_error
phaseErrorArray.append(i[1] % (2 * np.pi / n))
# unwrap phase
thre = 0.005
var = np.var(phaseErrorArray)
phaseErrorArray_fixed = []
for i in phaseErrorArray:
if var > thre:
if i < 2 * np.pi / 4 / n:
i += (2 * np.pi / n)
phaseErrorArray_fixed.append(i)
# phaseError = phaseError / len(vecDots)
phaseError = np.average(phaseErrorArray_fixed)
# print('phase error: ' + str(np.rad2deg(phaseError)))
# print('distribution: ', np.var(phaseErrorArray))
# print(phaseErrorArray)
# print(phaseErrorArray_fixed)
# print(vecDots[0])
vecDotsFixed = []
for i in vecDots:
vecDotsFixed.append((i[0], (i[1] - phaseError) % (2 * np.pi)))
# print(vecDotsFixed)
# fix vector representation to coordinates
cartDotsFixed = []
for vector in vecDotsFixed:
x = center[0] + vector[0] * np.sin(vector[1])
y = center[1] + vector[0] * np.cos(vector[1])
cartDotsFixed.append((x, y))
initDot = (center[0] + markerRadius, center[1])
# print(initDot)
codes = []
dotRegions = []
# specify dot regions
initX = initDot[0] - center[0]
initY = initDot[1] - center[1]
try:
initRad = np.arctan2(initX, initY)
except TypeError:
initRad = np.arctan2(np.real(initX), np.real(initY))
for j in range(n):
destX = center[0] + \
markerRadius * np.sin(initRad + j * 2 * np.pi / n)
destY = center[1] + \
markerRadius * np.cos(initRad + j * 2 * np.pi / n)
dotRegions.append((destX, destY))
codes = []
for dot in dotRegions:
isDot = 0
for dotData in cartDotsFixed:
if distance(dot, dotData) < 3:
isDot = 1
codes.append(isDot)
# detect dots and extract codes from marker grid
# for dots in dotRegions:
# result = detectDots(img, dots)
# codes.append(result)
# codes = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# print(codes)
# print(phaseError)
return codes, dotRegions, phaseError
def recognizeID(msg, full=False):
# print(msg)
# recognize ID by decoded codeword
codeList = [
[0],
[32, 1, 34, 3, 68, 7, 8, 64, 14, 16, 81, 116, 104, 58, 29],
[96, 65, 2, 115, 4, 102, 39, 9, 76, 78, 48, 19, 24, 57, 28],
[97, 66, 5, 38, 41, 10, 77, 110, 112, 83, 20, 55, 56, 27, 92],
[33, 67, 37, 6, 40, 105, 42, 13, 80, 82, 52, 21, 84, 26, 74],
[98, 69, 119, 95, 11, 46, 111, 113, 23, 120, 59, 124, 93, 126, 63],
[99, 70, 103, 108, 12, 79, 49, 51, 118, 88, 25, 123, 125, 62, 31],
[35, 100, 71, 72, 107, 44, 15, 17, 50, 117, 86, 89, 122, 61, 30],
[73, 18, 36],
[75, 101, 106, 43, 45, 47, 114, 53, 22, 87, 121, 90, 60, 94, 85],
[91, 109, 54],
[127]
]
# Recognize ID by full codeword.
uniqueCodes = [
np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=np.int),
np.array([1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0], dtype=np.int),
np.array([1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0], dtype=np.int),
np.array([1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0], dtype=np.int),
np.array([1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0], dtype=np.int),
np.array([1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0], dtype=np.int),
np.array([1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0], dtype=np.int),
np.array([1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0], dtype=np.int),
np.array([1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0], dtype=np.int),
np.array([1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0], dtype=np.int),
np.array([1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0], dtype=np.int),
np.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=np.int)
]
n = 15
IDout = 0
if full:
for ID in range(len(uniqueCodes)):
code = uniqueCodes[ID]
for i in range(n):
recCode_shift = np.roll(msg, i)
# print(recCode_shift)
if recCode_shift.tolist() == code.tolist():
# print('found ID')
IDout = ID
break
else:
for ID in range(len(codeList)):
for code in codeList[ID]:
if msg == code:
IDout = ID
break
return IDout
def cropImage(img, pos, radius, margin=4):
# crop image region surrounded by circle
# img size
width = np.shape(img)[0]
height = np.shape(img)[1]
posX = int(pos[0])
posY = int(pos[1])
# crop size
crop = int(round((radius + margin)) * 2 + 1)
crop_half = int(round(radius) + margin)
imgCropped = np.zeros((crop, crop))
xMinFixed = 0
xMaxFixed = crop
yMinFixed = 0
yMaxFixed = crop
xMin = posX - crop_half
xMax = posX + crop_half
yMin = posY - crop_half
yMax = posY + crop_half
if xMin < 0:
xMinFixed = -xMin
if xMax >= width:
xMaxFixed = crop + (width - xMax) - 1
if yMin < 0:
yMinFixed = -yMin
if yMax >= height:
yMaxFixed = crop + (height - yMax) - 1
pxMin = constraint(posX - crop_half, 0, width)
pxMax = constraint(posX + crop_half, 0, width)
pyMin = constraint(posY - crop_half, 0, height)
pyMax = constraint(posY + crop_half, 0, height)
imgCropped[xMinFixed:xMaxFixed, yMinFixed:yMaxFixed] = \
img[pxMin:pxMax + 1, pyMin:pyMax + 1]
return imgCropped
def excludeMarkerPeaks(img, pos, radius, margin=2):
# crop image region surrounded by circle
# img size
width = np.shape(img)[0]
height = np.shape(img)[1]
posX = int(pos[0])
posY = int(pos[1])
# crop size
# crop = (radius + margin) * 2 + 1
crop_half = radius + margin
# imgCropped = np.zeros((crop, crop))
# xMinFixed = 0
# xMaxFixed = crop
# yMinFixed = 0
# yMaxFixed = crop
# xMin = posX - crop_half
# xMax = posX + crop_half
# yMin = posY - crop_half
# yMax = posY + crop_half
# if xMin < 0:
# xMinFixed = -xMin
# if xMax >= width:
# xMaxFixed = crop + (width - xMax) - 1
# if yMin < 0:
# yMinFixed = -yMin
# if yMax >= height:
# yMaxFixed = crop + (height - yMax) - 1
pxMin = round(constraint(posX - crop_half, 0, width))
pxMax = round(constraint(posX + crop_half, 0, width))
pyMin = round(constraint(posY - crop_half, 0, height))
pyMax = round(constraint(posY + crop_half, 0, height))
# imgCropped[xMinFixed:xMaxFixed, yMinFixed:yMaxFixed] = \
img[pxMin:pxMax + 1, pyMin:pyMax + 1] = False
return img
def calculateForceVector(img):
# calcuate vector of the applied force
width = np.shape(img)[0]
height = np.shape(img)[1]
centerP = np.floor(np.shape(img)[0] / 2)
vecX = 0
vecY = 0
x = np.linspace(0, width - 1, width)
y = np.linspace(0, height - 1, height)
xv, yv = np.meshgrid(x, y)
vecMag = np.sqrt(np.power(xv - centerP, 2) + np.power(yv - centerP, 2))
vecRad = np.arctan2(xv - centerP, yv - centerP)
# print(np.sum(img))
img_sum = np.sum(img)
if img_sum > 0:
vecX = np.sum(img * vecMag * np.sin(vecRad)) / img_sum
vecY = -np.sum(img * vecMag * np.cos(vecRad)) / img_sum
else:
vecX = 0
vecY = 0
# print(vecX, vecY)
return (vecX, vecY)
def detectBlobs(img, areaThreshold=1000, forceThreshold=6, binThreshold=2):
contours = []
hierarchy = []
# moments = []
areas = []
cxs = []
cys = []
# pixelpoints = []
forces = []
blobs = []
img_thre = np.zeros_like(img)
if np.max(img) > 0:
# img_uint8 = np.zeros_like(img, dtype=np.uint8)
# img_uint8 = (img / np.max(img) * 255).astype(np.uint8)
img_thre = copy.deepcopy(img) * 2
img_thre[img_thre >= 255] = 255
img_thre = img_thre.astype(np.uint8)
# Binary threshold
img_thre = cv2.threshold(img_thre,
binThreshold,
255,
cv2.THRESH_BINARY)[1]
# find contours
_, contours, hierarchy = cv2.findContours(
img_thre,
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE
)
# find peaks
img_peaks = findLocalPeaks(img, threshold=0.2).astype(np.uint8)
# remove peaks which are included in large blobs
# make masks for blobs over area threshold
mask = np.zeros(img.shape, dtype=np.uint8)
for cnt in contours:
# print(cnt)
area = cv2.contourArea(cnt)
# print(area)
if area > areaThreshold:
cv2.drawContours(mask, [cnt], 0, 255, -1)
img_peaks = cv2.subtract(img_peaks, mask)
img_thre = mask
# extract coordinates from peak image
peaks = findPeakCoord(img_peaks)
sub_peaks = findSubpixelPeaks(peaks, img, n=5)
for peak in zip(peaks, sub_peaks):
# peak coordinates
cxs.append(peak[1][0])
cys.append(peak[1][1])
# force calculation
cropped = cropImage(img, (peak[0][0], peak[0][1]), 1, margin=0)
if np.shape(cropped)[0] == 0 or np.shape(cropped)[0] == 0:
force = 0
else:
# calculate force from the raw input image
force = np.sum(cropped)
forces.append(force)
# create blob objects
b = Blob(peak[0][1], peak[0][0], 3 * 3, force, [], [])
# if b.area < areaThreshold:
if b.force > forceThreshold:
blobs.append(b)
'''
for cnt in contours:
# moment
M = cv2.moments(cnt)
moments.append(M)
# area
area = cv2.contourArea(cnt)
areas.append(area)
# centroid
try:
cx = M['m10'] / M['m00']
cy = M['m01'] / M['m00']
except ZeroDivisionError:
# print('zero division error!')
# calculate center by four extreme points
leftmost = tuple(cnt[cnt[:, :, 0].argmin()][0])
rightmost = tuple(cnt[cnt[:, :, 0].argmax()][0])
topmost = tuple(cnt[cnt[:, :, 1].argmin()][0])
bottommost = tuple(cnt[cnt[:, :, 1].argmax()][0])
cx = (leftmost[0] + rightmost[0] + topmost[0] + bottommost[0]) / 2
cy = (leftmost[1] + rightmost[1] + topmost[1] + bottommost[1]) / 2
cxs.append(cx)
cys.append(cy)
# extract blob mask for exact force calculation
mask = np.zeros(img.shape, dtype=np.uint8)
cv2.drawContours(mask, [cnt], 0, 255, -1)
# pixelpoint = np.transpose(np.nonzero(mask))
pixelpoint = np.nonzero(mask)
pixelpoints.append(pixelpoint)
# calculate force from the raw input image
force = np.sum(img[pixelpoint])
forces.append(force)
# create blob objects
b = Blob(cx, cy, area, force, pixelpoint, cnt)
if b.area < areaThreshold:
if b.force > forceThreshold:
blobs.append(b)
'''
# print(pixelpoints)
# print(contours)
return blobs, contours, hierarchy, areas, cxs, cys, forces, img_thre
class Blob:
# posX: x coordinate (0-184)
# posY: y coordinate (0-104)
# ID: blob ID (0-11)
# force: force applied to the blob (0-?)
# area: area of the blob
# t_appeared: timestamp of the appeared time
# points: coordinates of blob pixels
def __init__(self, cx, cy, area, force, points, contour):
self.cx = cx
self.cy = cy
self.c = (cx, cy)
# self.ID = ID
self.force = force
self.area = area
self.t_appeared = time.time()
self.points = points
self.contour = contour
self.lifetime = 0
self.slot = -1
self.phase = 0
def update(self, blob):
self.cx = blob.cx
self.cy = blob.cy
self.c = (blob.cx, blob.cy)
# self.ID = ID
self.force = blob.force
self.area = blob.area
self.points = blob.points
self.contour = blob.contour
self.lifetime = 0
def attributeID(self, ID):
self.ID = ID
# print('attributed ID: %d' % ID)
def succeedTime(self, time):
self.t_appeared = time
class TrackBlobs():
def __init__(self):
# set initial parameters
self.nextID = 0
self.prevBlobs = []
# self.IDTable = [False] * 1000
# def registerID(self, blob):
# # .index returns the index of the first item appears in the list
# availableID = self.IDTable.index(False)
# # print(self.IDTable)
# print(availableID)
# blob.attributeID(availableID)
# self.IDTable[availableID] = True
# return blob
def update(self, img):
# find blobs in current frame
self.currentBlobs = detectBlobs(img, areaThreshold=1000)[0]
# no blobs in the image
if len(self.currentBlobs) == 0:
# reset next ID
self.nextID = 0
# self.IDTable = [False] * 1000
self.prevBlobs = []
return self.currentBlobs
# prepare distance matrix
# current centroids
currentCentroids = np.zeros((len(self.currentBlobs), 2), dtype=np.float)
previousCentroids = np.zeros((len(self.prevBlobs), 2), dtype=np.float)
# store blob coordinates
for i in range(len(self.currentBlobs)):
currentCentroids[i] = self.currentBlobs[i].c
for i in range(len(self.prevBlobs)):
previousCentroids[i] = self.prevBlobs[i].c
# if there are no blobs being tracked, register all current blobs
if len(self.prevBlobs) == 0:
for b in self.currentBlobs:
# print(b.c)
# b = self.registerID(b)
b.attributeID(self.nextID)
# print('no prev blobs!')
self.nextID += 1
else:
# calculate distance of all pairs of current and previous blobs
distMat = dist.cdist(
previousCentroids,
currentCentroids,
metric='euclidean'
)
# print(distMat)
# sort the matrix by element's min values
rows = distMat.min(axis=1).argsort()
cols = distMat.argmin(axis=1)[rows]
# print(rows)
# print(cols)
# check if the combination is already used
usedRows = set()
usedCols = set()
# iterate over row, columns
for (row, col) in zip(rows, cols):
# ignore already examined rows, cols.
if row in usedRows or col in usedCols:
continue
# otherwise, update ID of the current blobs with
# previous blob IDs, and maintain appeared time.
blobID = self.prevBlobs[row].ID
blobTime = self.prevBlobs[row].t_appeared
self.currentBlobs[col].attributeID(blobID)
# print('ID updated!')
self.currentBlobs[col].succeedTime(blobTime)
# check that we have examined the row, col
usedRows.add(row)
usedCols.add(col)
# extract unchecked rows, cols
# unusedRows = set(range(0, distMat.shape[0])).difference(usedRows)
unusedCols = set(range(0, distMat.shape[1])).difference(usedCols)
# print('unused rows: ', unusedRows)
# print('unused cols: ', unusedCols)
# if the number of prev blobs are greater than or equal to
# current blobs, check their liftime
for col in unusedCols:
# self.register(inputCentroids[col])
self.currentBlobs[col].attributeID(self.nextID)
self.nextID += 1
# toss the current blob information to prev
self.prevBlobs = self.currentBlobs
return self.currentBlobs
class marker:
# pos_x: x coordinate (0-184)
# delta pos_x
# pos_y: y coordinate (0-104)
# delta pos_y
# ID: marker ID (1-90)
# slot: each slot has one blob slot[0-14]
# timestamp: time when the marker first created
# force: force applied to marker (0-?)
# delta force: delta force
# cof_x: center of force for x coord
# delta cof_x
# cof_y: center of force for y coord
# delta cof_y
# rotation: orientation of marker (0-2pi)
# delta rotation
def __init__(self, radius):
self.n = 15
self.pos = (0, 0)
self.pos_x = 0
self.pos_y = 0
self.d_pos_x = 0
self.d_pos_y = 0
self.radius = radius
self.timestamp = time.time()
self.blobs = []
self.slots = [None] * self.n