import cv2
from matplotlib import pyplot as plt
import numpy as np
imA=cv2.imread("target.png")
plt.imshow(cv2.cvtColor(imA,cv2.COLOR_BGR2RGB))
imA.shape
imBG=cv2.imread("bg_30061.jpg")
plt.imshow(cv2.cvtColor(imBG,cv2.COLOR_BGR2RGB))
imBG=cv2.resize(imBG,(1125,2436),interpolation=cv2.INTER_CUBIC)
imA_gray=cv2.cvtColor(imA,cv2.COLOR_BGR2GRAY)
imBG_gray=cv2.cvtColor(imBG,cv2.COLOR_BGR2GRAY)
sub=imBG_gray.astype("int32")-imA_gray.astype("int32")
sub=np.absolute(sub).astype("uint8")
plt.imshow(cv2.cvtColor(sub,cv2.COLOR_BGR2RGB))
thresh=cv2.adaptiveThreshold(sub,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,19,5)
thresh=cv2.erode(thresh,None,iterations=2)
thresh=cv2.dilate(thresh,None,iterations=2)
plt.figure(num="thresh")
plt.imshow(cv2.cvtColor(thresh,cv2.COLOR_BGR2RGB))
plt.close
cnts,hierarchy=cv2.findContours(thresh.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
len(cnts)
area=[]
for i in cnts:
cnt_area = cv2.contourArea(i)
area.append(cnt_area)
mask=np.zeros([2436,1125],dtype=np.uint8)
mask[:,:]=255
res=cv2.drawContours(mask,cnts,866,(0,0,225),2)
plt.imshow(cv2.cvtColor(res,cv2.COLOR_BGR2RGB))
mask2=np.zeros([2436,1125],dtype=np.uint8)
mask2[:,:]=0
res2=cv2.drawContours(mask2,cnts,866,255,cv2.FILLED)
plt.imshow(cv2.cvtColor(res2,cv2.COLOR_BGR2RGB))
h,w,c=imA.shape
b,g,r=cv2.split(imA)
imA_2=np.zeros((4,h,w),dtype=imA.dtype)
imA_2[0][0:h,0:w]=b
imA_2[1][0:h,0:w]=g
imA_2[2][0:h,0:w]=r
imA_2[3][0:h,0:w]=mask2
imA_new=cv2.merge(imA_2)
cv2.imwrite("imA_new.png",imA_new)