opencv+python用背景减去法抠图
opencv+python用背景减去法抠图
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 #(2436, 1125, 3)
imBG=cv2.imread("bg_30061.jpg")
plt.imshow(cv2.cvtColor(imBG,cv2.COLOR_BGR2RGB))
# Step 1 预处理
# 日常缩放图像,背景图要缩放到和图A意一样大
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))
# Step 2 二值化图像
thresh=cv2.adaptiveThreshold(sub,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,19,5)
## 图像二值化有很多种方法, adaptiveThreshold 是基于局部的,最后两个参数,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
# Step 3 边缘检测
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)
# 通过面积大小,找到需要的边缘的 index,这里为 866
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))
# 保存为 png
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)
opencv+python用背景减去法抠图相关教程