-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrbt.py
2271 lines (1846 loc) · 77.1 KB
/
rbt.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
#!/usr/bin/env python2
"""
Given the following .png files in /tmp/
jdoe@laptop ~/l/lego-crane-cuber> ls -l /tmp/rubiks-side-*
-rw-r--r-- 1 jdoe jdoe 105127 Jan 15 00:30 /tmp/rubiks-side-B.png
-rw-r--r-- 1 jdoe jdoe 105014 Jan 15 00:30 /tmp/rubiks-side-D.png
-rw-r--r-- 1 jdoe jdoe 103713 Jan 15 00:30 /tmp/rubiks-side-F.png
-rw-r--r-- 1 jdoe jdoe 99467 Jan 15 00:30 /tmp/rubiks-side-L.png
-rw-r--r-- 1 jdoe jdoe 98052 Jan 15 00:30 /tmp/rubiks-side-R.png
-rw-r--r-- 1 jdoe jdoe 97292 Jan 15 00:30 /tmp/rubiks-side-U.png
jdoe@laptop ~/l/lego-crane-cuber>
For each png
- find all of the rubiks squares
- json dump a dictionary that contains the RGB values for each square
"""
from copy import deepcopy
from pprint import pformat
from subprocess import check_output
import cv2
import json
import logging
import math
import numpy as np
import os
import sys
import time
log = logging.getLogger(__name__)
def click_event(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
print(x, y)
def merge_two_dicts(x, y):
"""
Given two dicts, merge them into a new dict as a shallow copy.
"""
z = x.copy()
z.update(y)
return z
def convert_key_strings_to_int(data):
result = {}
for (key, value) in data.items():
if key.isdigit():
result[int(key)] = value
else:
result[key] = value
return result
def pixel_distance(A, B):
"""
In 9th grade I sat in geometry class wondering "when then hell am I
ever going to use this?"...today is that day.
Return the distance between two pixels
"""
(col_A, row_A) = A
(col_B, row_B) = B
return math.sqrt(math.pow(col_B - col_A, 2) + math.pow(row_B - row_A, 2))
def get_angle(A, B, C):
"""
Return the angle at C (in radians) for the triangle formed by A, B, C
a, b, c are lengths
C
/ \
b / \a
/ \
A-------B
c
"""
(col_A, row_A) = A
(col_B, row_B) = B
(col_C, row_C) = C
a = pixel_distance(C, B)
b = pixel_distance(A, C)
c = pixel_distance(A, B)
try:
cos_angle = (math.pow(a, 2) + math.pow(b, 2) - math.pow(c, 2)) / (2 * a * b)
except ZeroDivisionError as e:
log.warning(
"get_angle: A %s, B %s, C %s, a %.3f, b %.3f, c %.3f" % (A, B, C, a, b, c)
)
raise e
# If CA and CB are very long and the angle at C very narrow we can get an
# invalid cos_angle which will cause math.acos() to raise a ValueError exception
if cos_angle > 1:
cos_angle = 1
elif cos_angle < -1:
cos_angle = -1
angle_ACB = math.acos(cos_angle)
# log.info("get_angle: A %s, B %s, C %s, a %.3f, b %.3f, c %.3f, cos_angle %s, angle_ACB %s" %
# (A, B, C, a, b, c, pformat(cos_angle), int(math.degrees(angle_ACB))))
return angle_ACB
def sort_corners(corner1, corner2, corner3, corner4):
"""
Sort the corners such that
- A is top left
- B is top right
- C is bottom left
- D is bottom right
Return an (A, B, C, D) tuple
"""
results = []
corners = (corner1, corner2, corner3, corner4)
min_x = None
max_x = None
min_y = None
max_y = None
for (x, y) in corners:
if min_x is None or x < min_x:
min_x = x
if max_x is None or x > max_x:
max_x = x
if min_y is None or y < min_y:
min_y = y
if max_y is None or y > max_y:
max_y = y
# top left
top_left = None
top_left_distance = None
for (x, y) in corners:
distance = pixel_distance((min_x, min_y), (x, y))
if top_left_distance is None or distance < top_left_distance:
top_left = (x, y)
top_left_distance = distance
results.append(top_left)
# top right
top_right = None
top_right_distance = None
for (x, y) in corners:
if (x, y) in results:
continue
distance = pixel_distance((max_x, min_y), (x, y))
if top_right_distance is None or distance < top_right_distance:
top_right = (x, y)
top_right_distance = distance
results.append(top_right)
# bottom left
bottom_left = None
bottom_left_distance = None
for (x, y) in corners:
if (x, y) in results:
continue
distance = pixel_distance((min_x, max_y), (x, y))
if bottom_left_distance is None or distance < bottom_left_distance:
bottom_left = (x, y)
bottom_left_distance = distance
results.append(bottom_left)
# bottom right
bottom_right = None
bottom_right_distance = None
for (x, y) in corners:
if (x, y) in results:
continue
distance = pixel_distance((max_x, max_y), (x, y))
if bottom_right_distance is None or distance < bottom_right_distance:
bottom_right = (x, y)
bottom_right_distance = distance
results.append(bottom_right)
return results
def approx_is_square(
approx, SIDE_VS_SIDE_THRESHOLD=0.60, ANGLE_THRESHOLD=20, ROTATE_THRESHOLD=30
):
"""
Rules
- there must be four corners
- all four lines must be roughly the same length
- all four corners must be roughly 90 degrees
- AB and CD must be horizontal lines
- AC and BC must be vertical lines
SIDE_VS_SIDE_THRESHOLD
If this is 1 then all 4 sides must be the exact same length. If it is
less than one that all sides must be within the percentage length of
the longest side.
ANGLE_THRESHOLD
If this is 0 then all 4 corners must be exactly 90 degrees. If it
is 10 then all four corners must be between 80 and 100 degrees.
ROTATE_THRESHOLD
Controls how many degrees the entire square can be rotated
The corners are labeled
A ---- B
| |
| |
C ---- D
"""
assert (
SIDE_VS_SIDE_THRESHOLD >= 0 and SIDE_VS_SIDE_THRESHOLD <= 1
), "SIDE_VS_SIDE_THRESHOLD must be between 0 and 1"
assert (
ANGLE_THRESHOLD >= 0 and ANGLE_THRESHOLD <= 90
), "ANGLE_THRESHOLD must be between 0 and 90"
# There must be four corners
if len(approx) != 4:
return False
# Find the four corners
(A, B, C, D) = sort_corners(
tuple(approx[0][0]),
tuple(approx[1][0]),
tuple(approx[2][0]),
tuple(approx[3][0]),
)
# Find the lengths of all four sides
AB = pixel_distance(A, B)
AC = pixel_distance(A, C)
DB = pixel_distance(D, B)
DC = pixel_distance(D, C)
distances = (AB, AC, DB, DC)
max_distance = max(distances)
cutoff = int(max_distance * SIDE_VS_SIDE_THRESHOLD)
# log.info("approx_is_square A %s, B, %s, C %s, D %s, distance AB %d, AC %d, DB %d, DC %d, max %d, cutoff %d" %
# (A, B, C, D, AB, AC, DB, DC, max_distance, cutoff))
# If any side is much smaller than the longest side, return False
for distance in distances:
if distance < cutoff:
return False
# all four corners must be roughly 90 degrees
min_angle = 90 - ANGLE_THRESHOLD
max_angle = 90 + ANGLE_THRESHOLD
# Angle at A
angle_A = int(math.degrees(get_angle(C, B, A)))
if angle_A < min_angle or angle_A > max_angle:
return False
# Angle at B
angle_B = int(math.degrees(get_angle(A, D, B)))
if angle_B < min_angle or angle_B > max_angle:
return False
# Angle at C
angle_C = int(math.degrees(get_angle(A, D, C)))
if angle_C < min_angle or angle_C > max_angle:
return False
# Angle at D
angle_D = int(math.degrees(get_angle(C, B, D)))
if angle_D < min_angle or angle_D > max_angle:
return False
far_left = min(A[0], B[0], C[0], D[0])
far_right = max(A[0], B[0], C[0], D[0])
far_up = min(A[1], B[1], C[1], D[1])
# far_down = max(A[1], B[1], C[1], D[1])
top_left = (far_left, far_up)
top_right = (far_right, far_up)
# bottom_left = (far_left, far_down)
# bottom_right = (far_right, far_down)
debug = False
"""
if A[0] >= 93 and A[0] <= 96 and A[1] >= 70 and A[1] <= 80:
debug = True
log.info("approx_is_square A %s, B, %s, C %s, D %s, distance AB %d, "
"AC %d, DB %d, DC %d, max %d, cutoff %d, angle_A %s, angle_B %s, "
"angle_C %s, angle_D %s, top_left %s, top_right %s, bottom_left %s, "
"bottom_right %s" %
(A, B, C, D, AB, AC, DB, DC, max_distance, cutoff,
angle_A, angle_B, angle_C, angle_D,
pformat(top_left), pformat(top_right), pformat(bottom_left), pformat(bottom_right)))
"""
# Is AB horizontal?
if B[1] < A[1]:
# Angle at B relative to the AB line
angle_B = int(math.degrees(get_angle(A, top_left, B)))
if debug:
log.info(
"AB is horizontal, angle_B %s, ROTATE_THRESHOLD %s"
% (angle_B, ROTATE_THRESHOLD)
)
if angle_B > ROTATE_THRESHOLD:
if debug:
log.info(
"AB horizontal rotation %s is above ROTATE_THRESHOLD %s"
% (angle_B, ROTATE_THRESHOLD)
)
return False
else:
# Angle at A relative to the AB line
angle_A = int(math.degrees(get_angle(B, top_right, A)))
if debug:
log.info(
"AB is vertical, angle_A %s, ROTATE_THRESHOLD %s"
% (angle_A, ROTATE_THRESHOLD)
)
if angle_A > ROTATE_THRESHOLD:
if debug:
log.info(
"AB vertical rotation %s is above ROTATE_THRESHOLD %s"
% (angle_A, ROTATE_THRESHOLD)
)
return False
# TODO - if the area of the approx is way more than the
# area of the contour then this is not a square
return True
def square_width_height(approx, debug):
"""
This assumes that approx is a square. Return the width and height of the square.
"""
width = 0
height = 0
# Find the four corners
(A, B, C, D) = sort_corners(
tuple(approx[0][0]),
tuple(approx[1][0]),
tuple(approx[2][0]),
tuple(approx[3][0]),
)
# Find the lengths of all four sides
AB = pixel_distance(A, B)
AC = pixel_distance(A, C)
DB = pixel_distance(D, B)
DC = pixel_distance(D, C)
width = max(AB, DC)
height = max(AC, DB)
if debug:
log.info(
"square_width_height: AB %d, AC %d, DB %d, DC %d, width %d, height %d"
% (AB, AC, DB, DC, width, height)
)
return (width, height)
def compress_2d_array(original):
"""
Convert 2d array to a 1d array
"""
result = []
for row in original:
for col in row:
result.append(col)
return result
def get_side_name(size, square_index):
squares_per_side = size * size
if square_index <= squares_per_side:
return "U"
elif square_index <= (squares_per_side * 2):
return "L"
elif square_index <= (squares_per_side * 3):
return "F"
elif square_index <= (squares_per_side * 4):
return "R"
elif square_index <= (squares_per_side * 5):
return "B"
elif square_index <= (squares_per_side * 6):
return "D"
else:
raise Exception(
"We should not be here, square_index %d, size %d, squares_per_side %d"
% (square_index, size, squares_per_side)
)
class CubeNotFound(Exception):
pass
class RowColSizeMisMatch(Exception):
pass
class FoundMulitpleContours(Exception):
pass
class ZeroCandidates(Exception):
pass
class CustomContour(object):
def __init__(self, rubiks_parent, index, contour, heirarchy, debug):
self.rubiks_parent = rubiks_parent
self.index = index
self.contour = contour
self.heirarchy = heirarchy
peri = cv2.arcLength(contour, True)
self.approx = cv2.approxPolyDP(contour, 0.1 * peri, True)
self.area = cv2.contourArea(contour)
self.corners = len(self.approx)
self.width = None
self.debug = debug
# compute the center of the contour
M = cv2.moments(contour)
if M["m00"]:
self.cX = int(M["m10"] / M["m00"])
self.cY = int(M["m01"] / M["m00"])
# if self.cX == 188 and self.cY == 93:
# log.warning("CustomContour M %s" % pformat(M))
else:
self.cX = None
self.cY = None
def __str__(self):
return "Contour #%d (%s, %s)" % (self.index, self.cX, self.cY)
def is_square(self, target_area=None):
AREA_THRESHOLD = 0.50
if not approx_is_square(self.approx):
return False
if self.width is None:
(self.width, self.height) = square_width_height(self.approx, self.debug)
if target_area:
area_ratio = float(target_area / self.area)
if area_ratio < float(1.0 - AREA_THRESHOLD) or area_ratio > float(
1.0 + AREA_THRESHOLD
):
# log.info("FALSE %s target_area %d, my area %d, ratio %s" % (self, target_area, self.area, area_ratio))
return False
else:
# log.info("TRUE %s target_area %d, my area %d, ratio %s" % (self, target_area, self.area, area_ratio))
return True
else:
return True
def get_child(self):
# Each contour has its own information regarding what hierarchy it
# is, who is its parent, who is its parent etc. OpenCV represents it as
# an array of four values : [Next, Previous, First_child, Parent]
child = self.heirarchy[2]
if child == -1:
return None
else:
return self.rubiks_parent.contours_by_index[child]
def child_is_square(self):
"""
The black border between the squares can cause us to sometimes find a
contour for the outside edge of the border and a contour for the the
inside edge. This function returns True if this contour is the outside
contour in that scenario.
"""
child_con = self.get_child()
if child_con:
# If there is a dent in a square sometimes you will get a really small
# contour inside the square...we want to ignore those so make sure the
# area of the inner square is close to the area of the outer square.
if int(child_con.area * 3) < self.area:
return False
if child_con.is_square():
return True
return False
def get_parent(self):
# Each contour has its own information regarding what hierarchy it
# is, who is its parent, who is its parent etc. OpenCV represents it as
# an array of four values : [Next, Previous, First_child, Parent]
parent = self.heirarchy[3]
if parent == -1:
return None
else:
return self.rubiks_parent.contours_by_index[parent]
def parent_is_candidate(self):
parent_con = self.get_parent()
if parent_con:
if parent_con in self.rubiks_parent.candidates:
return True
return False
def parent_is_square(self):
parent_con = self.get_parent()
if parent_con:
# If there is a dent in a square sometimes you will get a really small
# contour inside the square...we want to ignore those so make sure the
# area of the inner square is close to the area of the outer square.
if int(parent_con.area * 2) < self.area:
return False
if parent_con.is_square():
return True
return False
def adjust_gamma(image, gamma=1.0):
"""
http://www.pyimagesearch.com/2015/10/05/opencv-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 increase_brightness(img, value=30):
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)
lim = 255 - value
v[v > lim] = 255
v[v <= lim] += value
final_hsv = cv2.merge((h, s, v))
img = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)
return img
class RubiksOpenCV(object):
def __init__(self, index=0, name=None, debug=False):
self.index = index
self.name = name
self.debug = debug
self.image = None
self.size_static = None
self.reset()
def __str__(self):
return str(self.name)
def reset(self):
self.data = {}
self.candidates = []
self.contours_by_index = {}
self.mean_square_area = None
self.median_square_area = None
self.black_border_width = None
self.top = None
self.right = None
self.bottom = None
self.left = None
# 2 for 2x2x2, 3 for 3x3x3, etc
self.size = None
def get_contour_neighbors(self, contours, target_con):
"""
Return stats on how many other contours are in the same 'row' or 'col' as target_con
TODO: This only works if the cube isn't at an angle...would be cool to work all the time
"""
row_neighbors = 0
row_square_neighbors = 0
col_neighbors = 0
col_square_neighbors = 0
# Wiggle +/- 50% the median_square_width
if self.size is None:
WIGGLE_THRESHOLD = 0.50
elif self.size == 7:
WIGGLE_THRESHOLD = 0.50
else:
WIGGLE_THRESHOLD = 0.70
# width_wiggle determines how far left/right we look for other contours
# height_wiggle determines how far up/down we look for other contours
width_wiggle = int(self.median_square_width * WIGGLE_THRESHOLD)
height_wiggle = int(self.median_square_width * WIGGLE_THRESHOLD)
log.debug(
"get_contour_neighbors() for %s, median square width %s, width_wiggle %s, height_wiggle %s"
% (target_con, self.median_square_width, width_wiggle, height_wiggle)
)
for con in contours:
# do not count yourself
if con == target_con:
continue
x_delta = abs(con.cX - target_con.cX)
y_delta = abs(con.cY - target_con.cY)
if x_delta <= width_wiggle:
col_neighbors += 1
if con.is_square(self.mean_square_area):
col_square_neighbors += 1
log.debug("%s is a square col neighbor" % con)
else:
log.debug(
"%s is a non-square col neighbor, it has %d corners"
% (con, con.corners)
)
else:
log.debug(
"%s x delta %s is outside width wiggle room %s"
% (con, x_delta, width_wiggle)
)
if y_delta <= height_wiggle:
row_neighbors += 1
if con.is_square(self.mean_square_area):
row_square_neighbors += 1
log.debug("%s is a square row neighbor" % con)
else:
log.debug(
"%s is a non-square row neighbor, it has %d corners"
% (con, con.corners)
)
else:
log.debug(
"%s y delta %s is outside height wiggle room %s"
% (con, y_delta, height_wiggle)
)
# log.debug("get_contour_neighbors() for %s has row %d, row_square %d, col %d, col_square %d neighbors\n" %
# (target_con, row_neighbors, row_square_neighbors, col_neighbors, col_square_neighbors))
return (
row_neighbors,
row_square_neighbors,
col_neighbors,
col_square_neighbors,
)
def sort_by_row_col(self, contours, size):
"""
Given a list of contours sort them starting from the upper left corner
and ending at the bottom right corner
"""
result = []
for row_index in range(size):
# We want the 'size' squares that are closest to the top
tmp = []
for con in contours:
tmp.append((con.cY, con.cX))
top_row = sorted(tmp)[:size]
# Now that we have those, sort them from left to right
top_row_left_right = []
for (cY, cX) in top_row:
top_row_left_right.append((cX, cY))
top_row_left_right = sorted(top_row_left_right)
log.debug(
"sort_by_row_col() row %d: %s"
% (row_index, pformat(top_row_left_right))
)
contours_to_remove = []
for (target_cX, target_cY) in top_row_left_right:
for con in contours:
if con in contours_to_remove:
continue
if con.cX == target_cX and con.cY == target_cY:
result.append(con)
contours_to_remove.append(con)
break
for con in contours_to_remove:
contours.remove(con)
return result
def remove_candidate_contour(self, contour_to_remove):
# heirarchy is [Next, Previous, First_child, Parent]
(
_,
_,
contour_to_remove_child,
contour_to_remove_parent,
) = contour_to_remove.heirarchy
# log.warning("removing %s with child %s, parent %s" % (contour_to_remove, contour_to_remove_child, contour_to_remove_parent))
for con in self.candidates:
if con == contour_to_remove:
continue
(_, _, child, parent) = con.heirarchy
# log.info(" %s child %s, parent %s" % (con, child, parent))
if child == contour_to_remove.index:
con.heirarchy[2] = contour_to_remove_child
# log.info(" %s child is now %s" % (con, con.heirarchy[2]))
if parent == contour_to_remove.index:
con.heirarchy[3] = contour_to_remove_parent
if contour_to_remove_parent != -1:
self.contours_by_index[contour_to_remove_parent].heirarchy[
2
] = con.index
# log.info(" %s parent is now %s" % (con, con.heirarchy[3]))
del self.contours_by_index[contour_to_remove.index]
self.candidates.remove(contour_to_remove)
for con in self.candidates:
child_index = con.heirarchy[2]
parent_index = con.heirarchy[3]
if child_index != -1:
child = self.contours_by_index[child_index]
child.heirarchy[3] = con.index
if parent_index != -1:
parent = self.contours_by_index[parent_index]
parent.heirarchy[2] = con.index
def remove_non_square_candidates(self, target_square_area=None):
"""
Remove non-square contours from candidates. Return a list of the ones we removed.
"""
candidates_to_remove = []
for con in self.candidates:
if not con.is_square(target_square_area):
candidates_to_remove.append(con)
for x in candidates_to_remove:
self.remove_candidate_contour(x)
removed = len(candidates_to_remove)
if self.debug:
log.info(
"remove-non-square-candidates: %d removed, %d remain, target_square_area %s\n"
% (removed, len(self.candidates), target_square_area)
)
if removed:
return True
else:
return False
def remove_dwarf_candidates(self, area_cutoff):
candidates_to_remove = []
# Remove parents with square child contours
for con in self.candidates:
if con.area < area_cutoff:
candidates_to_remove.append(con)
for x in candidates_to_remove:
self.remove_candidate_contour(x)
removed = len(candidates_to_remove)
if self.debug:
log.info(
"remove-dwarf-candidates %d removed, %d remain\n"
% (removed, len(self.candidates))
)
return candidates_to_remove
def remove_gigantic_candidates(self, area_cutoff):
candidates_to_remove = []
# Remove parents with square child contours
for con in self.candidates:
if con.area > area_cutoff:
candidates_to_remove.append(con)
if self.debug:
log.info(
"remove_gigantic_candidates: %s area %d is greater than cutoff %d"
% (con, con.area, area_cutoff)
)
for x in candidates_to_remove:
self.remove_candidate_contour(x)
removed = len(candidates_to_remove)
if self.debug:
log.info(
"remove-gigantic-candidates: %d removed, %d remain\n"
% (removed, len(self.candidates))
)
return candidates_to_remove
def remove_square_within_square_candidates(self):
candidates_to_remove = []
# All non-square contours have been removed by this point so remove any contour
# that has a child contour. This allows us to remove the outer square in the
# "square within a square" scenario.
for con in self.candidates:
child = con.get_child()
if child:
candidates_to_remove.append(con)
if self.debug:
log.info("con %s will be removed, has child %s" % (con, child))
else:
if self.debug:
log.info("con %s will remain" % con)
for x in candidates_to_remove:
self.remove_candidate_contour(x)
removed = len(candidates_to_remove)
if self.debug:
log.info(
"remove-square-within-square-candidates %d removed, %d remain\n"
% (removed, len(self.candidates))
)
return True if removed else False
def get_median_square_area(self):
"""
Find the median area of all square contours
"""
square_areas = []
square_widths = []
total_square_area = 0
for con in self.candidates:
if con.is_square():
square_areas.append(int(con.area))
square_widths.append(int(con.width))
total_square_area += int(con.area)
if square_areas:
square_areas = sorted(square_areas)
square_widths = sorted(square_widths)
num_squares = len(square_areas)
# Do not take the exact median, take the one 2/3 of the way through
# the list. Sometimes you get clusters of smaller squares which can
# throw us off if we take the exact median.
square_area_index = int((2 * num_squares) / 3)
self.mean_square_area = int(total_square_area / len(square_areas))
self.median_square_area = int(square_areas[square_area_index])
self.median_square_width = int(square_widths[square_area_index])
if self.debug:
log.info(
"get_median_square_area: %d squares, median index %d, median area %s, mean area %s, all square areas %s"
% (
num_squares,
square_area_index,
self.median_square_area,
self.mean_square_area,
",".join(map(str, square_areas)),
)
)
log.info(
"get_median_square_area: %d squares, median index %d, median width %d, all square widths %s"
% (
num_squares,
square_area_index,
self.median_square_width,
",".join(map(str, square_widths)),
)
)
else:
self.mean_square_area = 0
self.median_square_area = 0
self.median_square_width = 0
if not square_areas:
raise CubeNotFound("%s no squares in image" % self.name)
def get_cube_boundry(self, strict):
"""
Find the top, right, bottom, left boundry of all square contours
"""
self.top = None
self.right = None
self.bottom = None
self.left = None
for con in self.candidates:
(
row_neighbors,
row_square_neighbors,
col_neighbors,
col_square_neighbors,
) = self.get_contour_neighbors(self.candidates, con)
if self.debug:
log.info(
"get_cube_boundry: %s row_neighbors %s, col_neighbors %s"
% (con, row_square_neighbors, col_square_neighbors)
)
if strict:
if self.size == 7:
if row_square_neighbors < 2 or col_square_neighbors < 2:
continue
elif self.size == 6:
if row_square_neighbors < 2 or col_square_neighbors < 2:
continue
elif self.size == 5:
if row_square_neighbors < 1 or col_square_neighbors < 1:
continue
elif self.size == 4:
if row_square_neighbors < 1 or col_square_neighbors < 1:
continue
elif self.size == 2:
if not row_neighbors and not col_neighbors:
continue
else:
if not row_neighbors and not col_neighbors:
continue
if not col_neighbors and row_neighbors >= self.size:
continue
if not row_neighbors and col_neighbors >= self.size:
continue
else:
# Ignore the rogue square with no neighbors. I used to do an "or" here but