gpt4 book ai didi

python - 如何从 float32 的 numpy 数组创建 pygame 表面?

转载 作者:太空狗 更新时间:2023-10-29 20:58:03 25 4
gpt4 key购买 nike

我有一段代码可以使用

my_surface = pygame.image.load('some_image.png')

这将返回一个 pygame 表面。我想在其他地方使用相同的代码,而是传入一个 numpy 数组。 (实际上,我将有一个 if 语句来确定我们是否有一个数组或一个图像的路径。在任何一种情况下,该函数都必须返回相同类型的对象,一个 pygame 表面。它已经可以使用上面的代码。如果脚本的使用方式不同,现在我必须添加第二种生成相同对象的方法。)我已经尝试使用

my_surface = pygame.pixelcopy.make_surface(my_array)

但问题是这个函数需要一个 INTEGER 数组。我的数组是 float32。我可以通过像这样传递数组来强制它通过

(my_array*10000).astype(int)

但是当我稍后显示它时,它看起来像垃圾(想象一下我的惊讶)。所以我的问题是,我们如何从 numpy float 组中优雅地创建一个 pygame 表面?

最佳答案

将数据范围转换为范围[0-255],数据大小必须为M x NM x N x 3

pygame.init()
display = pygame.display.set_mode((350, 350))
x = np.arange(0, 300)
y = np.arange(0, 300)
X, Y = np.meshgrid(x, y)
Z = X + Y
Z = 255*Z/Z.max()
surf = pygame.surfarray.make_surface(Z)

running = True

while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
display.blit(surf, (0, 0))
pygame.display.update()
pygame.quit()

enter image description here

如果你想要灰度:

import pygame
import numpy as np


def gray(im):
im = 255 * (im / im.max())
w, h = im.shape
ret = np.empty((w, h, 3), dtype=np.uint8)
ret[:, :, 2] = ret[:, :, 1] = ret[:, :, 0] = im
return ret

pygame.init()
display = pygame.display.set_mode((350, 350))
x = np.arange(0, 300)
y = np.arange(0, 300)
X, Y = np.meshgrid(x, y)
Z = X + Y
Z = 255 * Z / Z.max()
Z = gray(Z)
surf = pygame.surfarray.make_surface(Z)

running = True

while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
display.blit(surf, (0, 0))
pygame.display.update()
pygame.quit()

enter image description here

关于python - 如何从 float32 的 numpy 数组创建 pygame 表面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41168396/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com