日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
小200行Python代碼做了一個(gè)換臉程序

簡(jiǎn)介

在這篇文章中我將介紹如何寫一個(gè)簡(jiǎn)短(200行)的 Python 腳本,來自動(dòng)地將一幅圖片的臉替換為另一幅圖片的臉。

創(chuàng)新互聯(lián)公司憑借專業(yè)的設(shè)計(jì)團(tuán)隊(duì)扎實(shí)的技術(shù)支持、優(yōu)質(zhì)高效的服務(wù)意識(shí)和豐厚的資源優(yōu)勢(shì),提供專業(yè)的網(wǎng)站策劃、網(wǎng)站設(shè)計(jì)、成都網(wǎng)站制作、網(wǎng)站優(yōu)化、軟件開發(fā)、網(wǎng)站改版等服務(wù),在成都十多年的網(wǎng)站建設(shè)設(shè)計(jì)經(jīng)驗(yàn),為成都上千中小型企業(yè)策劃設(shè)計(jì)了網(wǎng)站。

這個(gè)過程分四步:

  • 檢測(cè)臉部標(biāo)記。

  • 旋轉(zhuǎn)、縮放、平移和第二張圖片,以配合***步。

  • 調(diào)整第二張圖片的色彩平衡,以適配***張圖片。

  • 把第二張圖像的特性混合在***張圖像中。

1.使用 dlib 提取面部標(biāo)記

該腳本使用 dlib 的 Python 綁定來提取面部標(biāo)記:

Dlib 實(shí)現(xiàn)了 Vahid Kazemi 和 Josephine Sullivan 的《使用回歸樹一毫秒臉部對(duì)準(zhǔn)》論文中的算法。算法本身非常復(fù)雜,但dlib接口使用起來非常簡(jiǎn)單:

 
 
 
 
  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()函數(shù)將一個(gè)圖像轉(zhuǎn)化成numpy數(shù)組,并返回一個(gè)68×2元素矩陣,輸入圖像的每個(gè)特征點(diǎn)對(duì)應(yīng)每行的一個(gè)x,y坐標(biāo)。

特征提取器(predictor)需要一個(gè)粗糙的邊界框作為算法輸入,由一個(gè)傳統(tǒng)的能返回一個(gè)矩形列表的人臉檢測(cè)器(detector)提供,其每個(gè)矩形列表在圖像中對(duì)應(yīng)一個(gè)臉。

2.用 Procrustes 分析調(diào)整臉部

現(xiàn)在我們已經(jīng)有了兩個(gè)標(biāo)記矩陣,每行有一組坐標(biāo)對(duì)應(yīng)一個(gè)特定的面部特征(如第30行的坐標(biāo)對(duì)應(yīng)于鼻頭)。我們現(xiàn)在要解決如何旋轉(zhuǎn)、翻譯和縮放***個(gè)向量,使它們盡可能適配第二個(gè)向量的點(diǎn)。一個(gè)想法是可以用相同的變換在***個(gè)圖像上覆蓋第二個(gè)圖像。

將這個(gè)問題數(shù)學(xué)化,尋找T,s 和 R,使得下面這個(gè)表達(dá)式:

結(jié)果最小,其中R是個(gè)2×2正交矩陣,s是標(biāo)量,T是二維向量,pi和qi是上面標(biāo)記矩陣的行。

事實(shí)證明,這類問題可以用“常規(guī) Procrustes 分析法”解決:

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

代碼實(shí)現(xiàn)了這幾步:

1.將輸入矩陣轉(zhuǎn)換為浮點(diǎn)數(shù)。這是后續(xù)操作的基礎(chǔ)。

2.每一個(gè)點(diǎn)集減去它的矩心。一旦為點(diǎn)集找到了一個(gè)***的縮放和旋轉(zhuǎn)方法,這兩個(gè)矩心 c1 和 c2 就可以用來找到完整的解決方案。

3.同樣,每一個(gè)點(diǎn)集除以它的標(biāo)準(zhǔn)偏差。這會(huì)消除組件縮放偏差的問題。

4.使用奇異值分解計(jì)算旋轉(zhuǎn)部分??梢栽诰S基百科上看到關(guān)于解決正交 Procrustes 問題的細(xì)節(jié)。

5.利用仿射變換矩陣返回完整的轉(zhuǎn)化。

其結(jié)果可以插入 OpenCV 的 cv2.warpAffine 函數(shù),將圖像二映射到圖像一:

 
 
 
 
  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 

對(duì)齊結(jié)果如下:

3.校正第二張圖像的顏色

如果我們?cè)噲D直接覆蓋面部特征,很快會(huì)看到這個(gè)問題:

這個(gè)問題是兩幅圖像之間不同的膚色和光線造成了覆蓋區(qū)域的邊緣不連續(xù)。我們?cè)囍拚?/p>

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

結(jié)果如下:

此函數(shù)試圖改變 im2 的顏色來適配 im1。它通過用 im2 除以 im2 的高斯模糊值,然后乘以im1的高斯模糊值。這里的想法是用RGB縮放校色,但并不是用所有圖像的整體常數(shù)比例因子,每個(gè)像素都有自己的局部比例因子。

用這種方法兩圖像之間光線的差異只能在某種程度上被修正。例如,如果圖像1是從一側(cè)照亮,但圖像2是被均勻照亮的,色彩校正后圖像2也會(huì)出現(xiàn)未照亮一側(cè)暗一些的問題。

也就是說,這是一個(gè)相當(dāng)簡(jiǎn)陋的辦法,而且解決問題的關(guān)鍵是一個(gè)適當(dāng)?shù)母咚购撕瘮?shù)大小。如果太小,***個(gè)圖像的面部特征將顯示在第二個(gè)圖像中。過大,內(nèi)核之外區(qū)域像素被覆蓋,并發(fā)生變色。這里的內(nèi)核用了一個(gè)0.6 *的瞳孔距離。

4.把第二張圖像的特征混合在***張圖像中

用一個(gè)遮罩來選擇圖像2和圖像1的哪些部分應(yīng)該是最終顯示的圖像:

值為1(顯示為白色)的地方為圖像2應(yīng)該顯示出的區(qū)域,值為0(顯示為黑色)的地方為圖像1應(yīng)該顯示出的區(qū)域。值在0和1之間為圖像1和圖像2的混合區(qū)域。

這是生成上圖的代碼:

 
 
 
 
  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. FEATHER_AMOUNT = 11 
  11. def draw_convex_hull(im, points, color): 
  12.     points = cv2.convexHull(points)
  13.     cv2.fillConvexPoly(im, points, color=color)  
  14. def get_face_mask(im, landmarks): 
  15.     im = numpy.zeros(im.shape[:2], dtype=numpy.float64)  
  16.     for group in OVERLAY_POINTS: 
  17.         draw_convex_hull(im, 
  18.                          landmarks[group], 
  19.                          color=1)  
  20.     im = numpy.array([im, im, im]).transpose((1, 2, 0))  
  21.     im = (cv2.GaussianBlur(im, (FEATHER_AMOUNT, FEATHER_AMOUNT), 0) > 0) * 1.0 
  22.     im = cv2.GaussianBlur(im, (FEATHER_AMOUNT, FEATHER_AMOUNT), 0)  
  23.     return im  
  24. mask = get_face_mask(im2, landmarks2) 
  25. warped_mask = warp_im(mask, M, im1.shape) 
  26. combined_mask = numpy.max([get_face_mask(im1, landmarks1), warped_mask], axis=0)  

我們把上述過程分解:

  • get_face_mask()的定義是為一張圖像和一個(gè)標(biāo)記矩陣生成一個(gè)遮罩,它畫出了兩個(gè)白色的凸多邊形:一個(gè)是眼睛周圍的區(qū)域,一個(gè)是鼻子和嘴部周圍的區(qū)域。之后它由11個(gè)像素向遮罩的邊緣外部羽化擴(kuò)展,可以幫助隱藏任何不連續(xù)的區(qū)域。

  • 這樣一個(gè)遮罩同時(shí)為這兩個(gè)圖像生成,使用與步驟2中相同的轉(zhuǎn)換,可以使圖像2的遮罩轉(zhuǎn)化為圖像1的坐標(biāo)空間。

  • 之后,通過一個(gè)element-wise***值,這兩個(gè)遮罩結(jié)合成一個(gè)。結(jié)合這兩個(gè)遮罩是為了確保圖像1被掩蓋,而顯現(xiàn)出圖像2的特性。

***,使用遮罩得到最終的圖像:

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

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

文章標(biāo)題:小200行Python代碼做了一個(gè)換臉程序
標(biāo)題URL:http://www.5511xx.com/article/cccspjp.html