-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrect.py
84 lines (67 loc) · 2.75 KB
/
rect.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
#!/usr/bin/python
"""Module for Rect class.
"""
import numpy as np
class Rect:
"""This class represents a rectangle.
Used for representing the game screen and regions of interest (ROIs.)
The `children` class attribute allows for some hierarchical structure.
"""
def __init__(self, top, left, height, width):
self.top = int(top)
self.left = int(left)
self.height = int(height)
self.width = int(width)
self.children = []
def __repr__(self):
this_repr = ['{height}x{width}+{top}+{left}'.format(**self.__dict__)]
for child in self.children:
for line in repr(child).split("\n"):
this_repr.append("-> " + line)
return "\n".join(this_repr)
def __and__(self, other):
"""Return the intersection of `self` and `other`.
"""
overlap_left = max(self.left, other.left)
overlap_top = max(self.top, other.top)
overlap_right = min(self.left + self.width, other.left + other.width)
overlap_bottom = min(self.top + self.height, other.top + other.height)
if overlap_left > overlap_right or overlap_top > overlap_bottom:
return None
return Rect(overlap_top,
overlap_left,
overlap_bottom - overlap_top,
overlap_right - overlap_left)
def to_mask(self, height, width, color=True):
"""Generate a zero-one mask from this Rect, viewed as part of a larger
rectangle. The mask will have the same height, width, and
top-left as this Rect.
Ones/zeros correspond to pixels and denote "in mask"/"not in mask"
respectively.
Parameters:
`height`: height of the larger rectangle.
`width`: width of the larger rectangle.
"""
if color:
shape = (height, width, 3)
fill = (1, 1, 1)
else:
shape = (height, width)
fill = 1
mask = np.zeros(shape)
mask[self.top:(self.top + self.height + 1),
self.left:(self.left + self.width + 1)] = fill
return mask.astype(np.uint8)
def subregion(self, pct_top, pct_left, pct_height, pct_width,
padding=0):
"""Return the subregion from
(pct_top)*100% to (pct_top + pct_height)*100%,
(pct_left)*100% to (pct_left + pct_width)*100%,
plus a bevel of (padding)*100%,
intersected with the screen.
"""
top = self.top + (pct_top - padding) * self.height
left = self.left + (pct_left - padding) * self.width
height = (padding + pct_height + padding) * self.height
width = (padding + pct_width + padding) * self.width
return Rect(top, left, height, width) & self