efficient way of performing integral on an image

╄→гoц情女王★ 提交于 2019-12-06 06:20:40

You can use cumsum to speedup trap. Calculating the cummulative sum (1-dimensional integral images proposed by @Benjamin)

>>> import numpy as np
>>> csdata = np.cumsum(data, axis=1)

Integrate with a discrete length

>>> npoints = 6
>>> result = np.zeros_like(data)
>>> result[:-npoints, :]  = csdata[npoints:, :] - csdata[:-npoints, :]

The result is a vectorization of cumdata[i+npoints, j] - cumdata[i, j] for every i, j in the image. It will fill with zeros last npoints rows. You can reflect the boundary with np.pad if you want to prevent this.

For non-discrete intervals, you can work with interpolations:

>>> from scipy.interpolate import interp2d
>>> C = 0.5   # to interpolate every npoints+C pixels
>>> y, x = np.mgrid[:data.shape[0], :data.shape[1]]
>>> ynew, xnew = np.mgrid[C:data.shape[0]+C, :data.shape[1]]
>>> f = interp2d(x, y, csdata)
>>> csnew = f(xnew, ynew)

The above shifts a regular grid C pixels in y direction, and interpolates the cummulative data csdata at those points (in practice, it vectorices interpolation for every pixel).

Then the integral of npoints+C length can be obtained as

>>> npoints = 6
>>> result = np.zeros_like(data)
>>> result[:-npoints, :]  = csnew[npoints:, :] - csdata[:-npoints, :]

Note that the upper bound is now csnew (a shift of 6 actually gets the 6.5 element), making it integrate every 6.5 points in practice.

You can then find the maximum point as

>>> idx = np.argmax(result.ravel()) # ravel to get the 1D maximum point
>>> maxy, maxx = np.unravel_index(idx, data.shape) # get 2D coordinates of idx
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!