简体   繁体   中英

Blending multiple images with OpenCV

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?

You can blend all of your images by blending according to follwoing sequence:

  1. Blend the first two images
  2. Take the result and blend it with the next image
  3. and so forth
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)

Try This:

blendedImage = weight_1 * image_1 + weight_2 * image_2 + ... + weight_n * image_n

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:

在此处输入图片说明

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM