【问题标题】:Pygame, copying the screen into an arrayPygame,将屏幕复制到数组中
【发布时间】:2018-04-04 13:54:04
【问题描述】:

如何在pygame中将屏幕内容放入一个数组中?我已经从文档中尝试过:

self.screen.lock()
tmp_frame = pygame.surfarray.array3d(self.screen)
self.screen.unlock()

我尝试了各种方法,比如先使用pixelcopy来获取表面的副本,但我总是遇到分段错误。

致命的 Python 错误:(pygame parachute) Segmentation Fault Aborted (核心转储)

是因为我想直接从屏幕复制吗? 这是屏幕包含的内容:

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 显示内容复制到数组中?

【问题讨论】:

    标签: pygame


    【解决方案1】:

    致任何可能遇到类似情况的人: 我找不到直接的解决方案,所有访问硬件加速表面的方法都会导致分段错误。 (array3d、array2d、访问参考数组 pixel3d 等)。

    但是,我想出了一个解决方法。看来您可以使用

    保存图像
    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)
    

    这应该会给你一个屏幕内容的 numpy 数组。

    【讨论】:

    • 这适用于 OpenGL!但我将图像旋转了 90 度。这是注定要发生的吗?
    【解决方案2】:
    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多