[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] about array_alpha?



flyaflya wrote:

> "pygame.surfarray.array_alpha" can be use to get a surface alpha
> array, but how to set this alpha array return to the surface?
> I know "make_surface" can make a surface form rgb array, but I cant
> find how to use alpha array?

The following works for me. Getting surfarray to do what I wanted was
tricky.
-Jasper


from pygame.surfarray import array3d, array_alpha, make_surface,
pixels_alpha

def diamondBlur( surface ):
matrix = [[0, 0, 1, 0, 0],
[0, 1, 1, 1, 0],
[1, 1, 1, 1, 1],
[0, 1, 1, 1, 0],
[0, 0, 1, 0, 0]]
return alphaBlur( surface, matrix )


# Convolution code

def blur( surface, matrix ):
'''Convolution blur, ignoring alpha values'''
blurRGB = convolveSurfArray( array3d( surface ), matrix )
return make_surface( blurRGB.astype( N.Int8 ) )

def alphaBlur( surface, matrix ):
'''Convolution blur, handling alpha values'''
resultSurface = blur( surface, matrix ).convert_alpha()
alphaPixels = pixels_alpha( resultSurface )
blurredAlpha = convolveSurfArray( array_alpha( surface ), matrix )
alphaPixels[:] = blurredAlpha.astype( 'b' )
return resultSurface

def convolveSurfArray( array, matrix ):
'''Standard convolution by matrix. The edge weights are off and over
darken.'''
size = len( matrix[0] )
center = size / 2
assert size % 2 != 0

result = N.zeros( array.shape )
w, h = array.shape[:2]
for x in range(size):
for y in range(size):
weight = matrix[y][x]
if weight:
xOff, yOff = center - x, center - y
result[ max( xOff,0):min(w+xOff,w), max( yOff,0):min(h+yOff,h) ] += \
array[ max(-xOff,0):min(w-xOff,w), max(-yOff,0):min(h-yOff,h) ] * weight

result /= N.sum( N.sum( matrix ) )
return result