CV2 堆肥 2 个不同大小的图像

CV2 Composting 2 images of differing size

我需要对 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)

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

我搜索了所有内容,但我找到的代码执行类似 'adds' 图像在一起(并排)的操作。

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

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)

编辑: 要将前景放在指定位置,您可以像以前一样使用 numpy indexing。 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)