Pygame - Recolor pixes of a certain color to another using SurfArray (Array slicing issue)

依然范特西╮ 提交于 2019-12-24 02:42:39

问题


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.



来源:https://stackoverflow.com/questions/29479915/pygame-recolor-pixes-of-a-certain-color-to-another-using-surfarray-array-slic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!