如何在numpy中创建半透明图像并以PNG格式保存到Pillow中

0 投票
1 回答
51 浏览
提问于 2025-04-13 00:52

你好,我想创建一个半透明的图片。原本我以为这很简单,但结果并不是这样。我创建了一个1000x1000像素的数组,深度为4(分别是B、G、R和A通道)。我把它们初始化为全0,想着这样会生成一张完全黑色但也完全透明的基础图像。然后我在上面画了一个50%透明度的绿色形状,这里为了简化代码,我选择了一个正方形。

这里是图片描述

from PIL import Image
import cv2

blankImage = np.zeros((1000,1000,4))
BGRAcolor = (38,255,0,125) # 50% transaparent light green

blankImage[250:250, 750:750] = BGRAcolor

#Image.fromarray(blankImage).save('result.png') #throws an error

cv2.imshow("blankImage", blankImage)
cv2.waitKey()

问题是我无法把这个图像保存为.png格式,因为PIL报了个错,所以我无法确认我是否正确地制作了这个图像。错误信息是:

Traceback (most recent call last):
  File "C:\Users\.....\Image.py", line 3098, in fromarray
    mode, rawmode = _fromarray_typemap[typekey]
                    ~~~~~~~~~~~~~~~~~~^^^^^^^^^
KeyError: ((1, 1, 4), '<f8')

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "c:\Users\.....\transparentImage.py", line 25, in <module>
    Image.fromarray(testImage).save('result.png')
    ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\.....\Image.py", line 3102, in fromarray
    raise TypeError(msg) from e
TypeError: Cannot handle this data type: (1, 1, 4), <f8

另外,我尝试使用opencv的imshow()来预览图像,但我真的无法判断opencv是否把透明的像素显示成黑色,还是我在制作/赋值给alpha通道时搞错了。而且颜色奇怪地变成了白色,而不是绿色。

有没有人能指出我哪里做错了?

抱歉,正方形变成了一条长方形的条带。

这里是图片描述

1 个回答

4

你的代码里有两个错误。

首先,你需要创建一个类型为 np.uint8 的 numpy 数组。

blankImage = np.zeros((1000, 1000, 4), dtype=np.uint8)

其次,你使用切片的方式不对。

blankImage[top:bottom, left:right] = BGRAcolor

下面是修正后的代码。

import numpy as np
from PIL import Image

testImage = np.zeros((1000, 1000, 4), dtype=np.uint8)
BGRAcolor = (38, 255, 0, 125)  # 50% transaparent light green

testImage[250:750, 250:750] = BGRAcolor

Image.fromarray(testImage).save('result.png')

撰写回答