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

Re: [pygame] Crop Image with Numeric



Peter Shinners wrote:

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.


Ooh, mumbo jumbo! This method is as instant as I was hoping for, thanks Pete! Tho I had to change your semicolons to colons, and swap your indices, the results were faster than the other method.


Here's your revised method:

#----------------------------------

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

    # Since the indices were off, I just rearranged the
    # return values to accommodate that.
    return pygame.Rect(top, left, bottom-top, right-left)