下面简单图片演示一下:
提取mask:
===>
替换背景:
+
=
python的opencv代码如下:
# coding=utf-8
import cv2
import numpy as np
img=cv2.imread('lp.jpg')
img_back=cv2.imread('back.jpg')
#日常缩放
rows,cols,channels = img_back.shape
img_back=cv2.resize(img_back,None,fx=0.7,fy=0.7)
cv2.imshow('img_back',img_back)
rows,cols,channels = img.shape
img=cv2.resize(img,None,fx=0.4,fy=0.4)
cv2.imshow('img',img)
rows,cols,channels = img.shape#rows,cols最后一定要是前景图片的,后面遍历图片需要用到
#转换hsv
hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
#获取mask
lower_blue=np.array([78,43,46])
upper_blue=np.array([110,255,255])
mask = cv2.inRange(hsv, lower_blue, upper_blue)
cv2.imshow('Mask', mask)
#腐蚀膨胀
erode=cv2.erode(mask,None,iterations=1)
cv2.imshow('erode',erode)
dilate=cv2.dilate(erode,None,iterations=1)
cv2.imshow('dilate',dilate)
#遍历替换
center=[50,50]#在新背景图片中的位置
for i in range(rows):
for j in range(cols):
if dilate[i,j]==0:#0代表黑色的点
img_back[center[0]+i,center[1]+j]=img[i,j]#此处替换颜色,为BGR通道
cv2.imshow('res',img_back)
cv2.waitKey(0)
cv2.destroyAllWindows()
批量测试代码:
import os
import sys
import cv2
import numpy as np
# 遍历文件夹
def walk_file(file):
for root, dirs, files in os.walk(file):
# root 表示当前正在访问的文件夹路径
# dirs 表示该文件夹下的子目录名list
# files 表示该文件夹下的文件list
img_files = []
# 遍历文件
for f in files:
# print(os.path.join(root, f))
img_files.append( os.path.join(root, f) )
# 遍历所有的文件夹
#for d in dirs:
# print(os.path.join(root, d))
return img_files
def matting(img_file, img_back_file='./back.png'):
img=cv2.imread( img_file )
#日常缩放
# rows,cols,channels = img_back.shape
# img_back=cv2.resize(img_back,None,fx=0.7,fy=0.7)
#cv2.imshow('img_back',img_back)
rows,cols,channels = img.shape
# img=cv2.resize(img,None,fx=0.5,fy=0.5)
#cv2.imshow('img',img)
rows,cols,channels = img.shape#rows,cols最后一定要是前景图片的,后面遍历图片需要用到
print ('>>>>>', rows,cols)
img_back=np.ones([rows,cols,3]) * 255 #cv2.imread( img_back_file )
#转换hsv
hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
#获取mask
lower_blue=np.array([0,0,0])
upper_blue=np.array([50,100,255])
mask = cv2.inRange(hsv, lower_blue, upper_blue)
#cv2.imshow('Mask', mask)
#腐蚀膨胀
erode=cv2.erode(mask,None,iterations=1)
#cv2.imshow('erode',erode)
dilate=cv2.dilate(erode,None,iterations=1)
#cv2.imshow('dilate',dilate)
#遍历替换
center=[0,0]#在新背景图片中的位置
for i in range(rows):
for j in range(cols):
if dilate[i,j]==0:#0代表黑色的点
img_back[center[0]+i,center[1]+j]=img[i,j]#此处替换颜色,为BGR通道
#cv2.imshow('res',img_back)
#cv2.waitKey(0)
#cv2.destroyAllWindows()
cv2.imwrite( './res/'+img_file.split('/')[-1], img_back )
def main():
img_files = walk_file('./imgs/')
print( '>>>', img_files )
for per_img in img_files:
matting( per_img )
if __name__ == '__main__':
main()