There are several ways of doing this... I'll start with this image:

Add blank alpha channel with OpenCV and set content with Numpy indexing:
import cv2
import numpy as np
img = cv2.imread('paddington.jpg')
# Add alpha layer with OpenCV
bgra = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
# Set alpha layer semi-transparent with Numpy indexing, B=0, G=1, R=2, A=3
bgra[...,3] = 127
# Save result
cv2.imwrite('result.png',bgra)

Alternatively, create a solid alpha layer filled with 128s and stack depth-wise with Numpy dstack()
:
import cv2
import numpy as np
img = cv2.imread('paddington.jpg')
# Create solid alpha layer, same height and width as "img", filled with 128s
alpha = np.zeros([img.shape[0],img.shape[1],1], dtype=np.uint8) + 128
# Depth-wise stack that layer onto existing 3 RGB layers
bgra = np.dstack((img,alpha))
# Save result
cv2.imwrite('result.png',bgra)
Alternatively, create a solid alpha layer filled with 128s and merge using OpenCV merge()
:
import cv2
import numpy as np
img = cv2.imread('paddington.jpg')
# Create solid alpha layer, same height and width as "img", filled with 128s
alpha = np.full_like(img[...,0], 128)
# Merge new alpha layer onto image with OpenCV "merge()"
bgra = cv2.merge((img,alpha))
# Save result
cv2.imwrite('result.png',bgra)
Note that, as expected, the OpenCV cvtColor()
method described first is fastest, by a factor of about 10x because it is hand optimised SIMD code. Timings with given image were as follows:
cv2.cvtColor()
- 48 microseconds
np.dstack()
- 477 microseconds
cv2.merge()
- 489 microseconds
Keywords: Python, image, image processing, Numpy, OpenCV, dstack, merge, cvtColor, add alpha channel, add transparency, set transparency, COLOR_BGR2BGRA, cv.COLOR_BGR2BGRA