[Image-SIG] Two PIL based Hill Shading Implementations, using Python & Python/C.

Will Henney whenney at gmail.com
Tue Feb 6 20:09:59 CET 2007


Hi John

How about this for a numpy implementation? Runs nearly as fast as the C version
on my mac (1.58 vs 1.16 secs). 

def hillShadeNumPy(filenameIn, filenameOut, scale=1.0, azdeg=315.0, altdeg=45.0):
    ''' Create a hill shade version of the given image using numpy '''
    from numpy import sin, cos, hypot, arctan, arctan2, pi

    dScale = (1.0 * scale)
    # convert alt, az to radians
    az = azdeg*pi/180.0
    alt = altdeg*pi/180.0
    (img, data, imgS, dataS) = initialiseImages(filenameIn)

    # get the image data as a numpy array of floats
    adata = N.asarray(img).astype('float')
    # gradient in x and y directions
    dx, dy = N.gradient(adata/dScale)
    slope = 0.5*pi - arctan(hypot(dx, dy))
    aspect = arctan2(dx, dy)
    c = sin(alt)*sin(slope) + cos(alt)*cos(slope)*cos(-az - aspect - 0.5*pi)
    c = N.where(c > 0.0, c*255.0, 0.0)
    imgS = Image.fromarray(c.astype('uint8'))
    imgS.save(filenameOut,'PNG')

Cheers

Will







More information about the Image-SIG mailing list