gpt4 book ai didi

python - 是否有更快的方法来检查 pygame 表面的列表 [i] 是否具有 alpha 0

转载 作者:行者123 更新时间:2023-12-04 07:27:22 28 4
gpt4 key购买 nike

我正在 pygame 中制作一个 Sprite 表类,并将我从图像中获得的每一帧都放在一个列表中。
但是,有时 Sprite 表有一些空帧。
例如我制作了一个带有 2 个 Sprite 动画的图像,所以我将每一个都排成一行,但是第一个比第二个大 1 帧,所以第二个有一个空帧。
我做了这个代码来检查框架是否为空。我使用了一个反向循环,因为大多数空帧都在列表的末尾,所以我可以在任何帧不为空时中断,这样就不会花费太多时间。

for i in reversed(range(len(frames))):
frame_alpha_as_array = surfarray.array_alpha(frames[i])

if np.sum(frame_alpha_as_array) == 0:
del(frames[i])
else:
break
但是,我想知道是否有更快的方法来做到这一点,这样它就不会占用太多的 cpu/gpu/ram (IDK)。
我对编程比较陌生,所以如果我做错了什么,不要太苛刻。

最佳答案

使用 pygame.surfarray.pixels_alpha() 而不是 pygame.surfarray.array_alpha() .虽然 pygame.surfarray.array_alpha()将像素 alpha 复制到二维数组,pygame.surfarray.pixels_alpha()直接指的是像素阿尔法。
参见 pygame.surfarray.pixels_alpha() 的文档

Create a new 2D array that directly references the alpha values (degree of transparency) in a Surface. Any changes to the array will affect the pixels in the Surface. This is a fast operation since no data is copied.
The Surface this array references will remain locked for the lifetime of the array.


使用 numpy.any 测试是否有任何数组元素大于 0:
if not np.any(surfarray.pixels_alpha(frames[i]) != 0):

关于python - 是否有更快的方法来检查 pygame 表面的列表 [i] 是否具有 alpha 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68138764/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com