CV2 合成 2 张不同大小的图像

Mik*_*eyB 1 python image alphablending cv2

我需要对 2 张大小不同的图像进行 alpha 混合。我已经设法通过将它们调整为相同的大小来合成它们,所以我得到了部分逻辑:

import cv2 as cv

def combine_two_color_images_composited(foreground_image, background_image):

    foreground = cv.resize(foreground_image, (400,400), interpolation=cv.INTER_CUBIC).copy()
    background = cv.resize(background_image, (400,400), interpolation=cv.INTER_CUBIC).copy()
    alpha =0.5
    # do composite of foreground onto the background
    cv.addWeighted(foreground, alpha, background, 1 - alpha, 0, background)

    cv.imshow('composited image', background)
    cv.waitKey(10000)
Run Code Online (Sandbox Code Playgroud)

我想知道是否需要制作一个与较大图像大小相同的蒙版,然后将其用于我的第一张图像。如果是这样,我还不知道如何在 CV2 中进行掩蔽……这只是我项目的一小部分,因此我无法花费大量时间研究掩蔽的工作原理。

我已经搜索了所有内容,但我找到的代码执行诸如将图像“添加”在一起(并排)之类的操作。

小智 5

要组合这两个图像,您可以使用 numpy 切片来选择要混合前景的背景图像部分,然后再次将新混合的部分插入背景中。

import cv

def combine_two_color_images(image1, image2):

    foreground, background = image1.copy(), image2.copy()
    
    foreground_height = foreground.shape[0]
    foreground_width = foreground.shape[1]
    alpha =0.5
    
    # do composite on the upper-left corner of the background image.
    blended_portion = cv.addWeighted(foreground,
                alpha,
                background[:foreground_height,:foreground_width,:],
                1 - alpha,
                0,
                background)
    background[:foreground_height,:foreground_width,:] = blended_portion
    cv.imshow('composited image', background)

    cv.waitKey(10000)
Run Code Online (Sandbox Code Playgroud)

编辑:要将前景放置在指定位置,您可以像以前一样使用numpy 索引。Numpy 索引非常强大,你会发现它在很多场合都很有用。我链接了上面的文档。真的很值得一看。

def combine_two_color_images_with_anchor(image1, image2, anchor_y, anchor_x):
    foreground, background = image1.copy(), image2.copy()
    # Check if the foreground is inbound with the new coordinates and raise an error if out of bounds
    background_height = background.shape[0]
    background_width = background.shape[1]
    foreground_height = foreground.shape[0]
    foreground_width = foreground.shape[1]
    if foreground_height+anchor_y > background_height or foreground_width+anchor_x > background_width:
        raise ValueError("The foreground image exceeds the background boundaries at this location")
    
    alpha =0.5

    # do composite at specified location
    start_y = anchor_y
    start_x = anchor_x
    end_y = anchor_y+foreground_height
    end_x = anchor_x+foreground_width
    blended_portion = cv.addWeighted(foreground,
                alpha,
                background[start_y:end_y, start_x:end_x,:],
                1 - alpha,
                0,
                background)
    background[start_y:end_y, start_x:end_x,:] = blended_portion
    cv.imshow('composited image', background)

    cv.waitKey(10000)
Run Code Online (Sandbox Code Playgroud)