简体   繁体   中英

How to open an image with alpha channels in OpenCV-Python?

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?

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, eg TIFF, PNG, GIF.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM