├── LICENSE ├── README.md ├── coupleswapper.py ├── coupleswapper_gui.py ├── faceswapper.py ├── make.bat ├── male_female.ico └── readme.txt /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # FaceSwapper 2 | Python换脸系列应用。Python applications for swapping faces. 3 | -------------------------------------------------------------------------------- /coupleswapper.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Aug 10 07:56:47 2017 4 | 5 | @author: Quantum Liu 6 | """ 7 | 8 | 9 | import sys,os,traceback 10 | import cv2 11 | import dlib 12 | import numpy as np 13 | 14 | from faceswapper import Faceswapper 15 | 16 | class TooManyFaces(Exception): 17 | ''' 18 | 定位到太多脸 19 | ''' 20 | pass 21 | 22 | 23 | class NoFace(Exception): 24 | ''' 25 | 没脸 26 | ''' 27 | pass 28 | 29 | 30 | class Coupleswapper(Faceswapper): 31 | ''' 32 | 双人照人脸交换器类,继承自Faceswapper类 33 | 实例化时载入多个照片资源 34 | ''' 35 | def get_landmarks(self,im,fname,n=2): 36 | ''' 37 | 人脸定位和特征提取,定位到两张及以上脸或者没有人脸将抛出异常 38 | im: 39 | 照片的numpy数组 40 | fname: 41 | 照片名字的字符串 42 | 返回值: 43 | 人脸特征(x,y)坐标的矩阵 44 | ''' 45 | rects = self.detector(im, 1) 46 | 47 | if len(rects) >=5: 48 | raise TooManyFaces('Too many faces in '+fname) 49 | if len(rects) <2: 50 | raise NoFace('No enough face in' +fname) 51 | return [np.matrix([[p.x, p.y] for p in self.predictor(im, rect).parts()]) for rect in rects] 52 | 53 | 54 | def swap(self,im_name): 55 | ''' 56 | 主函数 人脸交换 57 | im_name 58 | 合影图片的键名字符串 59 | face_path: 60 | 脸来源的图像路径名 61 | ''' 62 | im,landmarks=self.heads[im_name] 63 | out_im=im.copy() 64 | for i in [1,-1]: 65 | landmarks_head,landmarks_face=landmarks[:2][::i] 66 | M = self.transformation_from_points(landmarks_head[self.ALIGN_POINTS], 67 | landmarks_face[self.ALIGN_POINTS]) 68 | 69 | face_mask = self.get_face_mask(im, landmarks_face) 70 | warped_mask = self.warp_im(face_mask, M, im.shape) 71 | combined_mask = np.max([self.get_face_mask(im, landmarks_head), warped_mask], 72 | axis=0) 73 | warped_face = self.warp_im(im, M, im.shape) 74 | warped_corrected_im = self.correct_colours(im, warped_face, landmarks_head) 75 | out_im=out_im * (1.0 - combined_mask) + warped_corrected_im * combined_mask 76 | return out_im 77 | if __name__=='__main__': 78 | ''' 79 | 命令行运行: 80 | python release.py [合影路径] [输出图片路径](可选,默认./output.jpg) 81 | ''' 82 | im_path,out=(sys.argv[1] if len(sys.argv)>=2 else 'trump_cp.jpg'),(sys.argv[2] if len(sys.argv)>=3 else 'output.jpg') 83 | swapper=Coupleswapper([im_path]) 84 | output_im=swapper.swap(os.path.split(im_path)[-1]) 85 | swapper.save(out,output_im) 86 | output_im[output_im>254.9]=254.9 87 | cv2.imshow('',output_im.astype('uint8')) 88 | cv2.waitKey() 89 | -------------------------------------------------------------------------------- /coupleswapper_gui.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | # Form implementation generated from reading ui file 'C:\pyprojects\faceswapper\gui.ui' 3 | # 4 | # Created by: PyQt5 UI code generator 5.9 5 | # 6 | # WARNING! All changes made in this file will be lost! 7 | 8 | import os,traceback 9 | from PyQt5.QtWidgets import QFileDialog 10 | from PyQt5 import QtCore,QtGui, QtWidgets 11 | import cv2 12 | import numpy as np 13 | from coupleswapper import Coupleswapper,TooManyFaces,NoFace 14 | 15 | class Ui_Form(QtWidgets.QMainWindow): 16 | def __init__(self): 17 | super(Ui_Form,self).__init__() 18 | self.swapper=[] 19 | self.im_path='' 20 | self.cur_im_path='' 21 | self.img_swapped=None 22 | self.img_ori=None 23 | self.compare=None 24 | 25 | def setupUi(self, Form): 26 | Form.setObjectName("Form") 27 | Form.resize(270, 360) 28 | Form.setAccessibleName("") 29 | self.verticalLayout = QtWidgets.QVBoxLayout(Form) 30 | self.verticalLayout.setObjectName("verticalLayout") 31 | Form.setWindowIcon(QtGui.QIcon('./male_female.ico')) 32 | self.help_label=QtWidgets.QLabel(Form) 33 | self.verticalLayout.addWidget(self.help_label) 34 | with open('./readme.txt','r',encoding='utf8') as f: 35 | self.readme=f.read() 36 | #显示运行log 37 | self.statu_text=QtWidgets.QTextBrowser(Form) 38 | self.vb=self.statu_text.verticalScrollBar() 39 | self.verticalLayout.addWidget(self.statu_text)#支持滚轮 40 | #加载按钮 41 | self.bt_load = QtWidgets.QPushButton(Form) 42 | self.bt_load.setDefault(True) 43 | self.bt_load.setObjectName("bt_load") 44 | self.bt_load.clicked.connect(self.load_image) 45 | self.verticalLayout.addWidget(self.bt_load) 46 | #转换按钮 47 | self.bt_swap = QtWidgets.QPushButton(Form) 48 | self.bt_swap.setDefault(True) 49 | self.bt_swap.setObjectName("bt_swap") 50 | self.bt_swap.clicked.connect(self.swap) 51 | self.verticalLayout.addWidget(self.bt_swap) 52 | #保存结果按钮 53 | self.bt_save = QtWidgets.QPushButton(Form) 54 | self.bt_save.setDefault(True) 55 | self.bt_save.setObjectName("bt_save") 56 | self.bt_save.clicked.connect(self.save_result) 57 | self.verticalLayout.addWidget(self.bt_save) 58 | #保存对比图按钮 59 | self.bt_save_comp = QtWidgets.QPushButton(Form) 60 | self.bt_save_comp.setDefault(True) 61 | self.bt_save_comp.clicked.connect(self.save_compare) 62 | self.bt_save_comp.setObjectName("bt_save_comp") 63 | self.verticalLayout.addWidget(self.bt_save_comp) 64 | 65 | 66 | self.retranslateUi(Form) 67 | QtCore.QMetaObject.connectSlotsByName(Form) 68 | 69 | def retranslateUi(self, Form): 70 | _translate = QtCore.QCoreApplication.translate 71 | Form.setWindowTitle(_translate("Form", "交换♂身体")) 72 | self.bt_load.setText(_translate("Form", "加载图片")) 73 | self.bt_swap.setText(_translate("Form", "转换")) 74 | self.bt_save.setText(_translate("Form", "保存结果")) 75 | self.bt_save_comp.setText(_translate("Form", "保存对比")) 76 | self.help_label.setText(_translate("Form",self.readme)) 77 | self.statu_text.setText(_translate('Form','欢迎使用,请选择文件')) 78 | 79 | 80 | def load_image(self): 81 | ''' 82 | 加载原图 83 | ''' 84 | try: 85 | im_path,_=QFileDialog.getOpenFileName(self,'打开图片文件','./','Image Files(*.png *.jpg *.bmp)') 86 | if not os.path.exists(im_path): 87 | return 88 | self.im_path=im_path 89 | self.statu_text.append('打开图片文件:'+self.im_path) 90 | if not self.swapper: 91 | self.swapper=Coupleswapper([self.im_path]) 92 | elif not self.im_path== self.cur_im_path: 93 | self.swapper.load_heads([self.im_path]) 94 | self.img_ori=self.swapper.heads[os.path.split(self.im_path)[-1]][0] 95 | cv2.imshow('Origin',self.img_ori) 96 | except (TooManyFaces,NoFace): 97 | self.statu_text.append(traceback.format_exc()+'\n人脸定位失败,请重新选择!保证照片中有两张可识别的人脸。') 98 | return 99 | 100 | def swap(self): 101 | ''' 102 | 执行换脸 103 | ''' 104 | if not (self.swapper and os.path.exists(self.im_path)): 105 | return 106 | self.statu_text.append('转换成功!') 107 | self.img_swapped=self.swapper.swap(os.path.split(self.im_path)[-1]) 108 | self.img_swapped[self.img_swapped>254.9]=254.9 109 | self.img_swapped=self.img_swapped.astype('uint8') 110 | cv2.imshow('Result',self.img_swapped) 111 | 112 | def save_result(self): 113 | ''' 114 | 保存结果 115 | ''' 116 | output_path,_=QFileDialog.getSaveFileName(self,'选择保存位置','./','Image Files(*.png *.jpg *.bmp)') 117 | if not output_path: 118 | self.statu_text.append('无效路径,请重新选择') 119 | return 120 | self.swapper.save(output_path,self.img_swapped) 121 | self.statu_text.append('成功保存到:'+output_path) 122 | 123 | def save_compare(self): 124 | ''' 125 | 保存对比图 126 | ''' 127 | self.compare=np.concatenate([self.img_ori,self.img_swapped],1) 128 | cv2.imshow('Compare',self.compare) 129 | output_path,_=QFileDialog.getSaveFileName(self,'选择保存位置','./','Image Files(*.png *.jpg *.bmp)') 130 | if not output_path: 131 | self.statu_text.append('无效路径,请重新选择') 132 | return 133 | self.swapper.save(output_path,self.compare) 134 | self.statu_text.append('成功保存对比图到:'+output_path) 135 | if __name__ == "__main__": 136 | import sys 137 | app = QtWidgets.QApplication(sys.argv) 138 | Form = QtWidgets.QWidget() 139 | ui = Ui_Form() 140 | ui.setupUi(Form) 141 | try: 142 | Form.show() 143 | except: 144 | traceback.print_exc() 145 | finally: 146 | cv2.destroyAllWindows() 147 | sys.exit(app.exec_()) 148 | 149 | -------------------------------------------------------------------------------- /faceswapper.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Aug 4 15:10:26 2017 4 | 5 | @author: Quantum Liu 6 | 7 | reference:https://github.com/matthewearl/faceswap 8 | """ 9 | 10 | 11 | import sys,os,traceback 12 | import cv2 13 | import dlib 14 | import numpy as np 15 | 16 | 17 | class TooManyFaces(Exception): 18 | ''' 19 | 定位到太多脸 20 | ''' 21 | pass 22 | 23 | 24 | class NoFace(Exception): 25 | ''' 26 | 没脸 27 | ''' 28 | pass 29 | 30 | 31 | class Faceswapper(): 32 | ''' 33 | 人脸交换器类 34 | 实例化时载入多个头照片资源 35 | ''' 36 | def __init__(self,heads_list=[],predictor_path="./data/shape_predictor_68_face_landmarks.dat"): 37 | ''' 38 | head_list: 39 | 头(背景和发型)来源图片的路径的字符串列表,根据此列表在实例化时载入多个头像资源, 40 | 并获得面部识别点坐标,以字典形式存储,键名为文件名 41 | predictor_path: 42 | dlib资源的路径 43 | ''' 44 | #五官等标记点 45 | self.PREDICTOR_PATH = predictor_path 46 | self.FACE_POINTS = list(range(17, 68)) 47 | self.MOUTH_POINTS = list(range(48, 61)) 48 | self.RIGHT_BROW_POINTS = list(range(17, 22)) 49 | self.LEFT_BROW_POINTS = list(range(22, 27)) 50 | self.RIGHT_EYE_POINTS = list(range(36, 42)) 51 | self.LEFT_EYE_POINTS = list(range(42, 48)) 52 | self.NOSE_POINTS = list(range(27, 35)) 53 | self.JAW_POINTS = list(range(0, 17)) 54 | 55 | # 人脸的完整标记点 56 | self.ALIGN_POINTS = (self.LEFT_BROW_POINTS + self.RIGHT_EYE_POINTS + self.LEFT_EYE_POINTS + 57 | self.RIGHT_BROW_POINTS + self.NOSE_POINTS + self.MOUTH_POINTS) 58 | 59 | # 来自第二张图(脸)的标记点,眼、眉、鼻子、嘴,这一部分标记点将覆盖第一张图的对应标记点 60 | self.OVERLAY_POINTS = [self.LEFT_EYE_POINTS + self.RIGHT_EYE_POINTS + self.LEFT_BROW_POINTS + self.RIGHT_BROW_POINTS, 61 | self.NOSE_POINTS + self.MOUTH_POINTS] 62 | 63 | # 颜色校正参数 64 | self.COLOUR_CORRECT_BLUR_FRAC = 0.6 65 | 66 | #人脸定位、特征提取器,来自dlib 67 | self.detector = dlib.get_frontal_face_detector() 68 | self.predictor = dlib.shape_predictor(self.PREDICTOR_PATH) 69 | 70 | #头像资源 71 | self.heads={} 72 | if heads_list: 73 | self.load_heads(heads_list) 74 | 75 | def load_heads(self,heads_list): 76 | ''' 77 | 根据head_list添加更多头像资源 78 | ''' 79 | self.heads.update({os.path.split(name)[-1]:(self.read_and_mark(name)) for name in heads_list}) 80 | 81 | def get_landmarks(self,im,fname,n=1): 82 | ''' 83 | 人脸定位和特征提取,定位到两张及以上脸或者没有人脸将抛出异常 84 | im: 85 | 照片的numpy数组 86 | fname: 87 | 照片名字的字符串 88 | 返回值: 89 | 人脸特征(x,y)坐标的矩阵 90 | ''' 91 | rects = self.detector(im, 1) 92 | 93 | if len(rects) > n: 94 | raise TooManyFaces('No face in '+fname) 95 | if len(rects) < 0: 96 | raise NoFace('Too many faces in '+fname) 97 | return np.matrix([[p.x, p.y] for p in self.predictor(im, rects[0]).parts()]) 98 | 99 | def read_im(self,fname,scale=1): 100 | ''' 101 | 读取图片 102 | ''' 103 | # ============================================================================= 104 | # im = cv2.imread(fname, cv2.IMREAD_COLOR) 105 | # ============================================================================= 106 | im = cv2.imdecode(np.fromfile(fname,dtype=np.uint8),-1) 107 | if type(im)==type(None): 108 | print(fname) 109 | raise ValueError('Opencv read image {} error, got None'.format(fname)) 110 | return im 111 | 112 | def read_and_mark(self,fname): 113 | im=self.read_im(fname) 114 | return im,self.get_landmarks(im,fname) 115 | 116 | def resize(self,im_head,landmarks_head,im_face,landmarks_face): 117 | ''' 118 | 根据头照片和脸照片的大小(分辨率)调整图片大小,增强融合效果 119 | ''' 120 | scale=np.sqrt((im_head.shape[0]*im_head.shape[1])/(im_face.shape[0]*im_face.shape[1])) 121 | if scale>1: 122 | im_head=cv2.resize(im_head,(int(im_head.shape[1]/scale),int(im_head.shape[0]/scale))) 123 | landmarks_head=(landmarks_head/scale).astype(landmarks_head.dtype) 124 | else: 125 | im_face=cv2.resize(im_face,(int(im_face.shape[1]*scale),int(im_face.shape[0]*scale))) 126 | landmarks_face=(landmarks_face*scale).astype(landmarks_face.dtype) 127 | return im_head,landmarks_head,im_face,landmarks_face 128 | 129 | def draw_convex_hull(self,im, points, color): 130 | ''' 131 | 勾画多凸边形 132 | ''' 133 | points = cv2.convexHull(points) 134 | cv2.fillConvexPoly(im, points, color=color) 135 | 136 | def get_face_mask(self,im, landmarks,ksize=(11,11)): 137 | ''' 138 | 获得面部遮罩 139 | ''' 140 | mask = np.zeros(im.shape[:2], dtype=np.float64) 141 | 142 | for group in self.OVERLAY_POINTS: 143 | self.draw_convex_hull(mask, 144 | landmarks[group], 145 | color=1) 146 | 147 | mask = np.array([mask, mask, mask]).transpose((1, 2, 0)) 148 | 149 | mask = (cv2.GaussianBlur(mask, ksize, 0) > 0) * 1.0 150 | mask = cv2.GaussianBlur(mask, ksize, 0) 151 | 152 | return mask 153 | 154 | def transformation_from_points(self,points1, points2): 155 | """ 156 | Return an affine transformation [s * R | T] such that: 157 | 158 | sum ||s*R*p1,i + T - p2,i||^2 159 | 160 | is minimized. 161 | 计算仿射矩阵 162 | 参考:https://github.com/matthewearl/faceswap/blob/master/faceswap.py 163 | """ 164 | # Solve the procrustes problem by subtracting centroids, scaling by the 165 | # standard deviation, and then using the SVD to calculate the rotation. See 166 | # the following for more details: 167 | # https://en.wikipedia.org/wiki/Orthogonal_Procrustes_problem 168 | 169 | points1 = points1.astype(np.float64) 170 | points2 = points2.astype(np.float64) 171 | 172 | c1 = np.mean(points1, axis=0) 173 | c2 = np.mean(points2, axis=0) 174 | points1 -= c1 175 | points2 -= c2 176 | 177 | s1 = np.std(points1) 178 | s2 = np.std(points2) 179 | points1 /= s1 180 | points2 /= s2 181 | 182 | U, S, Vt = np.linalg.svd(points1.T * points2) 183 | 184 | # The R we seek is in fact the transpose of the one given by U * Vt. This 185 | # is because the above formulation assumes the matrix goes on the right 186 | # (with row vectors) where as our solution requires the matrix to be on the 187 | # left (with column vectors). 188 | R = (U * Vt).T 189 | 190 | return np.vstack([np.hstack(((s2 / s1) * R, 191 | c2.T - (s2 / s1) * R * c1.T)), 192 | np.matrix([0., 0., 1.])]) 193 | 194 | def warp_im(self,im, M, dshape): 195 | ''' 196 | 人脸位置仿射变换 197 | ''' 198 | output_im = np.zeros(dshape, dtype=im.dtype) 199 | cv2.warpAffine(im, 200 | M[:2], 201 | (dshape[1], dshape[0]), 202 | dst=output_im, 203 | borderMode=cv2.BORDER_TRANSPARENT, 204 | flags=cv2.WARP_INVERSE_MAP) 205 | return output_im 206 | 207 | def correct_colours(self,im1, im2, landmarks_head): 208 | ''' 209 | 颜色校正 210 | ''' 211 | blur_amount = int(self.COLOUR_CORRECT_BLUR_FRAC * np.linalg.norm( 212 | np.mean(landmarks_head[self.LEFT_EYE_POINTS], axis=0) - 213 | np.mean(landmarks_head[self.RIGHT_EYE_POINTS], axis=0))) 214 | if blur_amount % 2 == 0: 215 | blur_amount += 1 216 | im1_blur = cv2.GaussianBlur(im1, (blur_amount, blur_amount), 0) 217 | im2_blur = cv2.GaussianBlur(im2, (blur_amount, blur_amount), 0) 218 | im2_blur += (128 * (im2_blur <= 1.0)).astype(im2_blur.dtype) 219 | return im2.astype(np.float64) *im1_blur.astype(np.float64) /im2_blur.astype(np.float64) 220 | 221 | def swap(self,head_name,face_path): 222 | ''' 223 | 主函数 人脸交换 224 | head_name: 225 | 头资源的键名字符串 226 | face_path: 227 | 脸来源的图像路径名 228 | ''' 229 | im_head,landmarks_head,im_face,landmarks_face=self.resize(*self.heads[head_name],*self.read_and_mark(face_path)) 230 | M = self.transformation_from_points(landmarks_head[self.ALIGN_POINTS], 231 | landmarks_face[self.ALIGN_POINTS]) 232 | 233 | face_mask = self.get_face_mask(im_face, landmarks_face) 234 | warped_mask = self.warp_im(face_mask, M, im_head.shape) 235 | combined_mask = np.max([self.get_face_mask(im_head, landmarks_head), warped_mask], 236 | axis=0) 237 | 238 | warped_face = self.warp_im(im_face, M, im_head.shape) 239 | warped_corrected_im2 = self.correct_colours(im_head, warped_face, landmarks_head) 240 | 241 | out=im_head * (1.0 - combined_mask) + warped_corrected_im2 * combined_mask 242 | return out 243 | 244 | def save(self,output_path,output_im): 245 | ''' 246 | 保存图片 247 | ''' 248 | cv2.imencode('.jpg',output_im)[1].tofile(output_path) 249 | # ============================================================================= 250 | # cv2.imwrite(os.path.abspath(output_path.encode('utf-8').decode('gbk')), output_im) 251 | # ============================================================================= 252 | 253 | if __name__=='__main__': 254 | ''' 255 | 命令行运行: 256 | python faceswapper.py <头路径> <脸路径> <输出图片路径>(可选,默认./output.jpg) 257 | ''' 258 | head,face_path,out=sys.argv[1],sys.argv[2],(sys.argv[3] if len(sys.argv)>=4 else 'output.jpg') 259 | swapper=Faceswapper([head]) 260 | output_im=swapper.swap(os.path.split(head)[-1],face_path)#返回的numpy数组 261 | swapper.save(out,output_im) 262 | output_im[output_im>254.9]=254.9 263 | cv2.imshow('',output_im.astype('uint8')) 264 | cv2.waitKey() 265 | 266 | -------------------------------------------------------------------------------- /make.bat: -------------------------------------------------------------------------------- 1 | pyinstaller -F -i malefemale.ico -p c:\Anaconda3\Lib\site-packages\PyQt5\Qt\bin coupleswapper_gui.py -y 2 | pyinstaller -F -c coupleswapper.py -n coupleswapper_console -i malefemale.ico -y 3 | copy readme.txt .\dist 4 | -------------------------------------------------------------------------------- /male_female.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/QuantumLiu/FaceSwapper/34821f6dba9690598d3f60c3a3ef1c4d410f5dd7/male_female.ico -------------------------------------------------------------------------------- /readme.txt: -------------------------------------------------------------------------------- 1 | Created on Fri Aug 4 15:10:26 2017 2 | 3 | @author: Quantum Liu 天清 4 | https://github.com/QuantumLiu/FaceSwapper 5 | reference :https://github.com/matthewearl/faceswap 6 | 7 | 说明: 8 | 首先点击“加载图片”按钮,选择需要转换的图片 9 | 点击“转换”按钮,即可完成转换 10 | 转换完成后,点击“保存结果”按钮可保存转换后的图片 11 | 点击“保存对比”则保存原图和结果的对比图。 12 | --------------------------------------------------------------------------------