Numpy and Python: How to create a bump map efficiently starting from image and heightmap?

Viewed 398

I am working with Python and Numpy.

I have an image like this one: https://i.stack.imgur.com/aMIa5.png

I have its heightmap: https://i.stack.imgur.com/WbYHo.png

I want to combine them (refer to this https://en.wikipedia.org/wiki/Bump_mapping) to create a bump map like this one: https://i.stack.imgur.com/75om0.jpg

I need to do it with as little ram as possible. The formula I am using is:

newColor = oldColor+(tint-oldColor)*abs(difference)*k

Where difference is the difference in value between 2 adiajent points in the heightmap. Where tint is zero if difference is negative and tint is 255 when difference is positive. K is 0.5 Basically I am making a pixel lighter if the slope faces north, and darker if the slope faces south.

I am allocating too many ndarrays, so I am using too much ram. Is there a way of doing it with fewer arrays?

Here is my code.

Input:

  • image is a Numpy ndarray(shape=(8192,3192,3),dtype=np.uint8)
  • heightmap is a Numpy ndarray(shape=(8192,3192),dtype=np.float32) with values that range from 0 to 255

My code looks like this:

#Store the difference in height between two adjacent points
deltas = np.roll(heightmap,1,0)
np.subtract(heightmap,deltas,out=deltas)
difference = np.repeat(deltas[:,:,np.newaxis],3,axis=2)
del deltas

#newColor = oldColor+(shade-oldColor)*difference*k
shades = np.where(difference>0,np.int16(0),np.int16(255))
np.absolute(difference,out=difference)
np.multiply(difference,K,out=difference)
np.subtract(shades,image,out=shades)
np.multiply(difference,shades,out=difference)
del shades
np.add(image,difference,out=image,casting='unsafe')
del difference

#Save image
preview = I.fromarray(np.flip(image,0))
preview.save('image.png')

I am allocating delta, difference, shades, heightmap and image. I am using too many support arrays and too much memory. Is there a way of doing this without allocating so much ram?

0 Answers
Related