Reputation: 73
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?
Upvotes: 5
Views: 9129
Reputation: 207365
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.
Upvotes: 6