blob: fde004f40495f90f0cc4da23768ac193896390ac [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
Just470b5052000-01-16 20:37:11 +000019def pointsInRect(array, rect):
20 """Find out which points or array are inside rect.
21 Returns an array with a boolean for each point.
22 """
23 if len(array) < 1:
24 return []
25 lefttop = rect[:2]
26 rightbottom = rect[2:]
27 condition = Numeric.logical_and(
28 Numeric.greater(array, lefttop),
29 Numeric.less(array, rightbottom))
30 return Numeric.logical_and.reduce(condition, -1)
31
Justdeb3b632000-01-26 19:32:45 +000032def vectorLength(vector):
33 return Numeric.sqrt(vector[0]**2 + vector[1]**2)
34
35def asInt16(array):
36 "Round and cast to 16 bit integer."
37 return Numeric.floor(array + 0.5).astype(Numeric.Int16)
38
Just470b5052000-01-16 20:37:11 +000039
40def normRect((l, t, r, b)):
41 """XXX doc"""
42 return min(l, r), min(t, b), max(l, r), max(t, b)
43
44def scaleRect((l, t, r, b), x, y):
45 return l * x, t * y, r * x, b * y
46
47def offsetRect((l, t, r, b), dx, dy):
48 return l+dx, t+dy, r+dx, b+dy
Justbe7163c2000-01-18 22:29:39 +000049
50def insetRect((l, t, r, b), dx, dy):
51 return l+dx, t+dy, r-dx, b-dy
52
53def sectRect((l1, t1, r1, b1), (l2, t2, r2, b2)):
54 l, t, r, b = max(l1, l2), max(t1, t2), min(r1, r2), min(b1, b2)
55 if l >= r or t >= b:
56 return 0, (0, 0, 0, 0)
57 return 1, (l, t, r, b)
58
Just02a739a2000-01-23 19:10:27 +000059def unionRect((l1, t1, r1, b1), (l2, t2, r2, b2)):
60 l, t, r, b = min(l1, l2), min(t1, t2), max(r1, r2), max(b1, b2)
61 return (l, t, r, b)
62
63def rectCenter((l, t, r, b)):
64 return (l+r)/2, (t+b)/2
65
Justb3026ba2000-01-22 00:26:07 +000066def intRect(rect):
67 rect = Numeric.array(rect)
68 l, t = Numeric.floor(rect[:2])
69 r, b = Numeric.ceil(rect[2:])
70 return tuple(Numeric.array((l, t, r, b)).astype(Numeric.Int))
Justbe7163c2000-01-18 22:29:39 +000071