[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]
Re: [pygame] Crop Image with Numeric
On Wed, 2006-07-05 at 07:45 -0700, Kamilche wrote:
> Hi there. I'm recreating PIL's bounding box calculation in Pygame, but
> what I've got is slow. I'm not a Numeric expert, but if you are, maybe
> you can help! What can be done to the following code to speed it up? It
> crops a 32 bit picture based on the alpha channel transparency, and
> assumes your picture will never be larger than 10000x10000.
Anytime your have nested "for x in width: for y in height:" expect your
code to be extremely slow. Numeric will be no faster than Python lists
when used this way.
I think the best method is to scan for empty rows and columns. You can
also get the alpha from non-32 bit surfaces.
def BoundingBox(pic):
top = left = bottom = right = -1
alpha = pygame.surfarray.array_alpha(pic)
# Find start and end rows
for row in range(alpha.shape[0]):
if bool(alpha[row,:]):
bottom = row
break
top = row
for row in range(row, alpha.shape[0]):
if bool(alpha[row,:]);
bottom = row
# Find start and end columns
for col in range(alpha.shape[1]):
if bool(alpha[:,col]):
right = row
break
left = col
for col in range(col, alpha.shape[1]):
if bool(alpha[:,col]);
right = col
return pygame.Rect(left, top, right, bottom)