onj*_*jre 8 python pygame pygame-surface
我有一段可以使用的代码
my_surface = pygame.image.load('some_image.png')
Run Code Online (Sandbox Code Playgroud)
这将返回一个pygame表面.我想在其他地方使用相同的代码,而是传入一个numpy数组.(实际上,我将有一个if语句来确定我们是否有一个数组或一个图像的路径.在任何一种情况下,该函数必须返回相同类型的对象,一个pygame表面.它已经使用上面的工作了如果脚本的使用方式不同,我现在必须添加第二种生成相同对象的方法.)我尝试过使用
my_surface = pygame.pixelcopy.make_surface(my_array)
Run Code Online (Sandbox Code Playgroud)
但问题是这个函数需要一个INTEGER数组.我的数组是float32.我可以通过传递数组来强制它通过
(my_array*10000).astype(int)
Run Code Online (Sandbox Code Playgroud)
但是当我稍后显示它看起来像垃圾(想象我的惊喜).所以我的问题是,我们如何在一系列花车中优雅地创建一个pygame表面?
将数据范围转换为[0-255]范围,数据大小必须为mxn或mxnx3
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()
Run Code Online (Sandbox Code Playgroud)
如果你想要灰度:
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()
Run Code Online (Sandbox Code Playgroud)