On Fri, Feb 27, 2009 at 08:04:30PM -0800, Lenard Lindstrom wrote:
Marius Gedminas wrote:
Since I'm really clueless about
Numeric/numarray/numpy, please tell me if this code has any obvious
shortcomings:
# initialization, done once
import pygame
import numpy
image = pygame.image.load('title.png') # has an alpha channel
mask = pygame.surfarray.array_alpha(image)
# this is done once every frame
array = pygame.surfarray.pixels_alpha(image)
alpha = 42.5 # a float varying between 1 and 255
array[...] = (mask * alpha / 255).astype('b')
Well, alpha and 255 are both scalars, so (mask * (alpha / 255)) saves
one intermediate array. Also the preferred NumPy convention is to use
dtypes (data-types) rather than type characters: .astype(numpy.uint8).
I was using Numeric.UnsignedInt8 before, and couldn't find the NumPy
version of that in a hurry. dir(array) showed me a typecode() method
which returned things like 'b', and so I tried those.
But arithmetic operations have ufunc equivalents which take an optional
output array. This means the astype(), along with its intermediate
array, can be removed. It probably also means the intermediate array
float array goes away as well. So it is likely this alternative uses no
intermediate arrays.
## array = pygame.surfarray.pixels_alpha(image)
alpha = 42.5
## array[...] = (mask * alpha / 255).astype('b')
numpy.multiply(mask, alpha / 255, pygame.surfarray.pixels_alpha(image))
Unfortunately this gives me a TypeError: return arrays must be of ArrayType