当前位置:   article > 正文

[OpenCV实战]22 使用EigenFaces进行人脸重建_opencv 重构人物图像案例

opencv 重构人物图像案例

目录

1 背景

1.1 什么是EigenFaces?

1.2 坐标的变化

2 面部重建

2.1 计算新面部图像的PCA权重

2.2 使用EigenFaces进行面部重建

3 参考


在这篇文章中,我们将学习如何使用EigenFaces实现人脸重建。我们需要了解主成分分析(PCA)和EigenFaces。

1 背景

1.1 什么是EigenFaces

在我们之前的文章中,我们解释了Eigenfaces是可以添加到平均(平均)面部以创建新的面部图像的图像。我们可以用数学方式写这个,

其中

F是一张新生成的脸部图像;

Fm是平均人脸图像;

Fi是一个EigenFace(特征脸);

https://img-blog.csdnimg.cn/20190423194122119.png 是我们可以选择创建新图的标量系数权重,可正可负。

在我们之前的文章中,我们解释了如何计算EigenFaces,如何解释它们以及如何通过改变权重来创建新面孔。

现在假设,我们将获得一张新的面部照片,如下图所示。我们如何使用EigenFaces重建照片F?换句话说,我们如何找到在上面的等式中使用的权重将产生面部图像作为输出?这正是本文所涉及的问题,但在我们尝试这样做之前,我们需要一些线性代数背景。下图左侧是原始图像。左边的第二个图像是使用250个EigenFaces构建的,第三个图像使用1000个Eigenfaces,最右边的图像使用4000个Eigenfaces。

1.2 坐标的变化

在一个三维坐标系中,坐标轴x,y,z由下图中黑色线条表示。您可以想象相对于原始的x,y,z帧,以(xo, yo, zo)点进行旋转和平移,获得另一组垂直轴。在图2中,我们以蓝色显示该旋转和平移坐标系的轴X'Y'Z’。在X,Y,Z坐标系的点(x,y,z)用红点表示。我们如何找到X'Y'Z'坐标系中点(x',y',z')的坐标?这可以分两步完成。

转换:首先,我们可以以原坐标系点(x,y,z)通过减去新坐标系的原点(xo,yo,zo)来实现平移,所以我们有了一个新的向量(x-xo,y-yo,z-zo)。

投影:接下来,我们需要将(x-xo,y-yo,z-zo)投影到x',y',z'上,它只是(x-xo,y-yo,z-zo)的点积,方向分别为x',y'和z'。下图中的绿线显示了红点到Z'轴上的投影。让我们看看这种技术如何应用于人脸重建。

面部重建

2.1 计算新面部图像的PCA权重

正如我们在上一篇文章中所看到的,为了计算面部数据的主要成分,我们将面部图像转换为长矢量。例如,如果我们有一组尺寸为100x100x3的对齐面部图像,则每个图像可以被认为是长度为100x100x3=30000的矢量。就像三个数字的元组(x,y,z)代表3D空间中的一个点一样,我们可以说长度为30,000的向量是30,000维空间中的一个点。这个高维空间的轴线就像维坐标轴xyz彼此垂直一样。主成分(特征向量)在这个高维空间中形成一个新的坐标系,新的原点是主成分分析向量平均值。

给定一个新图像,我们找到权重流程如下:

1)矢量化图像:我们首先从图像数据创建一个长矢量。这很简单,重新排列数据只需要一行或两行代码。

2)减去平均向量.

3)主成分映射:这可以通过计算每个主分量与平均向量的差的点积来实现。所给出的点积结果就是权重

4)组合向量:一旦计算了权重,我们可以简单地将每个权重乘以主成分并将它们加在一起。最后,我们需要将平均人脸向量添加到此总和中。

5)将矢量重置为人脸图像:作为上一步的结果,我们获得了一个30k长的矢量,并且可以将其重新整形为100 x 100 x 3图像。这是最终的图像。

在我们的示例中,100 x 100 x 3图像具有30k尺寸。在对2000个图像进行PCA之后,我们可以获得2000维的空间,并且能够以合理的精度水平重建新面部。过去采用30k数字表示的内容现在仅使用2k个数字表示。换句话说,我们只是使用PCA来减少面部空间的尺寸。

2.2 使用EigenFaces进行面部重建

假设您已下载代码,我们将查看代码的重要部分。首先,在文件createPCAModel.cpp和createPCAModel.py中共享用于计算平均人脸和EigenFaces的代码。我们在上一篇文章中解释了该方法,因此我们将跳过该解释。相反,我们将讨论reconstructFace.cpp和reconstructFace.py。

代码如下:

C++:

  1. #include "pch.h"
  2. #include <iostream>
  3. #include <fstream>
  4. #include <sstream>
  5. #include <opencv2/opencv.hpp>
  6. #include <stdlib.h>
  7. #include <time.h>
  8. using namespace cv;
  9. using namespace std;
  10. // Matrices for average (mean) and eigenvectors
  11. Mat averageFace;
  12. Mat output;
  13. vector<Mat> eigenFaces;
  14. Mat imVector, meanVector, eigenVectors, im, display;
  15. // Display result
  16. // Left = Original Image
  17. // Right = Reconstructed Face
  18. void displayResult( Mat &left, Mat &right)
  19. {
  20. hconcat(left,right, display);
  21. resize(display, display, Size(), 4, 4);
  22. imshow("Result", display);
  23. }
  24. // Recontruct face using mean face and EigenFaces
  25. void reconstructFace(int sliderVal, void*)
  26. {
  27. // Start with the mean / average face
  28. Mat output = averageFace.clone();
  29. for (int i = 0; i < sliderVal; i++)
  30. {
  31. // The weight is the dot product of the mean subtracted
  32. // image vector with the EigenVector
  33. double weight = imVector.dot(eigenVectors.row(i));
  34. // Add weighted EigenFace to the output
  35. output = output + eigenFaces[i] * weight;
  36. }
  37. displayResult(im, output);
  38. }
  39. int main(int argc, char **argv)
  40. {
  41. // Read model file
  42. string modelFile("pcaParams.yml");
  43. cout << "Reading model file " << modelFile << " ... " ;
  44. FileStorage file(modelFile, FileStorage::READ);
  45. // Extract mean vector
  46. meanVector = file["mean"].mat();
  47. // Extract Eigen Vectors
  48. eigenVectors = file["eigenVectors"].mat();
  49. // Extract size of the images used in training.
  50. Mat szMat = file["size"].mat();
  51. Size sz = Size(szMat.at<double>(1,0),szMat.at<double>(0,0));
  52. // Extract maximum number of EigenVectors.
  53. // This is the max(numImagesUsedInTraining, w * h * 3)
  54. // where w = width, h = height of the training images.
  55. int numEigenFaces = eigenVectors.size().height;
  56. cout << "DONE" << endl;
  57. cout << "Extracting mean face and eigen faces ... ";
  58. // Extract mean vector and reshape it to obtain average face
  59. averageFace = meanVector.reshape(3,sz.height);
  60. // Reshape Eigenvectors to obtain EigenFaces
  61. for(int i = 0; i < numEigenFaces; i++)
  62. {
  63. Mat row = eigenVectors.row(i);
  64. Mat eigenFace = row.reshape(3,sz.height);
  65. eigenFaces.push_back(eigenFace);
  66. }
  67. cout << "DONE" << endl;
  68. // Read new test image. This image was not used in traning.
  69. string imageFilename("test/satya1.jpg");
  70. cout << "Read image " << imageFilename << " and vectorize ... ";
  71. im = imread(imageFilename);
  72. im.convertTo(im, CV_32FC3, 1/255.0);
  73. // Reshape image to one long vector and subtract the mean vector
  74. imVector = im.clone();
  75. imVector = imVector.reshape(1, 1) - meanVector;
  76. cout << "DONE" << endl;
  77. // Show mean face first
  78. output = averageFace.clone();
  79. cout << "Usage:" << endl
  80. << "\tChange the slider to change the number of EigenFaces" << endl
  81. << "\tHit ESC to terminate program." << endl;
  82. namedWindow("Result", CV_WINDOW_AUTOSIZE);
  83. int sliderValue;
  84. // Changing the slider value changes the number of EigenVectors
  85. // used in reconstructFace.
  86. createTrackbar( "No. of EigenFaces", "Result", &sliderValue, numEigenFaces, reconstructFace);
  87. // Display original image and the reconstructed image size by side
  88. displayResult(im, output);
  89. waitKey(0);
  90. destroyAllWindows();
  91. return 0;
  92. }

Python:

  1. # Import necessary packages
  2. import os
  3. import sys
  4. import cv2
  5. import numpy as np
  6. '''
  7. Display result
  8. Left = Original Image
  9. Right = Reconstructed Face
  10. '''
  11. def displayResult(left, right) :
  12. output = np.hstack((left,right))
  13. output = cv2.resize(output, (0,0), fx=4, fy=4)
  14. cv2.imshow("Result", output)
  15. # Recontruct face using mean face and EigenFaces
  16. def reconstructFace(*args):
  17. # Start with the mean / average face
  18. output = averageFace
  19. for i in range(0,args[0]):
  20. '''
  21. The weight is the dot product of the mean subtracted
  22. image vector with the EigenVector
  23. '''
  24. weight = np.dot(imVector, eigenVectors[i])
  25. output = output + eigenFaces[i] * weight
  26. displayResult(im, output)
  27. if __name__ == '__main__':
  28. # Read model file
  29. modelFile = "pcaParams.yml"
  30. print("Reading model file " + modelFile, end=" ... ", flush=True)
  31. file = cv2.FileStorage(modelFile, cv2.FILE_STORAGE_READ)
  32. # Extract mean vector
  33. mean = file.getNode("mean").mat()
  34. # Extract Eigen Vectors
  35. eigenVectors = file.getNode("eigenVectors").mat()
  36. # Extract size of the images used in training.
  37. sz = file.getNode("size").mat()
  38. sz = (int(sz[0,0]), int(sz[1,0]), int(sz[2,0]))
  39. '''
  40. Extract maximum number of EigenVectors.
  41. This is the max(numImagesUsedInTraining, w * h * 3)
  42. where w = width, h = height of the training images.
  43. '''
  44. numEigenFaces = eigenVectors.shape[0]
  45. print("DONE")
  46. # Extract mean vector and reshape it to obtain average face
  47. averageFace = mean.reshape(sz)
  48. # Reshape Eigenvectors to obtain EigenFaces
  49. eigenFaces = []
  50. for eigenVector in eigenVectors:
  51. eigenFace = eigenVector.reshape(sz)
  52. eigenFaces.append(eigenFace)
  53. # Read new test image. This image was not used in traning.
  54. imageFilename = "test/satya2.jpg"
  55. print("Read image " + imageFilename + " and vectorize ", end=" ... ");
  56. im = cv2.imread(imageFilename)
  57. im = np.float32(im)/255.0
  58. # Reshape image to one long vector and subtract the mean vector
  59. imVector = im.flatten() - mean;
  60. print("Done");
  61. # Show mean face first
  62. output = averageFace
  63. # Create window for displaying result
  64. cv2.namedWindow("Result", cv2.WINDOW_AUTOSIZE)
  65. # Changing the slider value changes the number of EigenVectors
  66. # used in reconstructFace.
  67. cv2.createTrackbar( "No. of EigenFaces", "Result", 0, numEigenFaces, reconstructFace)
  68. # Display original image and the reconstructed image size by side
  69. displayResult(im, output)
  70. cv2.waitKey(0)
  71. cv2.destroyAllWindows()

您可以创建模型pcaParams.yml使用createPCAModel.cpp和createPCAModel.py。该代码使用CelebA数据集的前1000个图像,并将它们首先缩放到一半大小。所以这个PCA模型是在大小(89 x 109)的图像上训练的。除了1000张图像之外,代码还使用了原始图像的垂直翻转版本,因此我们使用2000张图像进行训练。。但是createPCAModel文件里面没有reisze函数,要自己缩放为89X109分辨率。生成了pcaParams.yml文件,再通过reconstructFace获取人脸。

本文所有代码包括createPCAModel文件见:

https://github.com/luohenyueji/OpenCV-Practical-Exercise

但是图像没有列出,从CelebA数据集下载

http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html

3 参考

https://www.learnopencv.com/face-reconstruction-using-eigenfaces-cpp-python/

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/278486
推荐阅读
相关标签
  

闽ICP备14008679号