pygame - 使用 pygame 以编程方式创建和填充 8 位表面的最快方法

标签 pygame pygame-surface

我需要以编程方式从列表数组创建一个 8 位表面。这是我的一个限制。到目前为止,我已经使用了这个解决方案:

width = int(4)
height = int(4)
image_data_raw = ['\xf1', '\xf1', '\xf1', '\xf1',
              '\xf1', '\x00', '\x00', '\xf1',
              '\xf1', '\x00', '\x00', '\xf1',
              '\xf1', '\xf1', '\xf1', '\xf1']

def make_surface_from_raw_data():
    global image_data_raw
    global width
    global height

image_data_raw_bytes = [ord(i) for i in image_data_raw]

test_surface = pygame.Surface((width, height))
pxarray = pygame.PixelArray(test_surface)

i = int(0)
for y in range(height):
    for x in range(width):
        pxarray[x, y] = pygame.Color(image_data_raw_bytes[i],
                                     image_data_raw_bytes[i],
                                     image_data_raw_bytes[i])
        i += 1

new_surface = pxarray[:, :].make_surface()
image_data_2d_surface = new_surface
return image_data_2d_surface

但是,我对此不满意,因为它太慢了。

我的“image_raw_data”将比 4x4 大得多,并且从串行源流式传输。而且它们始终是 8 位灰度。因此,无需从8位转换为rbga。

我想知道是否有更快的方法来完成这项任务。在我的循环中,有几次从 char 到 8 位 int,然后再到 rgba 的转换。

非常感谢。

最佳答案

如果您安装了 NumPy,使用类似的东西会明显更快:

def make_surface_from_raw_data():
    global image_data_raw
    global width
    global height

    # we create a numpy array from image_data_raw
    # and do some bit shifting so that the single value is used for each color channel
    # then we have to reshape that array into the right size
    data = np.fromiter((x | x << 8 | x << 16 for x in (ord(i) for i in image_data_raw)), dtype=np.uint32).reshape(width, -width)

    # now let's create a Surface in the right dimension 
    # that's faster than letting pygame figure out the size from the array (with the make_surface function)
    surface = pygame.Surface((width, height))

    # blit_array is the fastet way to get the value of the array into the Surface
    # (faster than creating an array from the Surface and updating it)
    pygame.surfarray.blit_array(surface, data)

    return surface  

关于pygame - 使用 pygame 以编程方式创建和填充 8 位表面的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52085373/

相关文章:

python - 如何在 pygame 中为我的角色添加加速?

python - Pygame 中不显示 Sprite

python-3.x - Pygame 水物理无法按预期工作

python - 如何制作在同一个 pygame.sprite.Group 中相互击中的两颗子弹?

python - 有没有办法找到在 "pygame"上按下的任何数字?以及如何显示它?

python - Pygame 运行缓慢

python - 如何将图像blit到pygame中与矩形大小相同的表面

python - Pygame,从二维 numpy 数组创建灰度

python - Pygame 的矩形不移动?

python - 在 Pygame 中显示 FPS