合并两张带遮罩的图片

8

我正在尝试在OpenCV Python中将logo绘制在一张风景图片的上方。我已经找到了一些答案可以“混合”/水印图像,但我不想使logo透明,我只想将logo显示在风景图片的顶部并保留logo的透明度(或缺乏透明度)。

我尝试了cv2.add()cv2.bitwise_and(),但这些方法没有复制logo。

src = cv2.imread('../images/pan1.jpg')
logo = cv2.imread('../images/logo.png')  # the background is black which is good because I dont want the black parts

# Ensure the logo image is the same size as the landscape image
logo_resized = np.zeros(src.shape, dtype="uint8")
# Place the logo at the bottom right
logo_resized[ src.shape[0] - logo.shape[0] : src.shape[0], src.shape[1] - logo.shape[1] : src.shape[1]] = logo

# Convert the logo to single channel
logo_gray = cv2.cvtColor(logo_resized, cv2.COLOR_BGR2GRAY)
# Create a mask of the logo image
ret, mask = cv2.threshold(logo_gray, 1, 255, cv2.THRESH_BINARY)

# Combine the landscape and the logo images but use a mask so the black parts of logo don't get copied across
# combined = cv2.bitwise_and(logo_resized, logo_resized, mask=mask)
combined = cv2.add(src, logo_resized, mask=mask)

我的结果:

输入图像描述 输入图像描述 输入图像描述


1
你是否因为某些原因而执着于使用OpenCV?使用基本的NumPy操作似乎可以轻松完成此任务。 - en_Knight
@en_Knight 我更倾向于使用OpenCV,因为我在Python中进行原型设计,然后再用C++实现。但是numpy也可以使用。 - sazr
你能提供原始的两张图片吗?一个是标志,另一个是风景。实际上,你只需要将图像中不是黑色的部分全部设置为0,然后将其与标志添加即可。 - api55
你想在Python中使用cv::Mat::copyTo函数,这个函数在这篇帖子中有完美的解释。 - zindarod
1个回答

13

我认为以下是您所想的。

代码:

room = cv2.imread('room.JPG' )
logo = cv2.imread('logo.JPG' )

#--- Resizing the logo to the shape of room image ---
logo = cv2.resize(logo, (room.shape[1], room.shape[0]))

#--- Apply Otsu threshold to blue channel of the logo image ---
ret, logo_mask = cv2.threshold(logo[:,:,0], 0, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU)
cv2.imshow('logo_mask', logo_mask)

room2 = room.copy() 

#--- Copy pixel values of logo image to room image wherever the mask is white ---
room2[np.where(logo_mask == 255)] = logo[np.where(logo_mask == 255)]

cv2.imshow('room_result.JPG', room2)
cv2.waitKey()
cv2.destroyAllWindows()

结果:

最终结果:

enter image description here

下面是在标志的蓝色通道上应用Otsu阈值所得到的掩模图像:

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接