2016-03-03 164 views
3

我有兩個圖像。我想從一個圖像中抓取一個區域(多邊形,而不是矩形),並將該區域複製到另一個圖像上。我怎樣才能做到這一點?這是我到目前爲止。OpenCV python從一個圖像複製多邊形到另一個圖像

import cv2 
import numpy as np 

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


src1_mask = np.zeros(src1.shape[:-1]) 
#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) 

在這一點上我有我的兩個圖像加載,我有一個多邊形和麪具的區域。現在我不知道如何使用這個蒙版/多邊形將src1的那部分複製到src2上。

#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)) 

最後編輯

使用位運算,我已經能夠達到我想要的東西。這裏是示例代碼。

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)) 

回答

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的一部分。

相關問題