您好,我想创建一个半透明图像。我原以为是直截了当的,结果却并非如此。我创建了一个深度为 4 的 1000x1000 像素阵列(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(testImage).save('result.png') #throws an error
cv2.imshow("Test Image", testImage)
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() 来预览图像,但我真的无法判断 open cv 是否将透明像素显示为黑色,或者我是否搞砸了为我的 alpha 层创建/分配值。而且由于某种原因颜色是白色而不是绿色。
任何人都可以指出我做错了什么吗?
请原谅正方形变成了长方形条。
PIL 没有专家,但这就是您想要的吗?
from PIL import Image
i = Image.new('RGBA', (1000,1000), color=(0,0,0,0))
j = Image.new('RGBA', (500,500), color=(38,255,0,125))
i.paste(j, (250,250))
i.show()