opencv 换脸(1)

最近流行一个换脸的软件,我们来基于 opencv 来尝试实现一下。

import cv2

img = cv2.imread("images/robort/03.jpg")

cv2.imshow("Image 1",img)
cv2.waitKey(0)
cv2.destroyAllWindows()

首先我们加载图片然后将图片显示出来。

import cv2
import numpy as np
import dlib


img = cv2.imread('05.jpg')

cv2.imshow("image 1",img)
cv2.waitKey(0)
cv2.destroyAllWindows()

我们使用 dlib 库来识别 face,我这里是在 mac 上安装 dlib ,安装过程还是需要做些一些工作。大家里上网搜索一下有关如何在您的对应系统安装 dlib。

import cv2
import numpy as np
import dlib


img = cv2.imread('05.jpg')
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
detector = dlib.get_frontal_face_detector()
faces = detector(img_gray)

首先我们为了识别图中 face 所以先将图片进行去色处理,然后我们使用 shape_predictor_68_face_landmarks.dat 训练好的模型进行识别 face。获取好我们需要人脸识别器 detector 然后将图片传入 detector 后就得到 faces 数据。



for face in faces:
    lamdmarks = predictor(img_gray,face)

    lamdmarks_points = []

    for n in range(0,68):
        x = lamdmarks.part(n).x
        y = lamdmarks.part(n).y
        lamdmarks_points.append((x,y))
        cv2.circle(img,(x,y),3,(0,0,255))
cv2.imshow("image 1",img)
cv2.waitKey(0)
cv2.destroyAllWindows()

然后通过识别器识别图片 face 后返回数据,我们仅取 68 点然后将这些点绘制到图片上


在opencv中,通过函数convexHulll能很容易的得到一系列点的凸轮廓,比如由点组成的轮廓,通过convexHull函数,我们就能得到轮廓的凸包。下面的图就是一些点集的轮廓。


points = np.array(lamdmarks_points,np.int32)
contexhull = cv2.convexHull(points)
# print(contexhull)

cv2.polylines(img,[contexhull],True,(255,0,0), 3)

我们将所有识别面部的标识点,然后使用 convexHull 识别这些点的外部轮廓,使用 polylines 绘制面部轮廓线。


mask = np.zeros_like(img_gray)

zeros_like 根据我们图片像素矩阵形成一个全部为 0 的矩阵表示为全黑色图片。

points = np.array(lamdmarks_points,np.int32)
convexhull = cv2.convexHull(points)
cv2.polylines(img,[convexhull],True,(255,0,0), 3)
cv2.fillConvexPoly(mask,convexhull,255)

fillConvexPoly 方法将根据 convexhull 线将图片在面部轮廓内部分颜色处理为白色,从而形成一个遮罩,用于我们进行面部抠图。


face_image_1 = cv2.bitwise_and(img,img,mask=mask);

通过 bitwise_and 算法也就是将遮罩 mask 用于图片,因为黑色部分为 0 所有 0000000 与对应像素 1010101 (例)进行取和操作都是为 0 所以现实遮罩的效果


©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 今天是十二月十七日,星期一,度过了周末迎来了周一,时间过得真快,每天都感觉时候间不够用,这段时间是孩子们复习阶段,...
    晓飞_9d34阅读 1,580评论 0 3
  • “ 在风口浪尖处,猪都可以飞起来"。这是处在互联网+时代的一句标志性话语,虽烂熟于各大媒介上,但每次听到都...
    B超机想吃狗肉阅读 2,976评论 0 0
  • 通过继承实现动态代理 客户端代码:
    墨平语凡阅读 2,642评论 0 0

友情链接更多精彩内容