-
Notifications
You must be signed in to change notification settings - Fork 487
/
Copy pathlayout_elements.py
1352 lines (1067 loc) · 44.9 KB
/
layout_elements.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
# Copyright 2021 The Layout Parser team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import List, Union, Dict, Dict, Any, Optional, Tuple
from collections.abc import Iterable
from copy import copy
from inspect import getmembers, isfunction
import warnings
import functools
import numpy as np
import pandas as pd
from PIL import Image
from cv2 import getPerspectiveTransform as _getPerspectiveTransform
from cv2 import warpPerspective as _warpPerspective
from .base import BaseCoordElement, BaseLayoutElement
from .utils import (
cvt_coordinates_to_points,
cvt_points_to_coordinates,
perspective_transformation,
vertice_in_polygon,
polygon_area,
)
from .errors import NotSupportedShapeError, InvalidShapeError
def mixin_textblock_meta(func):
@functools.wraps(func)
def wrap(self, *args, **kwargs):
out = func(self, *args, **kwargs)
if isinstance(out, BaseCoordElement):
self = copy(self)
self.block = out
return self
return wrap
def inherit_docstrings(cls=None, *, base_class=None):
# Refer to https://stackoverflow.com/a/17393254
if cls is None:
return functools.partial(inherit_docstrings, base_class=base_class)
for name, func in getmembers(cls, isfunction):
if func.__doc__:
continue
if base_class == None:
for parent in cls.__mro__[1:]:
if hasattr(parent, name):
func.__doc__ = getattr(parent, name).__doc__
break
else:
if hasattr(base_class, name):
func.__doc__ = getattr(base_class, name).__doc__
return cls
def support_textblock(func):
@functools.wraps(func)
def wrap(self, other, *args, **kwargs):
if isinstance(other, TextBlock):
other = other.block
out = func(self, other, *args, **kwargs)
return out
return wrap
@inherit_docstrings
class Interval(BaseCoordElement):
"""
This class describes the coordinate system of an interval, a block defined by a pair of start and end point
on the designated axis and same length as the base canvas on the other axis.
Args:
start (:obj:`numeric`):
The coordinate of the start point on the designated axis.
end (:obj:`numeric`):
The end coordinate on the same axis as start.
axis (:obj:`str`):
The designated axis that the end points belong to.
canvas_height (:obj:`numeric`, `optional`, defaults to 0):
The height of the canvas that the interval is on.
canvas_width (:obj:`numeric`, `optional`, defaults to 0):
The width of the canvas that the interval is on.
"""
_name = "interval"
_features = ["start", "end", "axis", "canvas_height", "canvas_width"]
def __init__(self, start, end, axis, canvas_height=None, canvas_width=None):
assert start <= end, f"Invalid input for start and end. Start must <= end."
self.start = start
self.end = end
assert axis in ["x", "y"], f"Invalid axis {axis}. Axis must be in 'x' or 'y'"
self.axis = axis
self.canvas_height = canvas_height or 0
self.canvas_width = canvas_width or 0
@property
def height(self):
"""
Calculate the height of the interval. If the interval is along the x-axis, the height will be the
height of the canvas, otherwise, it will be the difference between the start and end point.
Returns:
:obj:`numeric`: Output the numeric value of the height.
"""
if self.axis == "x":
return self.canvas_height
else:
return self.end - self.start
@property
def width(self):
"""
Calculate the width of the interval. If the interval is along the y-axis, the width will be the
width of the canvas, otherwise, it will be the difference between the start and end point.
Returns:
:obj:`numeric`: Output the numeric value of the width.
"""
if self.axis == "y":
return self.canvas_width
else:
return self.end - self.start
@property
def coordinates(self):
"""
This method considers an interval as a rectangle and calculates the coordinates of the upper left
and lower right corners to define the interval.
Returns:
:obj:`Tuple(numeric)`:
Output the numeric values of the coordinates in a Tuple of size four.
"""
if self.axis == "x":
coords = (self.start, 0, self.end, self.canvas_height)
else:
coords = (0, self.start, self.canvas_width, self.end)
return coords
@property
def points(self):
"""
Return the coordinates of all four corners of the interval in a clockwise fashion
starting from the upper left.
Returns:
:obj:`Numpy array`: A Numpy array of shape 4x2 containing the coordinates.
"""
return cvt_coordinates_to_points(self.coordinates)
@property
def center(self):
"""
Calculate the mid-point between the start and end point.
Returns:
:obj:`Tuple(numeric)`: Returns of coordinate of the center.
"""
return (self.start + self.end) / 2.0
@property
def area(self):
"""Return the area of the covered region of the interval.
The area is bounded to the canvas. If the interval is put
on a canvas, the area equals to interval width * canvas height
(axis='x') or interval height * canvas width (axis='y').
Otherwise, the area is zero.
"""
return self.height * self.width
def put_on_canvas(self, canvas):
"""
Set the height and the width of the canvas that the interval is on.
Args:
canvas (:obj:`Numpy array` or :obj:`BaseCoordElement` or :obj:`PIL.Image.Image`):
The base element that the interval is on. The numpy array should be the
format of `[height, width]`.
Returns:
:obj:`Interval`:
A copy of the current Interval with its canvas height and width set to
those of the input canvas.
"""
if isinstance(canvas, np.ndarray):
h, w = canvas.shape[:2]
elif isinstance(canvas, BaseCoordElement):
h, w = canvas.height, canvas.width
elif isinstance(canvas, Image.Image):
w, h = canvas.size
else:
raise NotImplementedError
return self.set(canvas_height=h, canvas_width=w)
@support_textblock
def condition_on(self, other):
if isinstance(other, Interval):
if other.axis == self.axis:
d = other.start
# Reset the canvas size in the absolute coordinates
return self.__class__(self.start + d, self.end + d, self.axis)
else:
return copy(self)
elif isinstance(other, Rectangle):
return self.put_on_canvas(other).to_rectangle().condition_on(other)
elif isinstance(other, Quadrilateral):
return self.put_on_canvas(other).to_quadrilateral().condition_on(other)
else:
raise Exception(f"Invalid input type {other.__class__} for other")
@support_textblock
def relative_to(self, other):
if isinstance(other, Interval):
if other.axis == self.axis:
d = other.start
# Reset the canvas size in the absolute coordinates
return self.__class__(self.start - d, self.end - d, self.axis)
else:
return copy(self)
elif isinstance(other, Rectangle):
return self.put_on_canvas(other).to_rectangle().relative_to(other)
elif isinstance(other, Quadrilateral):
return self.put_on_canvas(other).to_quadrilateral().relative_to(other)
else:
raise Exception(f"Invalid input type {other.__class__} for other")
@support_textblock
def is_in(self, other, soft_margin={}, center=False):
other = other.pad(**soft_margin)
if isinstance(other, Interval):
if self.axis != other.axis:
return False
else:
if not center:
return other.start <= self.start <= self.end <= other.end
else:
return other.start <= self.center <= other.end
elif isinstance(other, Rectangle) or isinstance(other, Quadrilateral):
x_1, y_1, x_2, y_2 = other.coordinates
if center:
if self.axis == "x":
return x_1 <= self.center <= x_2
else:
return y_1 <= self.center <= y_2
else:
if self.axis == "x":
return x_1 <= self.start <= self.end <= x_2
else:
return y_1 <= self.start <= self.end <= y_2
else:
raise Exception(f"Invalid input type {other.__class__} for other")
@support_textblock
def intersect(self, other: BaseCoordElement, strict: bool = True):
""""""
if isinstance(other, Interval):
if self.axis != other.axis:
if self.axis == "x" and other.axis == "y":
return Rectangle(self.start, other.start, self.end, other.end)
else:
return Rectangle(other.start, self.start, other.end, self.end)
else:
return self.__class__(
max(self.start, other.start),
min(self.end, other.end),
self.axis,
self.canvas_height,
self.canvas_width,
)
elif isinstance(other, Rectangle):
x_1, y_1, x_2, y_2 = other.coordinates
if self.axis == "x":
return Rectangle(max(x_1, self.start), y_1, min(x_2, self.end), y_2)
elif self.axis == "y":
return Rectangle(x_1, max(y_1, self.start), x_2, min(y_2, self.end))
elif isinstance(other, Quadrilateral):
if strict:
raise NotSupportedShapeError(
"The intersection between an Interval and a Quadrilateral might generate Polygon shapes that are not supported in the current version of layoutparser. You can pass `strict=False` in the input that converts the Quadrilateral to Rectangle to avoid this Exception."
)
else:
warnings.warn(
f"With `strict=False`, the other of shape {other.__class__} will be converted to {Rectangle} for obtaining the intersection"
)
return self.intersect(other.to_rectangle())
else:
raise Exception(f"Invalid input type {other.__class__} for other")
@support_textblock
def union(self, other: BaseCoordElement, strict: bool = True):
""""""
if isinstance(other, Interval):
if self.axis != other.axis:
raise InvalidShapeError(
f"Unioning two intervals of different axes is not allowed."
)
else:
return self.__class__(
min(self.start, other.start),
max(self.end, other.end),
self.axis,
self.canvas_height,
self.canvas_width,
)
elif isinstance(other, Rectangle):
x_1, y_1, x_2, y_2 = other.coordinates
if self.axis == "x":
return Rectangle(min(x_1, self.start), y_1, max(x_2, self.end), y_2)
elif self.axis == "y":
return Rectangle(x_1, min(y_1, self.start), x_2, max(y_2, self.end))
elif isinstance(other, Quadrilateral):
if strict:
raise NotSupportedShapeError(
"The intersection between an Interval and a Quadrilateral might generate Polygon shapes that are not supported in the current version of layoutparser. You can pass `strict=False` in the input that converts the Quadrilateral to Rectangle to avoid this Exception."
)
else:
warnings.warn(
f"With `strict=False`, the other of shape {other.__class__} will be converted to {Rectangle} for obtaining the intersection"
)
return self.union(other.to_rectangle())
else:
raise Exception(f"Invalid input type {other.__class__} for other")
def pad(self, left=0, right=0, top=0, bottom=0, safe_mode=True):
if self.axis == "x":
start = self.start - left
end = self.end + right
if top or bottom:
warnings.warn(
f"Invalid padding top/bottom for an x axis {self.__class__.__name__}"
)
else:
start = self.start - top
end = self.end + bottom
if left or right:
warnings.warn(
f"Invalid padding right/left for a y axis {self.__class__.__name__}"
)
if safe_mode:
start = max(0, start)
return self.set(start=start, end=end)
def shift(self, shift_distance):
"""
Shift the interval by a user specified amount along the same axis that the interval is defined on.
Args:
shift_distance (:obj:`numeric`): The number of pixels used to shift the interval.
Returns:
:obj:`BaseCoordElement`: The shifted Interval object.
"""
if isinstance(shift_distance, Iterable):
shift_distance = (
shift_distance[0] if self.axis == "x" else shift_distance[1]
)
warnings.warn(
f"Input shift for multiple axes. Only use the distance for the {self.axis} axis"
)
start = self.start + shift_distance
end = self.end + shift_distance
return self.set(start=start, end=end)
def scale(self, scale_factor):
"""
Scale the layout element by a user specified amount the same axis that the interval is defined on.
Args:
scale_factor (:obj:`numeric`): The amount for downscaling or upscaling the element.
Returns:
:obj:`BaseCoordElement`: The scaled Interval object.
"""
if isinstance(scale_factor, Iterable):
scale_factor = scale_factor[0] if self.axis == "x" else scale_factor[1]
warnings.warn(
f"Input scale for multiple axes. Only use the factor for the {self.axis} axis"
)
start = self.start * scale_factor
end = self.end * scale_factor
return self.set(start=start, end=end)
def crop_image(self, image):
x_1, y_1, x_2, y_2 = self.put_on_canvas(image).coordinates
return image[int(y_1) : int(y_2), int(x_1) : int(x_2)]
def to_rectangle(self):
"""
Convert the Interval to a Rectangle element.
Returns:
:obj:`Rectangle`: The converted Rectangle object.
"""
return Rectangle(*self.coordinates)
def to_quadrilateral(self):
"""
Convert the Interval to a Quadrilateral element.
Returns:
:obj:`Quadrilateral`: The converted Quadrilateral object.
"""
return Quadrilateral(self.points)
@inherit_docstrings
class Rectangle(BaseCoordElement):
"""
This class describes the coordinate system of an axial rectangle box using two points as indicated below::
(x_1, y_1) ----
| |
| |
| |
---- (x_2, y_2)
Args:
x_1 (:obj:`numeric`):
x coordinate on the horizontal axis of the upper left corner of the rectangle.
y_1 (:obj:`numeric`):
y coordinate on the vertical axis of the upper left corner of the rectangle.
x_2 (:obj:`numeric`):
x coordinate on the horizontal axis of the lower right corner of the rectangle.
y_2 (:obj:`numeric`):
y coordinate on the vertical axis of the lower right corner of the rectangle.
"""
_name = "rectangle"
_features = ["x_1", "y_1", "x_2", "y_2"]
def __init__(self, x_1, y_1, x_2, y_2):
self.x_1 = x_1
self.y_1 = y_1
self.x_2 = x_2
self.y_2 = y_2
@property
def height(self):
"""
Calculate the height of the rectangle.
Returns:
:obj:`numeric`: Output the numeric value of the height.
"""
return self.y_2 - self.y_1
@property
def width(self):
"""
Calculate the width of the rectangle.
Returns:
:obj:`numeric`: Output the numeric value of the width.
"""
return self.x_2 - self.x_1
@property
def coordinates(self):
"""
Return the coordinates of the two points that define the rectangle.
Returns:
:obj:`Tuple(numeric)`: Output the numeric values of the coordinates in a Tuple of size four.
"""
return (self.x_1, self.y_1, self.x_2, self.y_2)
@property
def points(self):
"""
Return the coordinates of all four corners of the rectangle in a clockwise fashion
starting from the upper left.
Returns:
:obj:`Numpy array`: A Numpy array of shape 4x2 containing the coordinates.
"""
return cvt_coordinates_to_points(self.coordinates)
@property
def center(self):
"""
Calculate the center of the rectangle.
Returns:
:obj:`Tuple(numeric)`: Returns of coordinate of the center.
"""
return (self.x_1 + self.x_2) / 2.0, (self.y_1 + self.y_2) / 2.0
@property
def area(self):
"""
Return the area of the rectangle.
"""
return self.width * self.height
@support_textblock
def condition_on(self, other):
if isinstance(other, Interval):
if other.axis == "x":
dx, dy = other.start, 0
else:
dx, dy = 0, other.start
return self.__class__(
self.x_1 + dx, self.y_1 + dy, self.x_2 + dx, self.y_2 + dy
)
elif isinstance(other, Rectangle):
dx, dy, _, _ = other.coordinates
return self.__class__(
self.x_1 + dx, self.y_1 + dy, self.x_2 + dx, self.y_2 + dy
)
elif isinstance(other, Quadrilateral):
transformed_points = perspective_transformation(
other.perspective_matrix, self.points, is_inv=True
)
return other.__class__(transformed_points, self.height, self.width)
else:
raise Exception(f"Invalid input type {other.__class__} for other")
@support_textblock
def relative_to(self, other):
if isinstance(other, Interval):
if other.axis == "x":
dx, dy = other.start, 0
else:
dx, dy = 0, other.start
return self.__class__(
self.x_1 - dx, self.y_1 - dy, self.x_2 - dx, self.y_2 - dy
)
elif isinstance(other, Rectangle):
dx, dy, _, _ = other.coordinates
return self.__class__(
self.x_1 - dx, self.y_1 - dy, self.x_2 - dx, self.y_2 - dy
)
elif isinstance(other, Quadrilateral):
transformed_points = perspective_transformation(
other.perspective_matrix, self.points, is_inv=False
)
return other.__class__(transformed_points, self.height, self.width)
else:
raise Exception(f"Invalid input type {other.__class__} for other")
@support_textblock
def is_in(self, other, soft_margin={}, center=False):
other = other.pad(**soft_margin)
if isinstance(other, Interval):
if not center:
if other.axis == "x":
start, end = self.x_1, self.x_2
else:
start, end = self.y_1, self.y_2
return other.start <= start <= end <= other.end
else:
c = self.center[0] if other.axis == "x" else self.center[1]
return other.start <= c <= other.end
elif isinstance(other, Rectangle):
x_interval = other.to_interval(axis="x")
y_interval = other.to_interval(axis="y")
return self.is_in(x_interval, center=center) and self.is_in(
y_interval, center=center
)
elif isinstance(other, Quadrilateral):
if not center:
# This is equivalent to determine all the points of the
# rectangle is in the quadrilateral.
is_vertice_in = [
vertice_in_polygon(vertice, other.points) for vertice in self.points
]
return all(is_vertice_in)
else:
center = np.array(self.center)
return vertice_in_polygon(center, other.points)
else:
raise Exception(f"Invalid input type {other.__class__} for other")
@support_textblock
def intersect(self, other: BaseCoordElement, strict: bool = True):
""""""
if isinstance(other, Interval):
return other.intersect(self)
elif isinstance(other, Rectangle):
return self.__class__(
max(self.x_1, other.x_1),
max(self.y_1, other.y_1),
min(self.x_2, other.x_2),
min(self.y_2, other.y_2),
)
elif isinstance(other, Quadrilateral):
if strict:
raise NotSupportedShapeError(
"The intersection between a Rectangle and a Quadrilateral might generate Polygon shapes that are not supported in the current version of layoutparser. You can pass `strict=False` in the input that converts the Quadrilateral to Rectangle to avoid this Exception."
)
else:
warnings.warn(
f"With `strict=False`, the other of shape {other.__class__} will be converted to {Rectangle} for obtaining the intersection"
)
return self.intersect(other.to_rectangle())
else:
raise Exception(f"Invalid input type {other.__class__} for other")
@support_textblock
def union(self, other: BaseCoordElement, strict: bool = True):
""""""
if isinstance(other, Interval):
return other.intersect(self)
elif isinstance(other, Rectangle):
return self.__class__(
min(self.x_1, other.x_1),
min(self.y_1, other.y_1),
max(self.x_2, other.x_2),
max(self.y_2, other.y_2),
)
elif isinstance(other, Quadrilateral):
if strict:
raise NotSupportedShapeError(
"The intersection between an Interval and a Quadrilateral might generate Polygon shapes that are not supported in the current version of layoutparser. You can pass `strict=False` in the input that converts the Quadrilateral to Rectangle to avoid this Exception."
)
else:
warnings.warn(
f"With `strict=False`, the other of shape {other.__class__} will be converted to {Rectangle} for obtaining the intersection"
)
return self.union(other.to_rectangle())
else:
raise Exception(f"Invalid input type {other.__class__} for other")
def pad(self, left=0, right=0, top=0, bottom=0, safe_mode=True):
x_1 = self.x_1 - left
y_1 = self.y_1 - top
x_2 = self.x_2 + right
y_2 = self.y_2 + bottom
if safe_mode:
x_1 = max(0, x_1)
y_1 = max(0, y_1)
return self.__class__(x_1, y_1, x_2, y_2)
def shift(self, shift_distance=0):
if not isinstance(shift_distance, Iterable):
shift_x = shift_distance
shift_y = shift_distance
else:
assert (
len(shift_distance) == 2
), "shift_distance should have 2 elements, one for x dimension and one for y dimension"
shift_x, shift_y = shift_distance
x_1 = self.x_1 + shift_x
y_1 = self.y_1 + shift_y
x_2 = self.x_2 + shift_x
y_2 = self.y_2 + shift_y
return self.__class__(x_1, y_1, x_2, y_2)
def scale(self, scale_factor=1):
if not isinstance(scale_factor, Iterable):
scale_x = scale_factor
scale_y = scale_factor
else:
assert (
len(scale_factor) == 2
), "scale_factor should have 2 elements, one for x dimension and one for y dimension"
scale_x, scale_y = scale_factor
x_1 = self.x_1 * scale_x
y_1 = self.y_1 * scale_y
x_2 = self.x_2 * scale_x
y_2 = self.y_2 * scale_y
return self.__class__(x_1, y_1, x_2, y_2)
def crop_image(self, image):
x_1, y_1, x_2, y_2 = self.coordinates
return image[int(y_1) : int(y_2), int(x_1) : int(x_2)]
def to_interval(self, axis, **kwargs):
if axis == "x":
start, end = self.x_1, self.x_2
else:
start, end = self.y_1, self.y_2
return Interval(start, end, axis=axis, **kwargs)
def to_quadrilateral(self):
return Quadrilateral(self.points)
@inherit_docstrings
class Quadrilateral(BaseCoordElement):
"""
This class describes the coodinate system of a four-sided polygon. A quadrilateral is defined by
the coordinates of its 4 corners in a clockwise order starting with the upper left corner (as shown below)::
points[0] -...- points[1]
| |
. .
. .
. .
| |
points[3] -...- points[2]
Args:
points (:obj:`Numpy array` or `list`):
A `np.ndarray` of shape 4x2 for four corner coordinates
or a list of length 8 for in the format of
`[p0_x, p0_y, p1_x, p1_y, p2_x, p2_y, p3_x, p3_y]`
or a list of length 4 in the format of
`[[p0_x, p0_y], [p1_x, p1_y], [p2_x, p2_y], [p3_x, p3_y]]`.
height (:obj:`numeric`, `optional`, defaults to `None`):
The height of the quadrilateral. This is to better support the perspective
transformation from the OpenCV library.
width (:obj:`numeric`, `optional`, defaults to `None`):
The width of the quadrilateral. Similarly as height, this is to better support the perspective
transformation from the OpenCV library.
"""
_name = "quadrilateral"
_features = ["points", "height", "width"]
def __init__(
self, points: Union[np.ndarray, List, List[List]], height=None, width=None
):
if isinstance(points, np.ndarray):
if points.shape != (4, 2):
raise ValueError(f"Invalid points shape: {points.shape}.")
elif isinstance(points, list):
if len(points) == 8:
points = np.array(points).reshape(4, 2)
elif len(points) == 4 and isinstance(points[0], list):
points = np.array(points)
else:
raise ValueError(
f"Invalid number of points element {len(points)}. Should be 8."
)
else:
raise ValueError(
f"Invalid input type for points {type(points)}."
"Please make sure it is a list of np.ndarray."
)
self._points = points
self._width = width
self._height = height
@property
def height(self):
"""
Return the user defined height, otherwise the height of its circumscribed rectangle.
Returns:
:obj:`numeric`: Output the numeric value of the height.
"""
if self._height is not None:
return self._height
return self.points[:, 1].max() - self.points[:, 1].min()
@property
def width(self):
"""
Return the user defined width, otherwise the width of its circumscribed rectangle.
Returns:
:obj:`numeric`: Output the numeric value of the width.
"""
if self._width is not None:
return self._width
return self.points[:, 0].max() - self.points[:, 0].min()
@property
def coordinates(self):
"""
Return the coordinates of the upper left and lower right corners points that
define the circumscribed rectangle.
Returns
:obj:`Tuple(numeric)`: Output the numeric values of the coordinates in a Tuple of size four.
"""
return cvt_points_to_coordinates(self.points)
@property
def points(self):
"""
Return the coordinates of all four corners of the quadrilateral in a clockwise fashion
starting from the upper left.
Returns:
:obj:`Numpy array`: A Numpy array of shape 4x2 containing the coordinates.
"""
return self._points
@property
def center(self):
"""
Calculate the center of the quadrilateral.
Returns:
:obj:`Tuple(numeric)`: Returns of coordinate of the center.
"""
return tuple(self.points.mean(axis=0).tolist())
@property
def area(self):
"""
Return the area of the quadrilateral.
"""
return polygon_area(self.points[:, 0], self.points[:, 1])
@property
def mapped_rectangle_points(self):
x_map = {0: 0, 1: 0, 2: self.width, 3: self.width}
y_map = {0: 0, 1: 0, 2: self.height, 3: self.height}
return self.map_to_points_ordering(x_map, y_map)
@property
def perspective_matrix(self):
return _getPerspectiveTransform(
self.points.astype("float32"),
self.mapped_rectangle_points.astype("float32"),
)
def map_to_points_ordering(self, x_map, y_map):
points_ordering = self.points.argsort(axis=0).argsort(axis=0)
# Ref: https://github.com/numpy/numpy/issues/8757#issuecomment-355126992
return np.vstack(
[
np.vectorize(x_map.get)(points_ordering[:, 0]),
np.vectorize(y_map.get)(points_ordering[:, 1]),
]
).T
@support_textblock
def condition_on(self, other):
if isinstance(other, Interval):
if other.axis == "x":
return self.shift([other.start, 0])
else:
return self.shift([0, other.start])
elif isinstance(other, Rectangle):
return self.shift([other.x_1, other.y_1])
elif isinstance(other, Quadrilateral):
transformed_points = perspective_transformation(
other.perspective_matrix, self.points, is_inv=True
)
return self.__class__(transformed_points, self.height, self.width)
else:
raise Exception(f"Invalid input type {other.__class__} for other")
@support_textblock
def relative_to(self, other):
if isinstance(other, Interval):
if other.axis == "x":
return self.shift([-other.start, 0])
else:
return self.shift([0, -other.start])
elif isinstance(other, Rectangle):
return self.shift([-other.x_1, -other.y_1])
elif isinstance(other, Quadrilateral):
transformed_points = perspective_transformation(
other.perspective_matrix, self.points, is_inv=False
)
return self.__class__(transformed_points, self.height, self.width)
else:
raise Exception(f"Invalid input type {other.__class__} for other")
@support_textblock
def is_in(self, other, soft_margin={}, center=False):
other = other.pad(**soft_margin)
if isinstance(other, Interval):
if not center:
if other.axis == "x":
start, end = self.coordinates[0], self.coordinates[2]
else:
start, end = self.coordinates[1], self.coordinates[3]
return other.start <= start <= end <= other.end
else:
c = self.center[0] if other.axis == "x" else self.center[1]
return other.start <= c <= other.end
elif isinstance(other, Rectangle):
x_interval = other.to_interval(axis="x")
y_interval = other.to_interval(axis="y")
return self.is_in(x_interval, center=center) and self.is_in(