5

I'm trying to set certain pixels to be transparent on an image with the python3 cv2 library. How do I open an image so that it can support transparency?

I looked into this and I can't find good documentation on using transparent pixels.

The current way I'm opening images is the following:

img = cv2.resize(cv2.imread("car.jpeg", cv2.COLOR_B), (0, 0), fx=0.2, fy=0.2)

and I'm setting colors like this:

img.itemset((r, c, 1), val)

How do I edit the alpha channels?

BSMP
  • 4,596
  • 8
  • 33
  • 44
Jared Goodman
  • 73
  • 1
  • 4

1 Answers1

6

You can either open an image that already has an alpha channel, such as a PNG or TIFF, using:

im = cv2.imread('image.png', cv2.IMREAD_UNCHANGED) 

and you will see its shape has 4 as the last dimension:

print(im.shape)
(400, 400, 4)

Or you can open an image that has no alpha channel, such as JPEG, and add one yourself:

BGR = cv2.imread('image.jpg', cv2.IMREAD_UNCHANGED)

BGRA = cv2.cvtColor(im,cv2.COLOR_BGR2BGRA) 

In either case, you can then set values in the alpha channel with:

BGRA[y,x,3] = ...

Then, at the end, save the image to a format that supports alpha/transparency obviously, e.g. TIFF, PNG, GIF.

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • Hm... Printing im.shape shows 3 dimensions for me. Does it need to be a png? I'm using a jpeg. – Jared Goodman Sep 06 '19 at 17:24
  • JPEGs do not have transparency - because they are for photographs and the world isn't really transparent anywhere - there's always something even if it is in the distance. TIFFs and PNG *can* have transparency because they are for computer graphics rather than photos. If you don't have transparency in your image and you want some, you will need to use the second part of my answer to add an alpha channel. Of course, you will then need to save as PNG/TIFF or GIF afterwards to get the transparency into the file... because JPEGs can't store transparency. – Mark Setchell Sep 06 '19 at 17:26
  • 1
    Just to clarify, not all TIFFs and PNGs have transparency - some do, some don't. Check the shape to see if it ends in `4`. – Mark Setchell Sep 06 '19 at 17:28
  • Works great! Thanks. – Jared Goodman Sep 06 '19 at 21:56