I have a background image on which I want to overlay my transparent image. I have tried so many options so far and none has worked well. Finally, I have found the following piece of code:
processedImagePIL = Image.fromarray(processedImage) #since we use opencv
shuttleImagePIL = Image.fromarray(shuttleIcon) #since we use opencv
blended = Image.blend(processedImagePIL, shuttleImagePIL, alpha=0.5)
but even that gave me a size error
ValueError: images do not match
I don't get why the image sizes should be equal, since what I want to overlay is a small icon, expecting that to be as big as my background is kinda stupid. Is there a straightforward algorithm which is efficient in Python? Any package or implementation would do.
My icon: https://ibb.co/fecVOz
My background: https://ibb.co/chweGK
OK, I've got it running through OpenCV:
# function to overlay a transparent image on background.
def transparentOverlay(backgroundImage, overlayImage, pos=(0, 0), scale=1):
overlayImage = cv2.resize(overlayImage, (0, 0), fx=scale, fy=scale)
h, w, _ = overlayImage.shape # Size of foreground
rows, cols, _ = backgroundImage.shape # Size of background Image
y, x = pos[0], pos[1] # Position of foreground/overlayImage image
# loop over all pixels and apply the blending equation
for i in range(h):
for j in range(w):
if x + i >= rows or y + j >= cols:
continue
alpha = float(overlayImage[i][j][3] / 255.0) # read the alpha channel
backgroundImage[x + i][y + j] = alpha * overlayImage[i][j][:3] + (1 - alpha) * backgroundImage[x + i][y + j]
return backgroundImage
And then used as follows:
# Overlay transparent images at desired postion(x,y) and Scale.
result = transparentOverlay(processedImage, shuttleIcon, tuple(trackedCenterPoint), 0.7)
seemed to have solved my problems.
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.