Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x BytesIO将PNG文件中的透明度替换为黑色背景_Python 3.x_Image_Python Imaging Library_Urllib_Bytesio - Fatal编程技术网

Python 3.x BytesIO将PNG文件中的透明度替换为黑色背景

Python 3.x BytesIO将PNG文件中的透明度替换为黑色背景,python-3.x,image,python-imaging-library,urllib,bytesio,Python 3.x,Image,Python Imaging Library,Urllib,Bytesio,我想在“image”变量中保持透明背景 若我写入一个文件,图像看起来很好。我的意思是图像有一个透明的背景 with urllib.request.urlopen(request) as response: imgdata = response.read() with open("temp_png_file.png", "wb") as output: output.write(imgdata) 但是,如果我将图像数据保存在BytesIO中,透明背景将变成黑

我想在“image”变量中保持透明背景

若我写入一个文件,图像看起来很好。我的意思是图像有一个透明的背景

with urllib.request.urlopen(request) as response:
     imgdata = response.read()
     with open("temp_png_file.png", "wb") as output:
         output.write(imgdata)
但是,如果我将图像数据保存在BytesIO中,透明背景将变成黑色背景

with urllib.request.urlopen(request) as response:
     imgdata = response.read()
ioFile = io.BytesIO(imgdata) 
img = Image.open(ioFile)
img.show()
(在代码段上方,img.show行显示了一个黑色背景的图像。)

如何在img变量中保留透明图像对象?

两件事


首先,如果在使用
枕头
打开文件时希望看到RGBA图像,最好将得到的图像转换为RGBA图像,否则可能会尝试显示调色板索引而不是RGB值:

因此,改变这一点:

img = Image.open(ioFile)
为此:

img = Image.open(ioFile).convert('RGBA')

其次,OpenCV
imshow()
无法处理透明度,因此我倾向于使用枕头的
show()
方法。像这样:

from PIL import Image

# Do OpenCV stuff
...
...

# Now make OpenCV array into Pillow Image and display
Image.fromarray(numpyImage).show()

尝试将
img=Image.open(ioFile)
更改为
img=Image.open(ioFile)。转换('RGBA')
@MarkSetchell,谢谢马克!这是这个问题的解决办法。然而,我也坚持了我的下一步。我需要将其转换为OpenCV图像对象。我这样做了:“opencvImage=cv2.cvtColor(np.array(img),cv2.COLOR\u RGB2BGR)”并且,opencvImage也显示了黑色背景。。你知道如何修复吗?你的图像在
convert('RGBA')
之后是RGBA,所以你需要决定如何处理透明度。OpenCV的
imshow()
不处理透明度,因此它看起来会出错,但如果您将其写入文件,它就可以了。PIL/Pillow提供了一种能够理解透明度的
show()
方法,因此您可以从PIL导入图像
,然后执行
Image.fromarray(numpyImage).show()
其中
numpyImage
是OpenCV图像或Numpy ndarray。谢谢@MarkSetchell。回答这个问题,这样我就可以标记为答案。