正如@sanyam和@Pam所指出的,我们可以保存转换后的图像并且它会正确显示。这是因为在Windows上,在使用系统默认的图像查看器显示之前,图像会被保存为临时BMP文件,根据
PIL文档的说明:
Image.show(title=None, command=None)
Displays this image. This method is mainly intended for debugging purposes.
On Unix platforms, this method saves the image to a temporary PPM file, and calls
either the xv utility or the display utility, depending on which one can be found.
On macOS, this method saves the image to a temporary BMP file, and opens it with
the native Preview application.
On Windows, it saves the image to a temporary BMP file, and uses the standard BMP
display utility to show it (usually Paint).
为了解决这个问题,我们可以对Pillow代码进行修补,将PNG格式作为默认格式。首先,我们需要找到Pillow包的根目录:
import PIL
print(PIL.__path__)
在我的系统上,输出如下:
[’D:\Anaconda\lib\site-packages\PIL’]
转到此目录并打开文件
ImageShow.py
。我在
register(WindowsViewer)
之后添加了以下代码:
class WindowsPNGViewer(Viewer):
format = "PNG"
def get_command(self, file, **options):
return ('start "Pillow" /WAIT "%s" '
'&& ping -n 2 127.0.0.1 >NUL '
'&& del /f "%s"' % (file, file))
register(WindowsPNGViewer, -1)
之后,我可以正确地显示带有alpha通道的图像。
参考资料
cv2.COLOR_RGB2RGBA
- DirtyBitImage.putalpha()
的文档,它不需要事先带有 alpha 通道的图像。这个问题与 OpenCV 无关。 - jdhao