TL; DR
This is the code for overlaying png_image.png
(image with alpha channel) on the upper left of bg.jpg
.
import cv2
frame = cv2.imread("bg.jpg ")
png_image = cv2.imread("alpha.png ", cv2.IMREAD_UNCHANGED) #Read with alpha channel included
#Setting the paste destination coordinates. For the time being, in the upper left
x1, y1, x2, y2 = 0, 0, png_image.shape[1], png_image.shape[0]
#Synthetic!
frame[y1:y2, x1:x2] = frame[y1:y2, x1:x2] * (1 - png_image[:, :, 3:] / 255) + \
png_image[:, :, :3] * (png_image[:, :, 3:] / 255)
The PNG file contains data that represents the transparency of each pixel called the "alpha channel". The range is 0-255, which is the same as RGB. A value of 255 is 100% valid, and a value of 0 is 0% (fully transparent).
png_image = cv2.imread("alpha.png ", cv2.IMREAD_UNCHANGED) #Read with alpha channel included
In normal cv2.imread ()
, it will be in the form of numpy.ndarray
of[h, w, 3]
, but specify cv2.IMREAD_UNCHANGED
to specify cv2.imread ()
. When called, it takes the form [h, w, 4]
. BGR
is BGRA
and ends with an alpha channel.
After loading the image, combine it. However, it can be synthesized by the usual NuPy matrix operation. What we are doing is allocating the original background image and the image to be drawn by the numerical value of the alpha channel and adding them together.
frame[y1:y2, x1:x2] = frame[y1:y2, x1:x2] * (1 - png_image[:, :, 3:] / 255) + \
png_image[:, :, :3] * (png_image[:, :, 3:] / 255)
png_image [:,:, 3:]
is the alpha channel retrieval. The range of the alpha channel is 0-255, so divide by 255 to get a ratio of 0-1. You can get the final image by multiplying the image to be drawn by the calculated ratio, multiplying the background by the "remaining" of the ratio, and adding them together.
By the way, if you write png_image [:,:, 3]
, you will get angry if the size of the matrix does not match (I made a mistake).
bg.jpg
alpha.png
The result of cv2.imwrite ("result.jpg ", frame)
Although there are various useful sites, I couldn't find the code that was just right, so I made an article. (Maybe it's too obvious to write it instead)
-Display png with alpha channel in OpenCV -Qiita -Python, OpenCV, NumPy for alpha blending and masking images \ | note \ .nkmk \ .me
For the image, I used the material of Cute free material collection Irasutoya.
Recommended Posts