blob: 02ace991ad98fe5a4d41e2fa7e00920991fd529f [file] [log] [blame]
Just470b5052000-01-16 20:37:11 +00001#
Justdeb3b632000-01-26 19:32:45 +00002# Various array and rectangle tools
Just470b5052000-01-16 20:37:11 +00003#
4
5import Numeric
6
7
8def calcBounds(array):
9 """Calculate the bounding rectangle of a 2D array.
10 Returns a 4-tuple:
11 smallest x, smallest y, largest x, largest y.
12 """
13 if len(array) == 0:
14 return 0, 0, 0, 0
15 xmin, ymin = Numeric.minimum.reduce(array)
16 xmax, ymax = Numeric.maximum.reduce(array)
17 return xmin, ymin, xmax, ymax
18
jvr182a7ba2003-06-29 18:18:54 +000019def updateBounds(bounds, (x, y), min=min, max=max):
20 """Return the bounding recangle of rectangle bounds and point (x, y)."""
21 xMin, yMin, xMax, yMax = bounds
22 return min(xMin, x), min(yMin, y), max(xMax, x), max(yMax, y)
23
24def pointInRect((x, y), rect):
25 """Return True when point (x, y) is inside rect."""
26 xMin, yMin, xMax, yMax = rect
27 return (xMin <= x <= xMax) and (yMin <= y <= yMax)
28
Just470b5052000-01-16 20:37:11 +000029def pointsInRect(array, rect):
30 """Find out which points or array are inside rect.
31 Returns an array with a boolean for each point.
32 """
33 if len(array) < 1:
34 return []
35 lefttop = rect[:2]
36 rightbottom = rect[2:]
37 condition = Numeric.logical_and(
38 Numeric.greater(array, lefttop),
39 Numeric.less(array, rightbottom))
40 return Numeric.logical_and.reduce(condition, -1)
41
Justdeb3b632000-01-26 19:32:45 +000042def vectorLength(vector):
43 return Numeric.sqrt(vector[0]**2 + vector[1]**2)
44
45def asInt16(array):
46 "Round and cast to 16 bit integer."
47 return Numeric.floor(array + 0.5).astype(Numeric.Int16)
48
Just470b5052000-01-16 20:37:11 +000049
50def normRect((l, t, r, b)):
51 """XXX doc"""
52 return min(l, r), min(t, b), max(l, r), max(t, b)
53
54def scaleRect((l, t, r, b), x, y):
55 return l * x, t * y, r * x, b * y
56
57def offsetRect((l, t, r, b), dx, dy):
58 return l+dx, t+dy, r+dx, b+dy
Justbe7163c2000-01-18 22:29:39 +000059
60def insetRect((l, t, r, b), dx, dy):
61 return l+dx, t+dy, r-dx, b-dy
62
63def sectRect((l1, t1, r1, b1), (l2, t2, r2, b2)):
64 l, t, r, b = max(l1, l2), max(t1, t2), min(r1, r2), min(b1, b2)
65 if l >= r or t >= b:
66 return 0, (0, 0, 0, 0)
67 return 1, (l, t, r, b)
68
Just02a739a2000-01-23 19:10:27 +000069def unionRect((l1, t1, r1, b1), (l2, t2, r2, b2)):
70 l, t, r, b = min(l1, l2), min(t1, t2), max(r1, r2), max(b1, b2)
71 return (l, t, r, b)
72
73def rectCenter((l, t, r, b)):
74 return (l+r)/2, (t+b)/2
75
Justb3026ba2000-01-22 00:26:07 +000076def intRect(rect):
77 rect = Numeric.array(rect)
78 l, t = Numeric.floor(rect[:2])
79 r, b = Numeric.ceil(rect[2:])
80 return tuple(Numeric.array((l, t, r, b)).astype(Numeric.Int))
Justbe7163c2000-01-18 22:29:39 +000081