我需要对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中进行掩蔽....这只是我项目的一小部分,所以我不能花费大量时间研究如何掩盖工作。
我已经搜索了所有,但我找到的代码做的事情就像'添加'图像在一起(并排)。
要合并这两个图像,您可以使用numpy切片选择要混合前景的背景图像部分,然后再次在背景中插入新混合的部分。
def combine_two_color_images(image1, image2):
foreground, background = img1.copy(), img2.copy()
foreground_height = foreground.shape[0]
foreground_width = foreground.shape[1]
alpha =0.5
# do composite on the upper-left corner of 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 = img1.copy(), img2.copy()
# Check if the foreground is inbound with the new coordinates and raise an error if out of bounds
background_height = background.shape[1]
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)