【发布时间】:2013-07-06 19:00:33
【问题描述】:
我正在使用 pygame 进行图像编辑(不显示)。 (是的,我知道还有其他选项,例如 PIL/pillow,但是 pygame 应该 可以解决这个问题。)
我想绘制并保存一个图像,其中我根据公式单独设置每个像素的 alpha 值(我正在绘制一个复杂的 RGBA 配置文件)。看来pixels_alpha 是这样做的正确方法。但是当我更改pixels_alpha 时,它会被忽略,图像只是保持透明。这是我的代码...
import pygame as pg
import os
def init_transparent(img_width, img_height):
"""
Create a new surface with width and height, starting with transparent
background. This part works!
"""
os.environ['SDL_VIDEODRIVER'] = 'dummy'
pg.init()
pg.display.init()
# next command enables alpha
# see http://stackoverflow.com/questions/14948711/
pg.display.set_mode((img_width, img_height), 0, 32)
# pg.SRCALPHA is a flag that turns on per-pixel alpha.
return pg.Surface((img_width, img_height), pg.SRCALPHA)
def make_semitransparent_image():
surf = init_transparent(20, 20)
# alphas should be a direct reference to the alpha data in surf
alphas = pg.surfarray.pixels_alpha(surf)
# alphas is a uint8-dtype numpy array. Right now it's all zeros.
for i in range(20):
for j in range(20):
# Since pixels_alpha gave me a uint8 array, I infer that
# alpha=255 means opaque. (Right?)
alphas[i,j] = 200
pg.image.save(surf, '/home/steve/Desktop/test.png')
make_semitransparent_image()
同样,它保存了一张图像,但无论我将alphas 设置为什么值,图像看起来都是完全透明的。我在这里做错了什么? (使用 Python 2.7,pygame 1.9.1release。)(提前致谢!)
【问题讨论】:
-
您使用 pygame 只是为了编辑图像,而不是实际显示吗?如果是,请检查Pillow
-
你在哪里设置你保存的
Surface中像素的RGB值?您似乎只设置了它们的 alpha 组件。 -
猴子:谢谢你的建议。就像你说的,我正在编辑而不是显示,如果 pygame 不起作用,我确实会尝试枕头。 martineau:我没有显示 RGB 调整。这段代码应该制作一个半透明的白色或黑色方块(默认是什么,我忘记了)。当我使用类似的代码将 RGB 设置为其他值时,没关系,图像始终是透明的。
-
输出是 0 alpha 的图像?还有PixelArray,我认为这是包装
surfarray的python类@ -
@monkey - 无论我做什么,输出图像看起来都是透明的,尽管我不能排除它只是几乎透明的。 (我不确定如何检查。)根据您的建议,我尝试制作一个 PixelArray,然后将每个像素设置为 pg.Color(255,255,255,255),但图像仍然是透明的。