如何写一个简短(200行)的Python脚本

简介
在这篇文章中我将介绍如何写一个简短(200行)的 python 脚本,来自动地将一幅图片的脸替换为另一幅图片的脸。
这个过程分四步:
检测脸部标记。
旋转、缩放、平移和第二张图片,以配合第一步。
调整第二张图片的色彩平衡,以适配第一张图片。
把第二张图像的特性混合在第一张图像中。
公众号后台回复:“换脸”,获取程序完整代码。
1.使用dlib提取面部标记
该脚本使用dlib的 python 绑定来提取面部标记:
dlib 实现了 vahid kazemi 和 josephine sullivan 的《使用回归树一毫秒脸部对准》论文中的算法。算法本身非常复杂,但dlib接口使用起来非常简单:
predictor_path =/home/matt/dlib-18.16/shape_predictor_68_face_landmarks.
datdetector = dlib.get_frontal_face_detector()predictor = dlib.
shape_predictor(predictor_path)defget_landmarks(im):
rects = detector(im,1) iflen(rects) >1:
raisetoomanyfaces iflen(rects) ==0:
raisenofaces returnnumpy.matrix([[p.x, p.
y]forpinpredictor(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 分析法”解决:
deftransformation_from_points(points1, points2):
points1 = points1.astype(numpy.float64)
points2 = points2.astype(numpy.float64)
c1 = numpy.mean(points1, axis=0)
c2 = numpy.mean(points2, axis=0)
points1 -= c1
points2 -= c2
s1 = numpy.std(points1)
s2 = numpy.std(points2)
points1 /= s1
points2 /= s2
u, s, vt = numpy.linalg.svd(points1.t *
points2)
r = (u * vt).t
returnnumpy.vstack([numpy.hstack(((s2 / s1) * r,
c2.t - (s2 / s1) * r * c1.t)),
numpy.matrix([0.,0.,1.])])
代码实现了这几步:
1.将输入矩阵转换为浮点数。这是后续操作的基础。
2.每一个点集减去它的矩心。一旦为点集找到了一个最佳的缩放和旋转方法,这两个矩心c1和c2就可以用来找到完整的解决方案。
3.同样,每一个点集除以它的标准偏差。这会消除组件缩放偏差的问题。
4.使用奇异值分解计算旋转部分。可以在维基百科上看到关于解决正交 procrustes 问题的细节。
5.利用仿射变换矩阵返回完整的转化。
其结果可以插入 opencv 的cv2.warpaffine函数,将图像二映射到图像一:
def warp_im(im, m, dshape):
output_im = numpy.zeros(dshape, dtype=im.dtype) cv2.warpaffine(im,
m[:2],
(dshape[1], dshape[0]),
dst=output_im,
bordermode=cv2.border_transparent,
flags=cv2.warp_inverse_map) returnoutput_im
对齐结果如下:
3.校正第二张图像的颜色
如果我们试图直接覆盖面部特征,很快会看到这个问题:
这个问题是两幅图像之间不同的肤色和光线造成了覆盖区域的边缘不连续。我们试着修正:
colour_correct_blur_frac =0.6left_eye_points = list(range(42,48))right_eye_points = list(range(36,42))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) ifblur_amount %2==0:
blur_amount +=1 im1_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 0) *1.0
im = cv2.gaussianblur(im, (feather_amount, feather_amount),0)
returnimmask = get_face_mask(im2, landmarks2)warped_mask = warp_im(mask, m,
im1.shape)combined_mask = numpy.max([get_face_mask(im1, landmarks1),
warped_mask],
axis=0)
我们把上述过程分解:
get_face_mask()的定义是为一张图像和一个标记矩阵生成一个遮罩,它画出了两个白色的凸多边形:一个是眼睛周围的区域,一个是鼻子和嘴部周围的区域。之后它由11个像素向遮罩的边缘外部羽化扩展,可以帮助隐藏任何不连续的区域。
这样一个遮罩同时为这两个图像生成,使用与步骤2中相同的转换,可以使图像2的遮罩转化为图像1的坐标空间。
之后,通过一个element-wise最大值,这两个遮罩结合成一个。结合这两个遮罩是为了确保图像1被掩盖,而显现出图像2的特性。
最后,使用遮罩得到最终的图像:
output_im= im1 * (1.0- combined_mask) + warped_corrected_im2 * combined_mask
完整代码(link):
import cv2import dlibimport numpyimport syspredictor_path =/home/matt/dlib-18.16/shape_predictor_68_face_landmarks.
datscale_factor =1feather_amount =11face_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 usedtolineupthe images.align_points = (left_brow_points + right_eye_points + left_eye_points +
right_brow_points + nose_points + mouth_points)#
points from the second imagetooverlayonthefirst.
the convex hull of each# element willbeoverlaid.
overlay_points = [ left_eye_points + right_eye_points + left_brow_points + right_brow_points, nose_points + mouth_points,]
# amount of blurtouse during colour correction,asafraction 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):
passdef get_landmarks(im):
rects = detector(im,1) iflen(rects) >1:
raise toomanyfaces iflen(rects) ==0:
raise nofaces returnnumpy.matrix([[p.x,p.y]forpin predictor(im, rects[0]).
parts()])def annotate_landmarks(im, landmarks): im=im.copy() foridx, 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.4,
color=(0,0,255))
cv2.circle(im, pos,3, color=(0,255,255)) returnimdef 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) forgroup in overlay_points:
draw_convex_hull(im,
landmarks[group],
color=1) im= numpy.array([im,im,im]).transpose((1,2,0))
im= (cv2.gaussianblur(im, (feather_amount, feather_amount),0) >0) *1.0 im= cv2.gaussianblur(im, (feather_amount, feather_amount),0) returnimdef transformation_from_points(points1, points2):
returnanaffine transformation [s * r | t] such that:
sum ||s*r*p1,i + t - p2,i||^2 isminimized.
# solve the procrustes problem by subtracting centroids, scaling by the
# standard deviation,andthen using the svdtocalculate the rotation. see
# the followingformore 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 -= c1
points2 -= c2
s1 = numpy.std(points1)
s2 = numpy.std(points2)
points1 /= s1
points2 /= s2
u, s, vt = numpy.linalg.svd(points1.t * points2)
# the r we seekisin fact the transpose of the one given by u * vt.
this
#isbecause the above formulation assumes the matrix goesontheright
# (with row vectors) whereasour solution requires the matrixtobeonthe
#left(with column vectors).
r = (u * vt).t returnnumpy.vstack([numpy.hstack(((s2 / s1) * r,
c2.t - (s2 / s1) * r * c1.t)),
numpy.matrix([0.,0.,1.])])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) returnim, sdef warp_im(im, m, dshape): output_im = numpy.zeros(dshape, dtype=im.dtype)
cv2.warpaffine(im,
m[:2],
(dshape[1], dshape[0]),
dst=output_im,
bordermode=cv2.border_transparent,
flags=cv2.warp_inverse_map) returnoutput_imdef 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) ifblur_amount %2==0:
blur_amount +=1 im1_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) return(im2.astype(numpy.float64) * im1_blur.astype(numpy.float64) /
im2_blur.astype(numpy.float64))im1, landmarks1 = read_im_and_landmarks(sys.argv[1])
im2, landmarks2 = read_im_and_landmarks(sys.argv[2])m = transformation_from_points(landmarks1[align_points],
landmarks2[align_points])mask = get_face_mask(im2, landmarks2)warped_mask = warp_im(mask, m, im1.shape)combined_mask = numpy.max([get_face_mask(im1, landmarks1), warped_mask],
axis=0)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_maskcv2.imwrite('output.jpg', output_im)

安卓应用在更新时也能使用吗?罗永浩要退出手机圈?三星折叠屏终面世
中国联通发布了接入型光传送设备公开招募结果
基于iNEMO的车载式汽车安全检测仪方案设计
从保时捷 Mission E 公布的来看,保时捷是否比特斯拉 Model S 更好?
特斯拉用四款车型50万辆销量狠狠打了所有传统车企的脸
如何写一个简短(200行)的Python脚本
恒温恒湿试验箱低温时不稳定怎么办
315m无线模块解码程序分享
基于大数据平台的网络交付
Byte Cup 2018国际机器学习竞赛夺冠记
财富中文网发布2019年《财富》美国500强排行榜 苹果公司重回第三位
变频器输出滤波器的功能
华为推出5G随行WiFi,开启全场景5G新体验
苹果将取消iPhone 12售后福利:不再免费换新
传iPad mini 7更改屏幕装配方向,改善“果冻屏”现象
cr6842s引脚的电压参数
财科院培训中心联合易华录举办首个“数据要素资产入表理论研修”专题培训班
vivo出席2020中国移动全球合作伙伴大会 携手同创互联新生态
如何用ESP8266,ESP8285做一个WiFi中继(WiFi放大器)
无铅烙铁头的温度测量