summaryrefslogtreecommitdiff
path: root/megapixels/app/models/bbox.py
blob: 55a92512c64b8e332fd9c3a36ef81c22dccbaffc (plain)
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
import math

from dlib import rectangle as dlib_rectangle
import numpy as np


class BBoxPoint:

  def __init__(self, x, y):
    self._x = x
    self._y = y

  @property
  def x(self):
    return self._x
  
  @property
  def y(self):
    return self._y
  
  def offset(self, x, y):
    return (self._x + x, self._y + y)

  def tuple(self):
    return (self._x, self._y)


class BBox:

  def __init__(self, x1, y1, x2, y2):
    """Represents a bounding box and provides methods for accessing and modifying
    :param x1: normalized left coord
    :param y1: normalized top coord
    :param x2: normalized right coord
    :param y2: normalized bottom coord
    """
    self._x1 = x1
    self._y1 = y1
    self._x2 = x2
    self._y2 = y2
    self._width = x2 - x1
    self._height = y2 - y1
    self._cx = x1 + (self._width // 2)
    self._cy = y1 + (self._height // 2)
    self._tl = (x1, y1)
    self._br = (x2, y2)
    self._rect = (self._x1, self._y1, self._x2, self._y2)
    self._area = self._width * self._height  # as percentage

  @property
  def area(self):
    return self._area
  
  @property
  def pt_tl(self):
    return self._tl

  @property
  def pt_br(self):
    return self._br

  @property
  def x(self):
    return self._x1
  
  @property
  def y(self):
    return self._y1

  @property
  def x1(self):
    return self._x1
  
  @property
  def y1(self):
    return self._y1


  @property
  def x2(self):
    return self._x2
  
  @property
  def y2(self):
    return self._y2
  
  @property
  def height(self):
    return self._height

  @property
  def width(self):
    return self._width

  @property
  def h(self):
    return self._height

  @property
  def w(self):
    return self._width

  @property
  def cx(self):
    return self._cx

  @property
  def cy(self):
    return self._cy
  
  # # -----------------------------------------------------------------
  # # Utils

  # def constrain(self, dim):
  def distance(self, b):
    a = self
    dcx = self._cx - b.cx
    dcy = self._cy - b.cy
    d = int(math.sqrt(math.pow(dcx, 2) + math.pow(dcy, 2)))
    return d

  # -----------------------------------------------------------------
  # Modify

  def expand_dim(self, amt, dim):
    """Expands BBox within dim
    :param box: (tuple) left, top, right, bottom
    :param dim: (tuple) width, height
    :returns (BBox) in pixel dimensions
    """
    # expand
    r = list( (np.array(self._rect) + np.array([-amt, -amt, amt, amt])).astype('int'))
    # outliers
    oob = list(range(4))
    oob[0] = min(r[0], 0)
    oob[1] = min(r[1], 0)
    oob[2] = dim[0] - r[2]
    oob[3] = dim[1] - r[3]
    oob = np.array(oob)
    oob[oob > 0] = 0
    # absolute amount
    oob = np.absolute(oob)
    # threshold expanded rectangle
    r[0] = max(r[0], 0)
    r[1] = max(r[1], 0)
    r[2] = min(r[2], dim[0])
    r[3] = min(r[3], dim[1])
    # redistribute oob amounts
    oob = np.array([-oob[2], -oob[3], oob[0], oob[1]])
    r = np.add(np.array(r), oob)
    # find overage
    oob[0] = min(r[0], 0)
    oob[1] = min(r[1], 0)
    oob[2] = dim[0] - r[2]
    oob[3] = dim[1] - r[3]
    oob = np.array(oob)
    oob[oob > 0] = 0
    oob = np.absolute(oob)
    if np.array(oob).any():
      m = np.max(oob)
      adj = np.array([m, m, -m, -m])
      # print(adj)
      r = np.add(np.array(r), adj)

    return BBox(*r)    


  # -----------------------------------------------------------------
  # Convert to

  def to_dim(self, dim):
    """scale is (w, h) is tuple of dimensions"""
    w, h = dim
    rect = list((np.array(self._rect) * np.array([w, h, w, h])).astype('int'))
    return BBox(*rect)

  def normalize(self, rect, dim):
    w, h = dim
    x1, y1, x2, y2 = rect
    return (x1 / w, y1 / h, x2 / w, y2 / h)

  # -----------------------------------------------------------------
  # Format as

  def to_xyxy(self):
    """Converts BBox back to x1, y1, x2, y2 rect"""
    return (self._x1, self._y1, self._x2, self._y2)

  def to_xywh(self):
    """Converts BBox back to haar type"""
    return (self._x1, self._y1, self._width, self._height)

  def to_trbl(self):
    """Converts BBox to CSS (top, right, bottom, left)""" 
    return (self._y1, self._x2, self._y2, self._x1)

  def to_dlib(self):
    """Converts BBox to dlib rect type"""
    return dlib_rectangle(self._x1, self._y1, self._x2, self._y2)

  def to_yolo(self):
    """Converts BBox to normalized center x, center y, w, h"""
    return (self._cx, self._cy, self._width, self._height)


  # -----------------------------------------------------------------
  # Create from

  @classmethod
  def from_xyxy_dim(cls, x1, y1, x2, y2, dim):
    """Converts x1, y1, w, h to BBox and normalizes
    :returns BBox
    """
    rect = cls.normalize(cls, (x1, y1, x2, y2), dim)
    return cls(*rect)

  @classmethod
  def from_xywh_dim(cls, x, y, w, h, dim):
    """Converts x1, y1, w, h to BBox and normalizes
    :param rect: (list) x1, y1, w, h
    :param dim: (list) w, h
    :returns BBox
    """
    rect = cls.normalize(cls, (x, y, x + w, y + h), dim)
    return cls(*rect)

  @classmethod
  def from_xyxy(cls, x1, y1, x2, y2):
    """Converts x1, y1, x2, y2 to BBox
    same as constructure but zprovided for conveniene
    """
    return cls(x1, y1, x2, y2)

  @classmethod
  def from_xywh(cls, x, y, w, h):
    """Converts x1, y1, w, h to BBox
    :param rect: (list) x1, y1, w, h
    :param dim: (list) w, h
    :returns BBox
    """
    return cls(x, y, x+w, y+h)

  @classmethod
  def from_css(cls, rect, dim):
    """Converts rect from CSS (top, right, bottom, left) to BBox
    :param rect: (list) x1, y1, x2, y2
    :param dim: (list) w, h
    :returns BBox
    """
    rect = (rect[3], rect[0], rect[1], rect[2])
    rect = cls.normalize(cls, rect, dim)
    return cls(*rect)

  @classmethod
  def from_dlib_dim(cls, rect, dim):
    """Converts dlib.rectangle to BBox
    :param rect: (list) x1, y1, x2, y2
    :param dim: (list) w, h
    :returns dlib.rectangle
    """ 
    rect = (rect.left(), rect.top(), rect.right(), rect.bottom())
    rect = cls.normalize(cls, rect, dim)
    return cls(*rect) 

  def __str__(self):
    return f'BBox: ({self._x1},{self._y1}), ({self._x2}, {self._y2}), width:{self._width}, height:{self._height}'

  def __repr__(self):
    return f'BBox: ({self._x1},{self._y1}), ({self._x2}, {self._y2}), width:{self._width}, height:{self._height}'

  def str(self):
    """Return BBox as a string "x1, y1, x2, y2" """
    return self.as_box()