我的代码允许用户在pygame屏幕的一部分上绘制。我希望能够提取屏幕这一部分的所有RGB像素值,并将其转换为3d阵列,如下所示:
top_left = [50, 50]
bottom_right = [100, 100]
pixel_data = SomeFunctionToGetPixelData(screen, top_left, bottom_right)
# get RGB value for pixel that was at position (53, 51) on the screen
print(pixel_data[3][1])
> [255, 255, 255]
最好的方法是什么?
从屏幕的部分创建子表面。次表面与其新父对象共享其像素(参见pygame.Surface.subsurface
(:
w = bottom_right[0] - top_left[0]
h = bottom_right[1] - top_left[1]
area = pygame.Rect(top_left[0], top_left[1], w, h)
sub_surface = screen.subsurface(area)
使用pygame.surfarray.array3d()
将表面的像素复制到3D阵列中:
pixel_data = pygame.surfarray.array3d(sub_surface)
最小函数:
def get_pixel_data(surf, top_left, bottom_right):
w = bottom_right[0] - top_left[0]
h = bottom_right[1] - top_left[1]
sub_surface = surf.subsurface(pygame.Rect(*top_left, w, h))
return pygame.surfarray.array3d(sub_surface)