I have two images. I want to grab a region (polygon, not rectangle) from one image and copy that region onto the other image. How can I accomplish this? Here is what I have so far.
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)
at this point I have my two images loaded and I have a polygon and mask for the region. Now I don't know how to use this mask/polygon to copy that part of src1 onto 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))
FINAL EDIT
Using bitwise operations I have been able to achieve what I wanted. Here is example code.
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))