0

I'm trying to reproduce an algorithm over image, but failed to achieve the performance of PIL on Python.

For simplity, we take interpolation as an example.Supposed we have a matrix Im of luminance. For any point (x,y), we can compute the interpolation value by g(x,y)=f(floor(x),floor(y))+f(floor(x)+1,floor(y))+f(floor(x),floor(y)+1)+f(floor(x)+1,floor(y)+1) /4

Here is part of code. It takes tens of seconds to resize an image, that's inefficient. Also, it's not a element-wise mapping function. It involves with the whole matrix, or more precisely, the neighbour points of each point.

im = np.matrix(...) #A 512*512 image
axis = [x/(2047/511.) for x in xrange(2048)]
axis = [(x,y) for x in axis for y in axis] #resize to 2048*2048
im_temp = []
for (x, y) in axis:
    (l, k) = np.floor((x, y)).astype(int)
    a, b = x-l, y-k
    temp = (1-a)*(1-b)*im[l+1,k+1] + a*(1-b)*im[l+2,k+1] + (1-a)*b*im[l+1,k+2] + a*b*im[l+2,k+2]
    im_temp.append(temp)
np.asmatrix(im_temp).reshape((2048,2048)).astype(int)

How can we implement this algorithm in a more efficient way instead of 2 for loop?

  • Share the implementation of `f`? – Divakar Mar 11 '17 at 16:41
  • Possible duplicate of [Most efficient way to map function over numpy array](http://stackoverflow.com/questions/35215161/most-efficient-way-to-map-function-over-numpy-array) – spicypumpkin Mar 11 '17 at 16:48
  • 1
    Be careful with duplicates; this is a 2d problem. Flat iteration solutions require reshaping.. – hpaulj Mar 11 '17 at 17:53
  • 1
    Are `x,y` indices of a 2d array, or coordinates? Why `floor`? The `+1` suggests you are looking at neighboring points. Are you using any Python image packages (beyond numpy)? Overall this question is underspecified and unclear. – hpaulj Mar 11 '17 at 17:57
  • http://stackoverflow.com/questions/42740021/numpy-apply-function-to-two-numpy-arrays-and-return-two-numpy-arrays is another recent 'mapping' question that might help. – hpaulj Mar 11 '17 at 20:35
  • The slowness comes from having to evaluate `temp` 2048*2048 times in Python code. The way to speed that up is to perform the calculations in compiled code, and not iterate or 'map' at all in Python. `PIL` interfaces with a compiled library, doesn't it? – hpaulj Mar 12 '17 at 02:07
  • @hpaulj, Thanks for your answer. I'm just asking, if we see `temp` as a function w.r.t. a matrix, can we have some efficient way to vectorized the process or speed the performance up. – Ruicheng Feng Mar 12 '17 at 02:33

0 Answers0