OpenCV-Python证件照背景替换

先将图片数据转换,然后利用KMeans图像分割,得到背景和前景,
通过遮罩进行模糊滤波和形态学操作,最后输出通道。

import cv2 as cv
import numpy as np

#读取数据
img=cv.imread("D:/testimage/ID.jpg")
h,w,c=img.shape
simplenum=h*w
#将图片转换为点保存
points=np.zeros((simplenum,c),np.float32)
index=0
for i in range(h):
    for j in range(w):
        index=i*w+j
        points[index][0] = img[i][j][0]
        points[index][1] = img[i][j][1]
        points[index][2] = img[i][j][2]

#聚类数目
clusternum=4
criteria=(cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 10, 0.1)
ret,label,center=cv.kmeans(points,clusternum,None,criteria,10,cv.KMEANS_PP_CENTERS)

#生产掩模
mask = np.zeros((h,w),np.uint8)
#假设背景于此
index=w*2+5
dst=img.copy()
new_index = label[index]
for i in range(h):
    for j in range(w):
        index = i * w + j
        label1 = label[index]
        if new_index == label1:
            dst[i][j][0] = 0
            dst[i][j][1] = 0
            dst[i][j][2] = 0
            mask[i][j] = 0
        else:
            mask[i][j] = 255

#开操作和膨胀处理/高斯滤波
element = cv.getStructuringElement(cv.MORPH_RECT,(3,3))
mask=cv.erode(mask,element)
mask=cv.GaussianBlur(mask,(3,3),0,0)
for i in range(h):
    for j in range(w):
        if mask[i][j]==0:
            dst[i][j][0] = 0
            dst[i][j][1] = 0
            dst[i][j][2] = 255
        else:
            continue
cv.imshow("1",mask)
cv.imshow("2",dst)
cv.imwrite("D:/testimage/result_ID.jpg",dst)
cv.waitKey(0)

原图:OpenCV-Python证件照背景替换_第1张图片
结果:OpenCV-Python证件照背景替换_第2张图片

你可能感兴趣的:(OpenCV基础教程,机器学习)