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

[pygame] surfarray.pixels3d(). I'm stumped.



I'm trying to blur both RGB and alpha using surfarray.  I can get it to work
with surfarray.array3d() and .array_alpha(), but it's very slow as I end up
using Surface.set_at() to combine the results of both methods together.

So I'm trying something similar.  First I setup references to the surface
via surfarray.pixels3d() and pixels_alpha(), create the result surfarrays by
convolution as before, and then try to set the results into the indirect
access pixel arrays.  The code at the end of the post gets the following
error at the end of blur():

exceptions.TypeError: Array can not be safely cast to required type

Is there some other way to do this that I'm missing?

-Jasper


# Convolution code

import Numeric as N
from pygame.surfarray import array3d,  array_alpha
from pygame.surfarray import pixels3d, pixels_alpha

def plusBlur( surface ):
    matrix  = [[0, 1, 0],
               [1, 1, 1],
               [0, 1, 0]]
    divisor = 5
    return blur( surface, matrix, divisor )

def blur( surface, matrix, divisor ):
    '''Convolution blur, handling alpha values'''
    blurRGB         = convolve( array3d(     surface ), matrix, divisor )
    blurAlpha       = convolve( array_alpha( surface ), matrix, divisor )

    blurRGBRef      = pixels3d(     surface )
    blurAlphaRef    = pixels_alpha( surface )

    blurRGBRef[:]   = blurRGB[:]
    blurAlphaRef[:] = blurAlpha[:]

def convolve( array, matrix, divisor ):
    '''Standard convolution by matrix'''
    size   = len( matrix[0] )
    center = size / 2
    assert size % 2 != 0

    array  = array.astype( N.Int32 )
    result = N.zeros( array.shape )
    for x in range(size):
        for y in range(size):
            scalar = matrix[x][y]
            if scalar:
                xOff, yOff = center - x, center - y

                # This avoids the unusefull slice :0, using instead :
                if xOff and yOff:  factor = array[:-xOff,:-yOff]
                elif xOff:         factor = array[:-xOff,:     ]
                elif yOff:         factor = array[:     ,:-yOff]
                else:              factor = array[:     ,:     ]

                result[xOff:,yOff:] += factor * scalar
    result /= divisor
    return result.astype( N.Int8 )