2

I want to keep transparent background at my 'image' variable.

If I write into a file, image looks fine. I mean image has a transparent background.

with urllib.request.urlopen(request) as response:
     imgdata = response.read()
     with open("temp_png_file.png", "wb") as output:
         output.write(imgdata)

However, if I keep the image data in BytesIO, transparent background becomes a black background.

with urllib.request.urlopen(request) as response:
     imgdata = response.read()
ioFile = io.BytesIO(imgdata) 
img = Image.open(ioFile)
img.show()

(Above code piece, img.show line shows an image with black background.)

How can I keep a transparent image object in img variable ?

eknbrk
  • 187
  • 1
  • 1
  • 16
  • Try changing `img = Image.open(ioFile)` to `img = Image.open(ioFile).convert('RGBA')` – Mark Setchell Dec 11 '18 at 10:55
  • @MarkSetchell, thank you mark ! It is the solution for this question. However, I stuck at my next step as well. I need to convert this into OpenCV image object. I did this : "opencvImage = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)" And, opencvImage shows a black background as well.. Do you have any idea how to fix that ? – eknbrk Dec 11 '18 at 11:17
  • Your image is RGBA after `convert('RGBA')`, so you need to decide how you want to handle transparency. OpenCV's `imshow()` doesn't handle transparency, so it will look wrong there but if you write it to a file it will be fine. PIL/Pillow offers a `show()` method that does understand transparency, so you can do `from PIL import Image` and then `Image.fromarray(numpyImage).show()` where `numpyimage` is an OpenCV image or Numpy ndarray. – Mark Setchell Dec 11 '18 at 14:54
  • Thank you @MarkSetchell. Reply the question, thus I can mark as an answer. – eknbrk Dec 11 '18 at 16:18

1 Answers1

3

Two things...


Firstly, if you want and expect an RGBA image when opening a file with Pillow, it is best to convert whatever you get into that - else you may end up trying to display palette indices instead of RGB values:

So change this:

img = Image.open(ioFile)

to this:

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

Secondly, OpenCV's imshow() can't handle transparency, so I tend to use Pillow's show() method instead. Like this:

from PIL import Image

# Do OpenCV stuff
...
...

# Now make OpenCV array into Pillow Image and display
Image.fromarray(numpyImage).show()
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432