实验20-智能换脸

news/2025/3/16 14:42:12/文章来源:https://www.cnblogs.com/liucaizhi/p/18233955

changeface.py

import cv2
import dlib
import numpy
import sysPREDICTOR_PATH = "./shape_predictor_68_face_landmarks.dat"
SCALE_FACTOR = 1
FEATHER_AMOUNT = 11
# 代表各个区域的关键点标号
FACE_POINTS = list(range(17, 68))
MOUTH_POINTS = list(range(48, 61))
RIGHT_BROW_POINTS = list(range(17, 22))
LEFT_BROW_POINTS = list(range(22, 27))
RIGHT_EYE_POINTS = list(range(36, 42))
LEFT_EYE_POINTS = list(range(42, 48))
NOSE_POINTS = list(range(27, 35))
JAW_POINTS = list(range(0, 17))# Points used to line up the images.   17-61
ALIGN_POINTS = (LEFT_BROW_POINTS + RIGHT_EYE_POINTS + LEFT_EYE_POINTS +RIGHT_BROW_POINTS + NOSE_POINTS + MOUTH_POINTS)# Points from the second image to overlay on the first. The convex hull of each
# element will be overlaid.   17-61
OVERLAY_POINTS = [LEFT_EYE_POINTS + RIGHT_EYE_POINTS + LEFT_BROW_POINTS + RIGHT_BROW_POINTS,NOSE_POINTS + MOUTH_POINTS,
]
# Amount of blur to use during colour correction, as a fraction of the
# pupillary distance.
COLOUR_CORRECT_BLUR_FRAC = 0.6detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(PREDICTOR_PATH)class TooManyFaces(Exception):passclass NoFaces(Exception):pass# 获取关键点坐标位置,只获取一张人脸
# input:代表一张图片的numpy array
# output:68*2的关键点坐标位置matrix
def get_landmarks(im):rects = detector(im, 1)if len(rects) > 1:raise TooManyFacesif len(rects) == 0:raise NoFacesreturn numpy.matrix([[p.x, p.y] for p in predictor(im, rects[0]).parts()])def read_im_and_landmarks(fname):im = cv2.imread(fname, cv2.IMREAD_COLOR)im = cv2.resize(im, (im.shape[1] * SCALE_FACTOR, im.shape[0] * SCALE_FACTOR))s = get_landmarks(im)return im, s# 注解关键点
def annotate_landmarks(im, landmarks):# 数组切片是原始数组的视图,这意味着数据不会被复制,视图上的任何修改都会被直接反映到源数组上.# 若想要得到的是ndarray切片的一份副本而非视图,就需要显式的进行复制操作函数copy()。im = im.copy()for idx, point in enumerate(landmarks):pos = (point[0, 0], point[0, 1])cv2.putText(im, str(idx), pos,fontFace=cv2.FONT_HERSHEY_SCRIPT_SIMPLEX,fontScale=0.2,color=(0, 0, 255))cv2.circle(im, pos, 1, color=(0, 255, 255))cv2.imwrite("landmak.jpg", im)return imdef draw_convex_hull(im, points, color):points = cv2.convexHull(points)  # 检测凸包函数cv2.fillConvexPoly(im, points, color=color)  # 绘制好多边形后并填充     点的顺序不同绘制出来的凸包也不同def get_face_mask(im, landmarks):im = numpy.zeros(im.shape[:2], dtype=numpy.float64)# for group in OVERLAY_POINTS:#     draw_convex_hull(im,landmarks[group],color=1)# 11. 下面这行代码用来替代上面两行代码draw_convex_hull(im, landmarks, color=1)im = numpy.array([im, im, im]).transpose((1, 2, 0))  # 得到一个类似于3通道的图片# 22. 高斯滤波,注释掉效果更好# im = (cv2.GaussianBlur(im, (FEATHER_AMOUNT, FEATHER_AMOUNT), 0) > 0) * 1.0# im = cv2.GaussianBlur(im, (FEATHER_AMOUNT, FEATHER_AMOUNT), 0)return im# 用普氏分析(Procrustes analysis)调整脸部
def transformation_from_points(points1, points2):"""
    Return an affine transformation [s * R | T] such that:返回一个仿射变换矩阵sum ||s*R*p1,i + T - p2,i||^2is minimized."""
    # 通过减去中心id,通过标准偏差进行缩放,然后使用SVD来计算旋转,从而解决了普是问题# Solve the procrustes problem by subtracting centroids, scaling by the# standard deviation, and then using the SVD to calculate the rotation. See# the following for more details:#   https://en.wikipedia.org/wiki/Orthogonal_Procrustes_problem
points1 = points1.astype(numpy.float64)points2 = points2.astype(numpy.float64)c1 = numpy.mean(points1, axis=0)c2 = numpy.mean(points2, axis=0)points1 -= c1points2 -= c2# 计算标准差s1 = numpy.std(points1)s2 = numpy.std(points2)points1 /= s1points2 /= s2# 通过奇异值分解求得旋转矩阵RU, S, Vt = numpy.linalg.svd(points1.T * points2)# The R we seek is in fact the transpose of the one given by U * Vt. This# is because the above formulation assumes the matrix goes on the right# (with row vectors) where as our solution requires the matrix to be on the# left (with column vectors).R = (U * Vt).T  # 维度:2*2# 仿射变换矩阵3*3 #  numpy.hstack用来在第1个维度上拼接tup  numpy.vstack在第0个维度上拼接tupreturn numpy.vstack([numpy.hstack(((s2 / s1) * R,c2.T - (s2 / s1) * R * c1.T)),numpy.matrix([0., 0., 1.])])def warp_im(im, M, dshape):output_im = numpy.zeros(dshape, dtype=im.dtype)# cv2.warpAffine(src, M, dsize[, dst[, flags[, borderMode[, borderValue ]]]])-->dstcv2.warpAffine(im, M[:2], (dshape[1], dshape[0]), dst=output_im, borderMode=cv2.BORDER_TRANSPARENT,flags=cv2.WARP_INVERSE_MAP)return output_im# 颜色校正
def correct_colours(im1, im2, landmarks1):blur_amount = COLOUR_CORRECT_BLUR_FRAC * numpy.linalg.norm(numpy.mean(landmarks1[LEFT_EYE_POINTS], axis=0) - numpy.mean(landmarks1[RIGHT_EYE_POINTS], axis=0))blur_amount = int(blur_amount)if blur_amount % 2 == 0:blur_amount += 1im1_blur = cv2.GaussianBlur(im1, (blur_amount, blur_amount), 0)im2_blur = cv2.GaussianBlur(im2, (blur_amount, blur_amount), 0)# Avoid divide-by-zero errors.im2_blur += (128 * (im2_blur <= 1.0)).astype(im2_blur.dtype)return (im2.astype(numpy.float64) * im1_blur.astype(numpy.float64) / im2_blur.astype(numpy.float64))im1, landmarks1 = read_im_and_landmarks("1.jpg")
im2, landmarks2 = read_im_and_landmarks("2.jpg")
# 44. 参数landmarks1[ALIGN_POINTS]-->landmarks1
M = transformation_from_points(landmarks1, landmarks2)  # [ALIGN_POINTS]# get_face_mask()的定义是为一张图像和一个标记矩阵生成一个掩膜
mask = get_face_mask(im2, landmarks2)
warped_mask = warp_im(mask, M, im1.shape)
# 33. 用min函数取掩膜区域效果更好
combined_mask = numpy.min([get_face_mask(im1, landmarks1), warped_mask], axis=0)
# 将图像2的掩膜转换到图像1的坐标空间
warped_im2 = warp_im(im2, M, im1.shape)
warped_corrected_im2 = correct_colours(im1, warped_im2, landmarks1)
output_im = im1 * (1.0 - combined_mask) + warped_corrected_im2 * combined_mask
cv2.imwrite('output.jpg', output_im)

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/720568.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

在线编辑涉密的Word文档,只读/禁止编辑/禁止复制/禁止另存/禁止打印

在日常办公环境中,保密信息的安全性是至关重要的,我们经常会需要在线预览编辑涉密的Word文档,但是又要求这些涉密的文档只能看,只读打开/禁止编辑/禁止复制/禁止另存/禁止打印,这时候该如何实现呢?猿大师办公助手可以帮您做到这些!猿大师办公助手可以把本地微软Office或…

实验19-使用keras完成语音识别

wavs_to_model.pyimport wave import numpy as np import osimport keras from keras.models import Sequential from keras.layers import Densenum_class = 0 # 加载的语音文件有几种类别 labsIndName=[] ## 训练集标签的名字 ["seven","stop"]# …

使用Wesky.Net.Opentools库,一行代码实现实体类类型转换为Json格式字符串

安装1.0.10以及以上版本的 Wesky.Net.OpenTools 包 包内,该功能的核心代码如下: 自定义属性:实体类JSON模式生成器: 使用方式:引用上面的1.0.10版本或以上的包。如果实体类有特殊需求,例如映射为其他名称,可以用OpenJson属性来实现。实体类对象案例如下:上面实体类,…

RFS_Server_06 上传并发布数据

操作描述:云服务器Ubuntu20.04系统Docker中有两个容器:Postgres容器和GeoServer容器。将数据存储至Postgres数据库容器中,并通过GeoServer连接,发布地图服务。 此文档中使用的Postgres数据库名称为pg01,GeoServer服务器名称为geoserver01。 1 基础操作:使用工具连接云…

vivado与modelsim联合仿真

写在前面:联合仿真需要版本对应,我的2020的modelsim和2020的vivado是可以用的。如果不对应,下边会编译报错。 第一步,编译仿真库文件。点击菜单栏Tools-->Compile Sim Libary,第一行Simulator选择Modelsim接下来Family选择你需要的器件对应的Family。Compiled library …

深度学习--风格迁移 原理以及实现--84

目录1. 简介4. 损失函数 参考链接:https://blog.csdn.net/ssshyeong/article/details/127092354 1. 简介 Image Style Transfer Using Convolutional Neural Networks:Gram矩阵(CVPR2016) 链接 Texture Synthesis Using Convolutional Neural Networks 图像经过卷积层后得到的…

Body AdvancedBrep Geometry

Body AdvancedBrep Geometry Body Brep Geometry是通过边界表示模型(包括NURBS)表示产品的三维形状。应使用保持该几何表示的IfcShapeResentation的以下属性值:IfcShapeRepresentation.RepresentationIdentifier = Body IfcShapeRepresentation.RepresentationType = Advanc…

node.js + mysql实现基本的增删改查功能(保姆级教程---2优化版)

node.js + mysql实现基本的增删改查(保姆级教程---2优化版)上一个实现对增删改查功能都写在同一个文件里,代码过于冗余,我认为可以优化,分开写在不同文件里面,使得更加直观。废话不多说,直接进入主题:对之前的代码进行抽离:db.js文件(用于数据库的连接,并导出连接供…

虚幻中实现本地双人的输入设备分别控制需要的Pawn

想要实现双人成行游戏中的双输入设备(双输入设备指的是一个键鼠和一个手柄,或者两个手柄)分别控制玩家1和玩家2,同时可以动态插拔设备切换对应的Pawn的控制权;本文是对探索并实现此功能的一个解决思路记录。1、前期准备和知识点梳理 1.1 本地多玩家 LocalPlayer 平常我们运…

HiPPO: Recurrent Memory with Optimal Polynomial Projections

目录概Motivation代码Gu A., Dao T., Ermon S., Rudra A. and Re C. HiPPO: Recurrent memory with optimal polynomial projections. NIPS, 2021.概 看下最近很火的 Mamba 的前身. 本文其实主要介绍的是一个如何建模历史信息在正交基上的稀疏的变化情况.Motivation对于一个函数…

存储引擎及特点、约束条件、严格模式、基本字段类型(整型、浮点型、字符串、日期时间、枚举和集合)

【一】存储引擎在平常我们处理的文件格式有很多,并且针对不同的文件格式会有对应不同的存储方式和处理机制 针对不同的数据应该有对应不同的处理机制 存储引擎就是不同的处理机制。# 查看所有引擎 show engines;四种主要的存储引擎 (1)Innodb引擎是MySQL5.5版本之后的默认存…