OpenCV python复制多边形从一个图像到另一个图像

时间:2016-03-03 21:08:27

标签: python opencv image-processing

我有两张照片。我想从一个图像中抓取一个区域(多边形,而不是矩形),并将该区域复制到另一个图像上。我怎么能做到这一点?这是我到目前为止所拥有的。

#I can also create a mask that has the same number of channels (3)
src1_mask = np.zeros(src1.shape)
#create a polygon for region of interest
poly = np.array([ [150,150], [200,100], [350,150], [350,200], [300,220], [200,200], [190,180] ], np.int32)
cv2.fillPoly(src1_mask, [poly], (255,255,255))

此时我已加载了两张图片,并且我有一个区域的多边形和蒙版。现在我不知道如何使用这个掩码/多边形将src1的那部分复制到src2上。

import cv2
import numpy as np
import matplotlib.pyplot as pst

#load two images
srcfilename = 'foo.jpg'
src1 = cv2.imread(srcfilename)
srcfilename = 'bar.jpg'
src2 = cv2.imread(srcfilename)

#create mask template
src1_mask = src1.copy()
src1_mask = cv2.cvtColor(src1_mask,cv2.COLOR_BGR2GRAY)
src1_mask.fill(0)

#define polygon around region
poly = np.array([ [0,0], [20,0], [65,40], [150,40], [225,5], [225,170],[120,200], [10,190] ], np.int32)

#fill polygon in mask
_ = cv2.fillPoly(src1_mask, [poly], 255)

#create region of interest
roi = src2[np.min(poly[:,1]):np.max(poly[:,1]),np.min(poly[:,0]):np.max(poly[:,0])]
mask = src1_mask[np.min(poly[:,1]):np.max(poly[:,1]),np.min(poly[:,0]):np.max(poly[:,0])]

mask_inv = cv2.bitwise_not(mask)
img1_bg = cv2.bitwise_and(roi,roi,mask = mask_inv)
src1_cut = src1[np.min(poly[:,1]):np.max(poly[:,1]),np.min(poly[:,0]):np.max(poly[:,0])]

img2_fg = cv2.bitwise_and(src1_cut,src1_cut,mask = mask)

# Put logo in ROI and modify the main image
dst = cv2.add(img1_bg,img2_fg)
src2_final = src2.copy()
src2_final[np.min(poly[:,1]):np.max(poly[:,1]),np.min(poly[:,0]):np.max(poly[:,0])] = dst

plt.imshow(cv2.cvtColor(src2_final, cv2.COLOR_BGR2RGB))

最终编辑

使用按位操作我已经能够达到我想要的效果。这是示例代码。

zip

2 个答案:

答案 0 :(得分:4)

假设src1是你的图像而src1_mask是你的二进制掩码:

    src1_mask=cv2.cvtColor(src1_mask,cv2.COLOR_GRAY2BGR)#change mask to a 3 channel image 
    mask_out=cv2.subtract(src1_mask,src1)
    mask_out=cv2.subtract(src1_mask,mask_out)

现在,mask_out包含位于您定义的多边形内部的图像src1部分。

答案 1 :(得分:0)

假设 src1 是源图像 poly 是您的多边形, src2 是您要复制的目标图片 poly

将poly复制到遮罩:

mask = np.zeros(src1.shape)
cv2.fillPoly(mask,[poly],1)
poly_copied = np.multiply(mask,src1)

src2中的Maskout poly:

mask = np.ones(src2)
#assuming src1 and src2 are of same size
cv2.fillPoly(mask,[poly],0)
src2 = np.multiply(mask,src2)

将poly复制到src2:

src2 = np.add(poly_copied,src2)