Reputation: 2143
What is the way to blend multiple images with OpenCV using python? I came across the following snippet:
img = cv2.addWeighted(mountain, 0.3, dog, 0.7, 0)
on https://docs.opencv.org/3.4/d5/dc4/tutorial_adding_images.html
that shows a way to blend 2 images mountain
and dog
. What if I want to blend more than 2 images? How could I do this?
Upvotes: 3
Views: 17990
Reputation: 40859
Here is Python code to blend multiple images in a list. I used the basic formulation from Shamsheer's answer.
First, let's get three images.
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
dim = (425, 425)
apple = mpimg.imread('apple.jpg')
apple = cv2.resize(apple, dim)
banana = mpimg.imread('banana.jpg')
banana = cv2.resize(banana, dim)
orange = mpimg.imread('orange.jpg')
orange = cv2.resize(orange, dim)
_ = plt.imshow(apple)
_ = plt.show()
_ = plt.imshow(banana)
_ = plt.show()
_ = plt.imshow(orange)
_ = plt.show()
Here are the images:
Now let's blend them together equally. Since there are three images, the fraction of each image's contribution to the final output is 0.333.
def blend(list_images): # Blend images equally.
equal_fraction = 1.0 / (len(list_images))
output = np.zeros_like(list_images[0])
for img in list_images:
output = output + img * equal_fraction
output = output.astype(np.uint8)
return output
list_images = [apple, banana, orange]
output = blend(list_images)
_ = plt.imshow(output)
And here is the result:
Upvotes: 2
Reputation: 744
Try This:
blendedImage = weight_1 * image_1 + weight_2 * image_2 + ... + weight_n * image_n
Upvotes: 7
Reputation: 2518
You can blend all of your images by blending according to follwoing sequence:
for idx, img in enumerate(imgs):
if idx == 1:
first_img = img
continue
else:
second_img = img
first_img = cv2.addWeighted(first_img, 0.5, second_img, 0.5, 0)
You might have a problem with the weights of each image, but this is another issues. To achieve an equal weigth for all images you can use the index to calculate the appropriate portion:
for idx, img in enumerate(imgs):
if idx == 1:
first_img = img
continue
else:
second_img = img
second_weight = 1/(idx+1)
first_weight = 1 - second_weight
first_img = cv2.addWeighted(first_img, first_weight, second_img, second_weight, 0)
Upvotes: 4