Skip to main content
 首页 » 编程设计

python之为图像着色 Pygame

2025年04月02日15qlqwjy

我想创建一个类似于几何冲刺的游戏。我有立方体的所有图像,但它们都是灰色和白色的 - 这是为了让用户选择颜色。

我有两个变量,colour_1 和 colour_2。 colour_1 应为灰色,colour_2 应为白色。如果我说变量是什么,我将如何修改图像以获得正确的颜色?

图像上的颜色不尽相同,边缘融合,使图像更平滑。这可能会导致并发症。

请您参考如下方法:

我在 Fishstick 提议的网站上找到了这个

这是基于它的工作代码

img_surface = pygame.image.load("image.gif")              # Load image on a surface 
img_array = pygame.surfarray.array3d(img_surface)         # Convert it into an 3D array 
colored_img = numpy.array(img_array)                      # Array thing 
colored_img[:, :, 0] = 255    # <-- Red 
colored_img[:, :, 1] = 128    # <-- Green 
colored_img[:, :, 2] = 0      # <-- Blue 
img_surface = pygame.surfarray.make_surface(colored_img)  # Convert it back to a surface 
screen.blit(img_surface, (0, 0))                          # Draw it on the screen 

这会改变每个像素的颜色值。如果将红色设置为 255,则所有像素的红色都会增加 255。但是,如果将所有颜色设置为 255,则图像将为白色。

请注意,您需要安装 NumPy 才能使用它,您可以这样做:

pip install numpy 

您也可以尝试将最后两行替换为

pygame.surfarray.blit_array(screen, colored_img) 

这应该更快,但它对我不起作用,所以我将数组转换为表面,然后将其 blit 显示在屏幕上。

如果这不能回答您的问题,也许这些会: