Merge pull request #493 from ChrisBeaumont/vector_integral

vectorized transform.integral.integrate
This commit is contained in:
Johannes Schönberger
2013-04-08 13:10:08 -07:00
2 changed files with 37 additions and 13 deletions
+22 -13
View File
@@ -1,3 +1,6 @@
import numpy as np
def integral_image(x):
"""Integral image / summed area table.
@@ -34,28 +37,34 @@ def integrate(ii, r0, c0, r1, c1):
----------
ii : ndarray
Integral image.
r0, c0 : int
Top-left corner of block to be summed.
r1, c1 : int
Bottom-right corner of block to be summed.
r0, c0 : int or ndarray
Top-left corner(s) of block to be summed.
r1, c1 : int or ndarray
Bottom-right corner(s) of block to be summed.
Returns
-------
S : int
Integral (sum) over the given window.
S : scalar or ndarray
Integral (sum) over the given window(s).
"""
S = 0
if np.isscalar(r0):
r0, c0, r1, c1 = [np.asarray([x]) for x in (r0, c0, r1, c1)]
S = np.zeros(r0.shape, ii.dtype)
S += ii[r1, c1]
if (r0 - 1 >= 0) and (c0 - 1 >= 0):
S += ii[r0 - 1, c0 - 1]
good = (r0 >= 1) & (c0 >= 1)
S[good] += ii[r0[good] - 1, c0[good] - 1]
if (r0 - 1 >= 0):
S -= ii[r0 - 1, c1]
good = r0 >= 1
S[good] -= ii[r0[good] - 1, c1[good]]
if (c0 - 1 >= 0):
S -= ii[r1, c0 - 1]
good = c0 >= 1
S[good] -= ii[r1[good], c0[good] - 1]
if S.size == 1:
return np.asscalar(S)
return S
+15
View File
@@ -26,6 +26,21 @@ def test_single():
assert_equal(x[0, 0], integrate(s, 0, 0, 0, 0))
assert_equal(x[10, 10], integrate(s, 10, 10, 10, 10))
def test_vectorized_integrate():
r0 = np.array([12, 0, 0, 10, 0, 10, 30])
c0 = np.array([10, 0, 10, 0, 0, 10, 31])
r1 = np.array([23, 19, 19, 19, 0, 10, 49])
c1 = np.array([19, 19, 19, 19, 0, 10, 49])
expected = np.array([x[12:24, 10:20].sum(),
x[:20, :20].sum(),
x[:20, 10:20].sum(),
x[10:20, :20].sum(),
x[0,0],
x[10, 10],
x[30:, 31:].sum()])
assert_equal(expected, integrate(s, r0, c0, r1, c1))
if __name__ == '__main__':
run_module_suite()