小200行Python代码做了一个换脸程序

开发 后端
在这篇文章中我将介绍如何写一个简短(200行)的 Python 脚本,来自动地将一幅图片的脸替换为另一幅图片的脸。
[[223384]]

简介

在这篇文章中我将介绍如何写一个简短(200行)的 Python 脚本,来自动地将一幅图片的脸替换为另一幅图片的脸。

这个过程分四步:

  • 检测脸部标记。

  • 旋转、缩放、平移和第二张图片,以配合***步。

  • 调整第二张图片的色彩平衡,以适配***张图片。

  • 把第二张图像的特性混合在***张图像中。

1.使用 dlib 提取面部标记

该脚本使用 dlib 的 Python 绑定来提取面部标记:

 

[[223385]]

Dlib 实现了 Vahid Kazemi 和 Josephine Sullivan 的《使用回归树一毫秒脸部对准》论文中的算法。算法本身非常复杂,但dlib接口使用起来非常简单: 

  1. PREDICTOR_PATH = "/home/matt/dlib-18.16/shape_predictor_68_face_landmarks.dat"   
  2. detector = dlib.get_frontal_face_detector()  
  3. predictor = dlib.shape_predictor(PREDICTOR_PATH)   
  4. def get_landmarks(im):  
  5.     rects = detector(im, 1)  
  6.     if len(rects) > 1:  
  7.         raise TooManyFaces  
  8.     if len(rects) == 0:  
  9.         raise NoFaces  
  10.     return numpy.matrix([[p.x, p.y] for p in predictor(im, rects[0]).parts()])   

get_landmarks()函数将一个图像转化成numpy数组,并返回一个68×2元素矩阵,输入图像的每个特征点对应每行的一个x,y坐标。

特征提取器(predictor)需要一个粗糙的边界框作为算法输入,由一个传统的能返回一个矩形列表的人脸检测器(detector)提供,其每个矩形列表在图像中对应一个脸。

2.用 Procrustes 分析调整脸部

现在我们已经有了两个标记矩阵,每行有一组坐标对应一个特定的面部特征(如第30行的坐标对应于鼻头)。我们现在要解决如何旋转、翻译和缩放***个向量,使它们尽可能适配第二个向量的点。一个想法是可以用相同的变换在***个图像上覆盖第二个图像。

将这个问题数学化,寻找T,s 和 R,使得下面这个表达式:

结果最小,其中R是个2×2正交矩阵,s是标量,T是二维向量,pi和qi是上面标记矩阵的行。

事实证明,这类问题可以用“常规 Procrustes 分析法”解决:

  1. def transformation_from_points(points1, points2):  
  2.     points1 = points1.astype(numpy.float64)  
  3.     points2 = points2.astype(numpy.float64)   
  4.  
  5.     c1 = numpy.mean(points1, axis=0)  
  6.     c2 = numpy.mean(points2, axis=0)  
  7.     points1 -= c1  
  8.     points2 -= c2   
  9.  
  10.     s1 = numpy.std(points1)  
  11.     s2 = numpy.std(points2)  
  12.     points1 /= s1  
  13.     points2 /= s2   
  14.  
  15.     U, S, Vt = numpy.linalg.svd(points1.T * points2)  
  16.     R = (U * Vt).T   
  17.  
  18.     return numpy.vstack([numpy.hstack(((s2 / s1) * R,  
  19.                                        c2.T - (s2 / s1) * R * c1.T)),  
  20.                          numpy.matrix([0., 0., 1.])])  

代码实现了这几步:

1.将输入矩阵转换为浮点数。这是后续操作的基础。

2.每一个点集减去它的矩心。一旦为点集找到了一个***的缩放和旋转方法,这两个矩心 c1 和 c2 就可以用来找到完整的解决方案。

3.同样,每一个点集除以它的标准偏差。这会消除组件缩放偏差的问题。

4.使用奇异值分解计算旋转部分。可以在维基百科上看到关于解决正交 Procrustes 问题的细节。

5.利用仿射变换矩阵返回完整的转化。

其结果可以插入 OpenCV 的 cv2.warpAffine 函数,将图像二映射到图像一:

  1. def warp_im(im, M, dshape):  
  2.     output_im = numpy.zeros(dshape, dtype=im.dtype)  
  3.     cv2.warpAffine(im,  
  4.                    M[:2],  
  5.                    (dshape[1], dshape[0]),  
  6.                    dst=output_im,  
  7.                    borderMode=cv2.BORDER_TRANSPARENT,  
  8.                    flags=cv2.WARP_INVERSE_MAP)  
  9.     return output_im  

对齐结果如下:

[[223387]]

3.校正第二张图像的颜色

如果我们试图直接覆盖面部特征,很快会看到这个问题:

 

[[223388]]

这个问题是两幅图像之间不同的肤色和光线造成了覆盖区域的边缘不连续。我们试着修正: 

  1. COLOUR_CORRECT_BLUR_FRAC = 0.6  
  2. LEFT_EYE_POINTS = list(range(42, 48))  
  3. RIGHT_EYE_POINTS = list(range(36, 42))   
  4.  
  5. def correct_colours(im1, im2, landmarks1):  
  6.     blur_amount = COLOUR_CORRECT_BLUR_FRAC * numpy.linalg.norm(  
  7.                               numpy.mean(landmarks1[LEFT_EYE_POINTS], axis=0) -  
  8.                               numpy.mean(landmarks1[RIGHT_EYE_POINTS], axis=0))  
  9.     blur_amount = int(blur_amount)  
  10.     if blur_amount % 2 == 0:  
  11.         blur_amount += 1  
  12.     im1_blur = cv2.GaussianBlur(im1, (blur_amount, blur_amount), 0)  
  13.     im2_blur = cv2.GaussianBlur(im2, (blur_amount, blur_amount), 0)   
  14.  
  15.     # Avoid divide-by-zero errors.  
  16.     im2_blur += 128 * (im2_blur <= 1.0)   
  17.  
  18.     return (im2.astype(numpy.float64) * im1_blur.astype(numpy.float64) / 
  19.  
  20.                                                 im2_blur.astype(numpy.float64))  

结果如下:

 

[[223389]]

此函数试图改变 im2 的颜色来适配 im1。它通过用 im2 除以 im2 的高斯模糊值,然后乘以im1的高斯模糊值。这里的想法是用RGB缩放校色,但并不是用所有图像的整体常数比例因子,每个像素都有自己的局部比例因子。

用这种方法两图像之间光线的差异只能在某种程度上被修正。例如,如果图像1是从一侧照亮,但图像2是被均匀照亮的,色彩校正后图像2也会出现未照亮一侧暗一些的问题。

也就是说,这是一个相当简陋的办法,而且解决问题的关键是一个适当的高斯核函数大小。如果太小,***个图像的面部特征将显示在第二个图像中。过大,内核之外区域像素被覆盖,并发生变色。这里的内核用了一个0.6 *的瞳孔距离。

4.把第二张图像的特征混合在***张图像中

用一个遮罩来选择图像2和图像1的哪些部分应该是最终显示的图像:

 

[[223390]]

值为1(显示为白色)的地方为图像2应该显示出的区域,值为0(显示为黑色)的地方为图像1应该显示出的区域。值在0和1之间为图像1和图像2的混合区域。

这是生成上图的代码: 

  1. LEFT_EYE_POINTS = list(range(42, 48))  
  2. RIGHT_EYE_POINTS = list(range(36, 42))  
  3. LEFT_BROW_POINTS = list(range(22, 27))  
  4. RIGHT_BROW_POINTS = list(range(17, 22))  
  5. NOSE_POINTS = list(range(27, 35))  
  6. MOUTH_POINTS = list(range(48, 61))  
  7. OVERLAY_POINTS = [  
  8.     LEFT_EYE_POINTS + RIGHT_EYE_POINTS + LEFT_BROW_POINTS + RIGHT_BROW_POINTS,  
  9.     NOSE_POINTS + MOUTH_POINTS,  
  10.  
  11. FEATHER_AMOUNT = 11  
  12.  
  13. def draw_convex_hull(im, points, color):  
  14.     points = cv2.convexHull(points) 
  15.     cv2.fillConvexPoly(im, points, color=color)   
  16.  
  17. def get_face_mask(im, landmarks):  
  18.     im = numpy.zeros(im.shape[:2], dtype=numpy.float64)   
  19.  
  20.     for group in OVERLAY_POINTS:  
  21.         draw_convex_hull(im,  
  22.                          landmarks[group],  
  23.                          color=1)   
  24.  
  25.     im = numpy.array([im, im, im]).transpose((1, 2, 0))   
  26.  
  27.     im = (cv2.GaussianBlur(im, (FEATHER_AMOUNT, FEATHER_AMOUNT), 0) > 0) * 1.0  
  28.     im = cv2.GaussianBlur(im, (FEATHER_AMOUNT, FEATHER_AMOUNT), 0)   
  29.  
  30.     return im   
  31.  
  32. mask = get_face_mask(im2, landmarks2)  
  33. warped_mask = warp_im(mask, M, im1.shape)  
  34. combined_mask = numpy.max([get_face_mask(im1, landmarks1), warped_mask], axis=0)   

我们把上述过程分解:

  • get_face_mask()的定义是为一张图像和一个标记矩阵生成一个遮罩,它画出了两个白色的凸多边形:一个是眼睛周围的区域,一个是鼻子和嘴部周围的区域。之后它由11个像素向遮罩的边缘外部羽化扩展,可以帮助隐藏任何不连续的区域。

  • 这样一个遮罩同时为这两个图像生成,使用与步骤2中相同的转换,可以使图像2的遮罩转化为图像1的坐标空间。

  • 之后,通过一个element-wise***值,这两个遮罩结合成一个。结合这两个遮罩是为了确保图像1被掩盖,而显现出图像2的特性。

***,使用遮罩得到最终的图像:  

  1. output_im = im1 * (1.0 - combined_mask) + warped_corrected_im2 * combined_mask   

 

[[223391]]

完整代码(link):

  1. import cv2 
  2. import dlib 
  3. import numpy 
  4.   
  5. import sys 
  6.   
  7. PREDICTOR_PATH = "/home/matt/dlib-18.16/shape_predictor_68_face_landmarks.dat" 
  8. SCALE_FACTOR = 1 
  9. FEATHER_AMOUNT = 11 
  10.   
  11. FACE_POINTS = list(range(17, 68)) 
  12. MOUTH_POINTS = list(range(48, 61)) 
  13. RIGHT_BROW_POINTS = list(range(17, 22)) 
  14. LEFT_BROW_POINTS = list(range(22, 27)) 
  15. RIGHT_EYE_POINTS = list(range(36, 42)) 
  16. LEFT_EYE_POINTS = list(range(42, 48)) 
  17. NOSE_POINTS = list(range(27, 35)) 
  18. JAW_POINTS = list(range(0, 17)) 
  19.   
  20. # Points used to line up the images. 
  21. ALIGN_POINTS = (LEFT_BROW_POINTS + RIGHT_EYE_POINTS + LEFT_EYE_POINTS + 
  22.                                RIGHT_BROW_POINTS + NOSE_POINTS + MOUTH_POINTS) 
  23.   
  24. # Points from the second image to overlay on the first. The convex hull of each 
  25. # element will be overlaid. 
  26. OVERLAY_POINTS = [ 
  27.     LEFT_EYE_POINTS + RIGHT_EYE_POINTS + LEFT_BROW_POINTS + RIGHT_BROW_POINTS, 
  28.     NOSE_POINTS + MOUTH_POINTS, 
  29.   
  30. # Amount of blur to use during colour correction, as a fraction of the 
  31. # pupillary distance. 
  32. COLOUR_CORRECT_BLUR_FRAC = 0.6 
  33.   
  34. detector = dlib.get_frontal_face_detector() 
  35. predictor = dlib.shape_predictor(PREDICTOR_PATH) 
  36.   
  37. class TooManyFaces(Exception): 
  38.     pass 
  39.   
  40. class NoFaces(Exception): 
  41.     pass 
  42.   
  43. def get_landmarks(im): 
  44.     rects = detector(im, 1) 
  45.   
  46.     if len(rects) > 1: 
  47.         raise TooManyFaces 
  48.     if len(rects) == 0: 
  49.         raise NoFaces 
  50.   
  51.     return numpy.matrix([[p.x, p.y] for p in predictor(im, rects[0]).parts()]) 
  52.   
  53. def annotate_landmarks(im, landmarks): 
  54.     im = im.copy() 
  55.     for idx, point in enumerate(landmarks): 
  56.         pos = (point[0, 0], point[0, 1]) 
  57.         cv2.putText(im, str(idx), pos, 
  58.                     fontFace=cv2.FONT_HERSHEY_SCRIPT_SIMPLEX, 
  59.                     fontScale=0.4, 
  60.                     color=(0, 0, 255)) 
  61.         cv2.circle(im, pos, 3, color=(0, 255, 255)) 
  62.     return im 
  63.   
  64. def draw_convex_hull(im, points, color): 
  65.     points = cv2.convexHull(points) 
  66.     cv2.fillConvexPoly(im, points, color=color) 
  67.   
  68. def get_face_mask(im, landmarks): 
  69.     im = numpy.zeros(im.shape[:2], dtype=numpy.float64) 
  70.   
  71.     for group in OVERLAY_POINTS: 
  72.         draw_convex_hull(im, 
  73.                          landmarks[group], 
  74.                          color=1) 
  75.   
  76.     im = numpy.array([im, im, im]).transpose((1, 2, 0)) 
  77.   
  78.     im = (cv2.GaussianBlur(im, (FEATHER_AMOUNT, FEATHER_AMOUNT), 0) > 0) * 1.0 
  79.     im = cv2.GaussianBlur(im, (FEATHER_AMOUNT, FEATHER_AMOUNT), 0) 
  80.   
  81.     return im 
  82.   
  83. def transformation_from_points(points1, points2): 
  84.     ""
  85.     Return an affine transformation [s * R | T] such that: 
  86.         sum ||s*R*p1,i + T - p2,i||^2 
  87.     is minimized. 
  88.     ""
  89.     # Solve the procrustes problem by subtracting centroids, scaling by the 
  90.     # standard deviation, and then using the SVD to calculate the rotation. See 
  91.     # the following for more details: 
  92.     #   https://en.wikipedia.org/wiki/Orthogonal_Procrustes_problem 
  93.   
  94.     points1 = points1.astype(numpy.float64) 
  95.     points2 = points2.astype(numpy.float64) 
  96.   
  97.     c1 = numpy.mean(points1, axis=0) 
  98.     c2 = numpy.mean(points2, axis=0) 
  99.     points1 -= c1 
  100.     points2 -= c2 
  101.   
  102.     s1 = numpy.std(points1) 
  103.     s2 = numpy.std(points2) 
  104.     points1 /= s1 
  105.     points2 /= s2 
  106.   
  107.     U, S, Vt = numpy.linalg.svd(points1.T * points2) 
  108.   
  109.     # The R we seek is in fact the transpose of the one given by U * Vt. This 
  110.     # is because the above formulation assumes the matrix goes on the right 
  111.     # (with row vectors) where as our solution requires the matrix to be on the 
  112.     # left (with column vectors). 
  113.     R = (U * Vt).T 
  114.   
  115.     return numpy.vstack([numpy.hstack(((s2 / s1) * R, 
  116.                                        c2.T - (s2 / s1) * R * c1.T)), 
  117.                          numpy.matrix([0., 0., 1.])]) 
  118.   
  119. def read_im_and_landmarks(fname): 
  120.     im = cv2.imread(fname, cv2.IMREAD_COLOR) 
  121.     im = cv2.resize(im, (im.shape[1] * SCALE_FACTOR, 
  122.                          im.shape[0] * SCALE_FACTOR)) 
  123.     s = get_landmarks(im) 
  124.   
  125.     return im, s 
  126.   
  127. def warp_im(im, M, dshape): 
  128.     output_im = numpy.zeros(dshape, dtype=im.dtype) 
  129.     cv2.warpAffine(im, 
  130.                    M[:2], 
  131.                    (dshape[1], dshape[0]), 
  132.                    dst=output_im, 
  133.                    borderMode=cv2.BORDER_TRANSPARENT, 
  134.                    flags=cv2.WARP_INVERSE_MAP) 
  135.     return output_im 
  136.   
  137. def correct_colours(im1, im2, landmarks1): 
  138.     blur_amount = COLOUR_CORRECT_BLUR_FRAC * numpy.linalg.norm( 
  139.                               numpy.mean(landmarks1[LEFT_EYE_POINTS], axis=0) - 
  140.                               numpy.mean(landmarks1[RIGHT_EYE_POINTS], axis=0)) 
  141.     blur_amount = int(blur_amount) 
  142.     if blur_amount % 2 == 0: 
  143.         blur_amount += 1 
  144.     im1_blur = cv2.GaussianBlur(im1, (blur_amount, blur_amount), 0) 
  145.     im2_blur = cv2.GaussianBlur(im2, (blur_amount, blur_amount), 0) 
  146.   
  147.     # Avoid divide-by-zero errors. 
  148.     im2_blur += 128 * (im2_blur <= 1.0) 
  149.   
  150.     return (im2.astype(numpy.float64) * im1_blur.astype(numpy.float64) / 
  151.                                                 im2_blur.astype(numpy.float64)) 
  152.   
  153. im1, landmarks1 = read_im_and_landmarks(sys.argv[1]) 
  154. im2, landmarks2 = read_im_and_landmarks(sys.argv[2]) 
  155.   
  156. M = transformation_from_points(landmarks1[ALIGN_POINTS], 
  157.                                landmarks2[ALIGN_POINTS]) 
  158.   
  159. mask = get_face_mask(im2, landmarks2) 
  160. warped_mask = warp_im(mask, M, im1.shape) 
  161. combined_mask = numpy.max([get_face_mask(im1, landmarks1), warped_mask], 
  162.                           axis=0) 
  163.   
  164. warped_im2 = warp_im(im2, M, im1.shape) 
  165. warped_corrected_im2 = correct_colours(im1, warped_im2, landmarks1) 
  166.   
  167. output_im = im1 * (1.0 - combined_mask) + warped_corrected_im2 * combined_mask 
  168.   
  169. cv2.imwrite('output.jpg', output_im)  

 

责任编辑:庞桂玉 来源: Python开发者
相关推荐

2020-05-11 17:12:52

换脸Python图像

2015-08-10 11:09:09

Python代码Python

2023-11-29 08:10:36

javascriptH5游戏

2018-02-06 10:04:59

2013-03-04 10:22:30

Python

2021-04-19 11:16:17

小程序微信开发

2014-01-09 09:42:56

Python语言检测器

2022-03-23 10:21:56

Python代码工具

2023-12-25 15:28:57

Python工具pywebio

2014-05-15 09:45:58

Python解析器

2021-04-29 15:53:21

AI 数据人工智能

2019-05-15 10:23:58

AI人工智能视频换脸技术

2021-04-26 09:04:13

Python 代码音乐

2018-05-25 16:23:00

Python代码工具

2016-09-27 17:29:23

腾讯云小程序微信

2009-06-11 10:59:19

netbeans提示

2016-09-30 09:22:55

2022-01-26 16:30:47

代码虚拟机Linux

2017-03-28 21:03:35

代码React.js

2016-12-02 08:53:18

Python一行代码
点赞
收藏

51CTO技术栈公众号