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?

1
  • Is this what you are looking for? Commented Sep 6, 2019 at 17:02

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Hm... Printing im.shape shows 3 dimensions for me. Does it need to be a png? I'm using a jpeg.
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.
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.
Works great! Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.