如何将屏幕内容放入pygame中的数组中?我从文档中试过这个:
self.screen.lock()
tmp_frame = pygame.surfarray.array3d(self.screen)
self.screen.unlock()
我尝试过各种各样的事情,例如先使用像素镜来获取曲面的副本,但我总是遇到分段错误。
致命的Python错误:( pygame降落伞)分段故障中止 (核心倾销)
是因为我想直接从屏幕上复制吗? 这是屏幕包含的内容:
self.screen = pygl2d.display.set_mode((self.SCREEN_WIDTH, self.SCREEN_HEIGHT), pygame.DOUBLEBUF, depth=24)
这是set_mode的定义:
def set_mode(resolution=(0,0), flags=0, depth=0):
flags |= pygame.OPENGL
screen = pygame.display.set_mode(resolution, flags, depth)
init_gl()
return screen
编辑后续:
我还尝试先用
将屏幕表面复制到另一个表面tmp_surface= self.screen.copy()
但是我得到了
pygame.error:无法复制opengl显示
所以,我想问题是你如何将这个opengl显示内容复制到数组中?
答案 0 :(得分:1)
import pygame
import numpy as np
import time
from pandas import *
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()
# Convert the window in black color(2D) into a matrix
window_pixel_matrix = pygame.surfarray.array2d(display)
print(window_pixel_matrix)
time.sleep(10)
pygame.quit()
评论: " pygame.surfarray.array2d()"我猜是你正在寻找的东西。 当然,你可以使用" pygame.surfarray.array3d()"功能也很好。
您可以参考官方网站:" https://www.pygame.org/docs/ref/surfarray.html#pygame.surfarray.array2d"
答案 1 :(得分:0)
对于可能会遇到类似情况的人: 我无法找到直接的解决方案,所有访问硬件加速表面的方法都会导致分段错误。 (array3d,array2d,访问引用数组pixels3d等)。
但是,我能够找到解决方法。您似乎可以使用
保存图像pygame.image.save(self.screen, 'output.png')
同样,你可以做到
string_image = pygame.image.tostring(self.screen, 'RGB')
temp_surf = pygame.image.fromstring(string_image,(self.SCREEN_WIDTH, self.SCREEN_HEIGHT),'RGB' )
tmp_arr = pygame.surfarray.array3d(temp_surf)
这应该可以为您提供一小部分屏幕内容。