python - 在pygame中以数组的形式获取屏幕某一部分的RGB像素数据
问题描述
我的代码允许用户在 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()
将像素从Surface复制到 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)
推荐阅读
- node.js - 共享库中间件部分中的通用猫鼬模型
- python - 通过删除布局框架从 QGridLayout 中删除小部件
- javascript - 如何在 Vuejs 中使用 axios 获取下载文件(.xlsx)?
- rest - 如何在express中使用rest api
- github - 按文件名及其文件内容搜索 Github 存储库
- plsql - 从通过 oracle 过程调用的 REST API 的响应中提取特定组件
- ios - 将标签的高度放在堆栈视图中的 UIView 内时表现异常
- node.js - 为什么postgres查询总是为主键返回null?
- python - 训练具有多个公共输出的 tensorflow 模型
- ruby-on-rails - Elatic Beanstalk Worker 和 Elastic Beanstal Rails API 如何协同工作?