使用PIL.Image.frombuffer()保存RGBA图像

时间:2017-12-22 11:52:02

标签: python buffer python-imaging-library raspberry-pi3 rgba

我需要保存由numpy数组制作的透明图像。我可以用以下方式保存图像:

img = Image.fromarray(data, 'RGB')

但我需要它透明,所以我试着用以下方法保存:

img = Image.fromarray(data, 'RGBA')

然后我收到此错误:

File "/home/pi/Documents/Projet/GetPos.py", line 51, in click
 img = Image.fromarray(data, 'RGBA')
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 2217, in 
fromarray
 return frombuffer(mode, size, obj, "raw", rawmode, 0, 1)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 2162, in 
frombuffer
 core.map_buffer(data, size, decoder_name, None, 0, args)
ValueError: buffer is not large enough

我做了一些研究但是对于我想要做的简单事情来说,每件事看起来都很复杂...... 有没有人可以帮我这个?

这是我的完整代码(我对python很新:)):

mouse = pymouse.PyMouse()
posX, posY = mouse.position()
print(mouse.position())

w, h = 1920, 1080
data = np.zeros((h, w, 3), dtype=np.uint8)

for x in range(posX-20, posX+20):
    if x > 1679:
        data[posY, w-1] = [255, 0, 0]
    else:
        data[posY, x] = [255, 0, 0]

for y in range(posY-20, posY+20):
    if y > 1049:
        data[h-1, posX] = [255, 0, 0]
    else:
        data[y, posX] = [255, 0, 0]

img = Image.fromarray(data, 'RGBA')            
##img = Image.frombuffer('RGBA', [1080, 1920], data, "raw", 'RGBA', 0, 1)
img.save('my.png')

1 个答案:

答案 0 :(得分:1)

为了保存透明图像,您需要为每个像素设置第四个值,称为Alpha通道,它决定了像素的不透明度。 (RGBA代表红色,绿色,蓝色和alpha。)因此,在代码中唯一需要更改的是基本上提供第4个alpha值,使用4个值的元组而不是3个像素。将第4个值设置为255表示它完全可见,0表示它是100%透明的。在下面的示例中,我只是将绘制红色的每个像素设置为完全可见,其他像素将是透明的:

mouse = pymouse.PyMouse()
posX, posY = mouse.position()

w, h = 1920, 1080
data = np.zeros((h, w, 4), dtype=np.uint8)

for x in range(posX-20, posX+20):
if x > 1679:
    data[posY, w-1] = [255, 0, 0, 255]
else:
    data[posY, x] = [255, 0, 0, 255]

for y in range(posY-20, posY+20):
    if y > 1049:
        data[h-1, posX] = [255, 0, 0, 255]
    else:
        data[y, posX] = [255, 0, 0, 255]

img = Image.fromarray(data, 'RGBA')            
img.save('my.png')