Pygame - Recolor pixes of a certain color to anoth

2019-07-22 20:45发布

问题:

I'm trying to make a palette swap functionality for a game, and I'm trying to find a way to change the color of pixels of a certain color to another. I've been able to make all of the pixels the same color with this function I found in a tutorial:

def color_surface(self,surface, red, green, blue):
    arr = pygame.surfarray.pixels3d(surface)
    arr[:,:,0] = red
    arr[:,:,1] = green
    arr[:,:,2] = blue

As far as I can tell, the first two indices are the location of the pixel, and the third is the color channel, right? Thinking that, I came up with this function here:

def recolor(self,fromColor,toColor):
    arr = pygame.surfarray.pixels3d(self.image)
    for color in arr[:,:,0:]:
        if color == fromColor:
            color = toColor

Now, I'm absolutely certain I'm messing up the array slicing. What I'm trying to do is to get a list of all of the pixels as a length 3 array of colors, and if that array matches fromColor, it switches to toColor. It's not working, though, and its wicked slow in not working. Is there an easier way?

Or am I just misunderstanding the surfArray entirely and the indexes are not what I'm thinking they are?

回答1:

Maybe you're looking for something less general, but there is a replace method in the PixelArray module used for replacing one color with another.

arr = PixelArray(surface)
arr.replace(fromColor, toColor)
del arr

That would change one color on a surface to another. The del statement is there because otherwise the surface remains locked for as long as the PixelArray object exists.

As for the array slicing, a section in the NumPy documentation explains the syntax.