1、图片效果

2、原代码

  1. # !/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. # Copyright (c) 2015 Matthew Earl
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included
  13. # in all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16. # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  18. # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19. # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  20. # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  21. # USE OR OTHER DEALINGS IN THE SOFTWARE.
  22.  
  23. """
  24. This is the code behind the Switching Eds blog post:
  25. http://matthewearl.github.io/2015/07/28/switching-eds-with-python/
  26. See the above for an explanation of the code below.
  27. To run the script you'll need to install dlib (http://dlib.net) including its
  28. Python bindings, and OpenCV. You'll also need to obtain the trained model from
  29. sourceforge:
  30. http://sourceforge.net/projects/dclib/files/dlib/v18.10/shape_predictor_68_face_landmarks.dat.bz2
  31. Unzip with `bunzip2` and change `PREDICTOR_PATH` to refer to this file. The
  32. script is run like so:
  33. ./faceswap.py <head image> <face image>
  34. If successful, a file `output.jpg` will be produced with the facial features
  35. from `<head image>` replaced with the facial features from `<face image>`.
  36. """
  37.  
  38. import cv2
  39. import dlib
  40. import numpy
  41.  
  42. import sys
  43. output = 'out3' # 输出图像名称
  44. sys.argv = ["isWap_faces.py", "./facesImage/head1.jpg", "./facesImage/head.jpg"]
  45. # PREDICTOR_PATH = "/home/matt/dlib-18.16/shape_predictor_68_face_landmarks.dat"
  46. PREDICTOR_PATH = "./model/shape_predictor_68_face_landmarks.dat"
  47. SCALE_FACTOR = 1
  48. FEATHER_AMOUNT = 11
  49.  
  50. FACE_POINTS = list(range(17, 68))
  51. MOUTH_POINTS = list(range(48, 61))
  52. RIGHT_BROW_POINTS = list(range(17, 22))
  53. LEFT_BROW_POINTS = list(range(22, 27))
  54. RIGHT_EYE_POINTS = list(range(36, 42))
  55. LEFT_EYE_POINTS = list(range(42, 48))
  56. NOSE_POINTS = list(range(27, 35))
  57. JAW_POINTS = list(range(0, 17))
  58.  
  59. # Points used to line up the images.
  60. ALIGN_POINTS = (LEFT_BROW_POINTS + RIGHT_EYE_POINTS + LEFT_EYE_POINTS +
  61. RIGHT_BROW_POINTS + NOSE_POINTS + MOUTH_POINTS)
  62.  
  63. # Points from the second image to overlay on the first. The convex hull of each
  64. # element will be overlaid.
  65. OVERLAY_POINTS = [
  66. LEFT_EYE_POINTS + RIGHT_EYE_POINTS + LEFT_BROW_POINTS + RIGHT_BROW_POINTS,
  67. NOSE_POINTS + MOUTH_POINTS,
  68. ]
  69.  
  70. # Amount of blur to use during colour correction, as a fraction of the
  71. # pupillary distance.
  72. COLOUR_CORRECT_BLUR_FRAC = 0.4
  73.  
  74. detector = dlib.get_frontal_face_detector()
  75. predictor = dlib.shape_predictor(PREDICTOR_PATH)
  76.  
  77. class TooManyFaces(Exception):
  78. pass
  79.  
  80. class NoFaces(Exception):
  81. pass
  82.  
  83. def get_landmarks(im):
  84. rects = detector(im, 1)
  85.  
  86. if len(rects) > 1:
  87. raise TooManyFaces
  88. if len(rects) == 0:
  89. raise NoFaces
  90.  
  91. return numpy.matrix([[p.x, p.y] for p in predictor(im, rects[0]).parts()])
  92.  
  93. def annotate_landmarks(im, landmarks):
  94. im = im.copy()
  95. for idx, point in enumerate(landmarks):
  96. pos = (point[0, 0], point[0, 1])
  97. cv2.putText(im, str(idx), pos,
  98. fontFace=cv2.FONT_HERSHEY_SCRIPT_SIMPLEX,
  99. fontScale=0.4,
  100. color=(0, 0, 255))
  101. cv2.circle(im, pos, 3, color=(0, 255, 255))
  102. return im
  103.  
  104. def draw_convex_hull(im, points, color):
  105. points = cv2.convexHull(points)
  106. cv2.fillConvexPoly(im, points, color=color)
  107.  
  108. def get_face_mask(im, landmarks):
  109. im = numpy.zeros(im.shape[:2], dtype=numpy.float64)
  110.  
  111. for group in OVERLAY_POINTS:
  112. draw_convex_hull(im,
  113. landmarks[group],
  114. color=1)
  115.  
  116. im = numpy.array([im, im, im]).transpose((1, 2, 0))
  117.  
  118. im = (cv2.GaussianBlur(im, (FEATHER_AMOUNT, FEATHER_AMOUNT), 0) > 0) * 1.0
  119. im = cv2.GaussianBlur(im, (FEATHER_AMOUNT, FEATHER_AMOUNT), 0)
  120.  
  121. return im
  122.  
  123. def transformation_from_points(points1, points2):
  124. """
  125. Return an affine transformation [s * R | T] such that:
  126. sum ||s*R*p1,i + T - p2,i||^2
  127. is minimized.
  128. """
  129. # Solve the procrustes problem by subtracting centroids, scaling by the
  130. # standard deviation, and then using the SVD to calculate the rotation. See
  131. # the following for more details:
  132. # https://en.wikipedia.org/wiki/Orthogonal_Procrustes_problem
  133.  
  134. points1 = points1.astype(numpy.float64)
  135. points2 = points2.astype(numpy.float64)
  136.  
  137. c1 = numpy.mean(points1, axis=0)
  138. c2 = numpy.mean(points2, axis=0)
  139. points1 -= c1
  140. points2 -= c2
  141.  
  142. s1 = numpy.std(points1)
  143. s2 = numpy.std(points2)
  144. points1 /= s1
  145. points2 /= s2
  146.  
  147. U, S, Vt = numpy.linalg.svd(points1.T * points2)
  148.  
  149. # The R we seek is in fact the transpose of the one given by U * Vt. This
  150. # is because the above formulation assumes the matrix goes on the right
  151. # (with row vectors) where as our solution requires the matrix to be on the
  152. # left (with column vectors).
  153. R = (U * Vt).T
  154.  
  155. return numpy.vstack([numpy.hstack(((s2 / s1) * R,
  156. c2.T - (s2 / s1) * R * c1.T)),
  157. numpy.matrix([0., 0., 1.])])
  158.  
  159. def read_im_and_landmarks(fname):
  160. im = cv2.imread(fname, cv2.IMREAD_COLOR)
  161. im = cv2.resize(im, (im.shape[1] * SCALE_FACTOR,
  162. im.shape[0] * SCALE_FACTOR))
  163. s = get_landmarks(im)
  164.  
  165. return im, s
  166.  
  167. def warp_im(im, M, dshape):
  168. output_im = numpy.zeros(dshape, dtype=im.dtype)
  169. cv2.warpAffine(im,
  170. M[:2],
  171. (dshape[1], dshape[0]),
  172. dst=output_im,
  173. borderMode=cv2.BORDER_TRANSPARENT,
  174. flags=cv2.WARP_INVERSE_MAP)
  175. return output_im
  176.  
  177. def correct_colours(im1, im2, landmarks1):
  178. blur_amount = COLOUR_CORRECT_BLUR_FRAC * numpy.linalg.norm(
  179. numpy.mean(landmarks1[LEFT_EYE_POINTS], axis=0) -
  180. numpy.mean(landmarks1[RIGHT_EYE_POINTS], axis=0))
  181. blur_amount = int(blur_amount)
  182. if blur_amount % 2 == 0:
  183. blur_amount += 1
  184. im1_blur = cv2.GaussianBlur(im1, (blur_amount, blur_amount), 0)
  185. im2_blur = cv2.GaussianBlur(im2, (blur_amount, blur_amount), 0)
  186.  
  187. # Avoid divide-by-zero errors.
  188. im2_blur += (128 * (im2_blur <= 1.0)).astype(im2_blur.dtype)
  189.  
  190. return (im2.astype(numpy.float64) * im1_blur.astype(numpy.float64) /
  191. im2_blur.astype(numpy.float64))
  192.  
  193. im1, landmarks1 = read_im_and_landmarks(sys.argv[1])
  194. im2, landmarks2 = read_im_and_landmarks(sys.argv[2])
  195.  
  196. M = transformation_from_points(landmarks1[ALIGN_POINTS],
  197. landmarks2[ALIGN_POINTS])
  198.  
  199. mask = get_face_mask(im2, landmarks2)
  200. warped_mask = warp_im(mask, M, im1.shape)
  201. combined_mask = numpy.max([get_face_mask(im1, landmarks1), warped_mask],
  202. axis=0)
  203.  
  204. warped_im2 = warp_im(im2, M, im1.shape)
  205. warped_corrected_im2 = correct_colours(im1, warped_im2, landmarks1)
  206.  
  207. output_im = im1 * (1.0 - combined_mask) + warped_corrected_im2 * combined_mask
  208.  
  209. cv2.imwrite('./outImage/{}.jpg'.format(output), output_im)

  

3、目录结构

python AI换脸 用普氏分析法(Procrustes Analysis)实现人脸对齐的更多相关文章

  1. Procrustes Analysis普氏分析法

    选取N幅同类目标物体的二维图像,并用上一篇博文的方法标注轮廓点,这样就得到训练样本集: 由于图像中目标物体的形状和位置存在较大偏差,因此所得到的数据并不具有仿射不变性,需要对其进行归一化处理.这里采用 ...

  2. 帕累托分析法(Pareto Analysis)(柏拉图分析)

    帕累托分析法(Pareto Analysis)(柏拉图分析) ABC分类法是由意大利经济学家帕雷托首创的.1879年,帕累托研究个人收入的分布状态图是地,发现少数人收入占全部人口收入的大部分,而多数人 ...

  3. 用200行Python代码“换脸”

    介绍 本文将介绍如何编写一个只有200行的Python脚本,为两张肖像照上人物的“换脸”. 这个过程可分为四步: 检测面部标记. 旋转.缩放和转换第二张图像,使之与第一张图像相适应. 调整第二张图像的 ...

  4. 程序员体验AI换脸就不要用ZAO了,详解Github周冠军项目Faceswap的变脸攻略

    本文链接:https://blog.csdn.net/BEYONDMA/article/details/100594136       上个月笔者曾在<银行家杂志>发文传统银行如何引领开放 ...

  5. python笔记之常用模块用法分析

    python笔记之常用模块用法分析 内置模块(不用import就可以直接使用) 常用内置函数 help(obj) 在线帮助, obj可是任何类型 callable(obj) 查看一个obj是不是可以像 ...

  6. 2017人生总结(MECE分析法)

    试着用MECE分析法对人生的整个规划做一下总结.作为技术人员,其实除了编码架构能力之外,分析问题的能力的重要程度也会随着职业发展越来越重要.<美团点评技术博客>说这几天要在黄金时段头版头条 ...

  7. 基于Python的信用评分卡模型分析(二)

    上一篇文章基于Python的信用评分卡模型分析(一)已经介绍了信用评分卡模型的数据预处理.探索性数据分析.变量分箱和变量选择等.接下来我们将继续讨论信用评分卡的模型实现和分析,信用评分的方法和自动评分 ...

  8. 从Vehicle-ReId到AI换脸,应有尽有,解你所惑

    最近在做视频搜索的技术调研,已经初步有了一些成果输出,算法准确性还可以接受,基本达到了调研的预期.现将该技术调研过程中涉及到的内容总结一篇文章分享出来,内容比较多,初看起来可能关系不大,但是如果接触面 ...

  9. TINY语言采用递归下降分析法编写语法分析程序

    目录 自顶向下分析方法 TINY文法 消左提左.构造first follow 基本思想 python构造源码 运行结果 参考来源:聊聊编译原理(二) - 语法分析 自顶向下分析方法 自顶向下分析方法: ...

随机推荐

  1. ipvsadm命令用法

    ipvsadm命令选项 -A                         添加虚拟服务器 -E                         修改虚拟服务器 -D                 ...

  2. Prism框架的Module(模块化)编程

    Prism框架用的是新版本的,Prism7.1.关于其中的变动,感兴趣的参考https://www.cnblogs.com/hicolin/p/8694892.html 如何告诉Shell(我们的宿主 ...

  3. 51 Nod1042 数字0到9的数量

    1042 数字0-9的数量  基准时间限制:1 秒 空间限制:131072 KB 分值: 10 难度:2级算法题  收藏  关注 给出一段区间a-b,统计这个区间内0-9出现的次数. 比如 10-19 ...

  4. [kuangbin带你飞]专题一 简单搜索 x

    A - 棋盘问题 POJ - 1321 在一个给定形状的棋盘(形状可能是不规则的)上面摆放棋子,棋子没有区别.要求摆放时任意的两个棋子不能放在棋盘中的同一行或者同一列,请编程求解对于给定形状和大小的棋 ...

  5. sh_16_字符串判断方法

    sh_16_字符串判断方法 # 1. 判断空白字符 space_str = " \t\n\r" print(space_str.isspace()) # 2. 判断字符串中是否只包 ...

  6. CentOS7 安装MySQL8修改密码

    1. 添加MySQL8的本地源 执行以下命令获取安装MySQL源 [root@virde ~]# wget https://repo.mysql.com//mysql80-community-rele ...

  7. template模板循环嵌套循环

    template嵌套循环写法:在第一次循环里面需要循环的地方再写个循环,把要循环的数据对象改为第一层的循环对象别名 //template模板循环嵌套循环 <script id="ban ...

  8. JAVA常见工具配置

    1.MyEclipse中配备struts.xml的自动提示 https://jingyan.baidu.com/article/9158e0004054baa2541228e2.html 2.MySQ ...

  9. Mac 10.15 关闭SIP

    升级Mac后SIP开启了,根目录不能创建文件了 关闭 sip,终端输入 sudo mount -uw / 在我们开发过程中,有时候我们安装一些工具软件需要将文件拷贝到系统限制更改的文件夹中,甚至有时需 ...

  10. jmeter也能做Webservice接口测试

    百度到天气预报接口:http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl 新增RPC接口线程 调取的参数及调取天气结果的显示 ...