python - 需要帮助来理解 surfarray.array2d - 它似乎无法正确保存颜色

标签 python pygame

我做了一个测试,将 Surface 转换为 array2d,然后将其转换回来,如下所示:

fg = pygame.surfarray.make_surface(pygame.surfarray.array2d(fg))

这是完整的代码(如果您愿意,可以复制并粘贴到 Pygame 中进行快速测试):

pygame.init()


SURFACE_MAIN = pygame.display.set_mode((300, 300))
fg = pygame.Surface((300, 300))
fg.fill((70, 53, 52))

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_s:
                fg = pygame.surfarray.make_surface(pygame.surfarray.array2d(fg))

    SURFACE_MAIN.blit(pygame.Surface.copy(fg), (0, 0))
    pygame.display.update()

当你按下s键时,原来的棕色变成绿色。

旧颜色:(70, 53, 52, 255)
新颜色:(85, 182, 0, 255)

这个问题的解决方案原来是使用 array3d,但我不明白为什么会这样。有人可以向我解释吗?非常感谢!

引用:https://www.pygame.org/docs/ref/surfarray.html#pygame.surfarray.array2d

最佳答案

pygame.surfarray.make_surface 函数会将 2D 数组转换为位深度为 8 的表面,将 3D 数组转换为位深度为 32 的表面。这很重要,因为如何pygame 处理位深度。

位深度

位深度是表示一种颜色的信息量。位深度 32 允许我们表示 2^32 = 4,294,967,296 颜色,这与为每个颜色分量(红色、绿色、蓝色、Alpha)分配 8 位相同(一个介于 0 之间的值) -255).

8 位深度允许我们表示 2^8 = 256 颜色。对于每个颜色分量(0-3 之间的值),这将是 2 位。然而,这不是 pygame 处理这种位深度颜色的方式。

pygame是如何处理的

Pygame 不会存储 RGBA 的每个值,而是将像素存储为单个整数,只要位深度大于 8,就可以对其进行解码以获得颜色分量的值。当你有一个较低的位深度 pygame 为表面使用调色板。现在,每个像素值都成为具有 256 种颜色的调色板的索引,而不是编码整数。此调色板可通过方法 surface.get_palette() 获得。并且可以使用 surface.set_palette() 进行设置.

正是这种转换让你的颜色值变得怪异。这是一个用于演示和试验的简短程序(使用控制台,从 32 的位深度和您的颜色开始,输入以逗号和/或空格分隔的值):

import pygame
pygame.init()

screen = pygame.display.set_mode((1, 1))

depth = int(input('\nDepth size: '))
color = [int(x) for x in input('Color: ').replace(',', ' ').split()]

surface = pygame.Surface((1, 1), depth=depth)  # Valid bit depth sizes are 8, 12, 16, 24 or 32
surface.fill(color)
print('\nSurface 1 has bit depth', surface.get_bitsize(), ' | The color is: ', surface.get_at((0, 0)))

surface2 = pygame.surfarray.make_surface(pygame.surfarray.array2d(surface))
print('\nSurface 2 has bit depth', surface2.get_bitsize(), ' | The color is: ', surface2.get_at((0, 0)))
surface2.set_palette([(123, 123, 123) for _ in range(256)])  # Set whole color palette to one color
print('Surface 2 now has the color: ', surface2.get_at((0, 0)))

surface3 = pygame.surfarray.make_surface(pygame.surfarray.array3d(surface))
print('\nSurface 3 has bit depth', surface3.get_bitsize(), ' | The color is: ', surface3.get_at((0, 0)))
print('Surface 3 has no color palette since it has a bit depth greater than 8')

关于python - 需要帮助来理解 surfarray.array2d - 它似乎无法正确保存颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44409674/

相关文章:

python - 剪切一些值为 255 的行和列

python - 与 pygame 中的归一化向量移动不一致?

python - 如何在 Pygame 环境中绘制矩形和圆形

Python:如何为多人游戏序列化对象?

python - 重新启动程序后附加列表时,pickle 数据将被删除

python - del 的使用不好吗?

python - 使用 pygame 中的类创建矩形?

python - 谁能告诉我如何使打印屏幕变蓝?

python - 当且仅当标题字符串中包含 '20' 时,遍历每个数据帧标题并将 int month 更新为 str month

python - 如何在 Python 中控制模拟