百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 热门文章 > 正文

[OpenCV实战]22 使用EigenFaces进行人脸重建

bigegpt 2024-09-12 11:27 10 浏览

使用EigenFaces进行人脸重建

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

1背景

1.1 什么是EigenFaces?

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

添加图片注释,不超过 140 字(可选)

其中

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

Fm是平均人脸图像;

Fi是一个EigenFace(特征脸);

添加图片注释,不超过 140 字(可选)

https://img-blog.csdnimg.cn/20190423194122119.png

是我们可以选择创建新图的标量系数权重,可正可负。

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

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

添加图片注释,不超过 140 字(可选)

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'轴上的投影。让我们看看这种技术如何应用于人脸重建。

添加图片注释,不超过 140 字(可选)

2 面部重建

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

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

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

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

2)减去平均向量.

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

添加图片注释,不超过 140 字(可选)

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

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

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

2.2 使用EigenFaces进行面部重建

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

代码如下:

C++:


#include "pch.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <opencv2/opencv.hpp>
#include <stdlib.h>
#include <time.h>

using namespace cv;
using namespace std;


// Matrices for average (mean) and eigenvectors
Mat averageFace;
Mat output;
vector<Mat> eigenFaces;
Mat imVector, meanVector, eigenVectors, im, display;

// Display result
// Left = Original Image
// Right = Reconstructed Face
void displayResult( Mat &left, Mat &right)
{
    hconcat(left,right, display);     
    resize(display, display, Size(), 4, 4);
    imshow("Result", display);
}

// Recontruct face using mean face and EigenFaces
void reconstructFace(int sliderVal, void*)
{
    // Start with the mean / average face
    Mat output = averageFace.clone();
    for (int i = 0;  i < sliderVal; i++)
    {
        // The weight is the dot product of the mean subtracted
        // image vector with the EigenVector
        double weight = imVector.dot(eigenVectors.row(i)); 

        // Add weighted EigenFace to the output
        output = output + eigenFaces[i] * weight; 
    }

    displayResult(im, output);
}
    

int main(int argc, char **argv)
{

    // Read model file
    string modelFile("pcaParams.yml");
    cout << "Reading model file " << modelFile << " ... " ; 

    FileStorage file(modelFile, FileStorage::READ);
    
    // Extract mean vector
    meanVector = file["mean"].mat();

    // Extract Eigen Vectors
    eigenVectors = file["eigenVectors"].mat();

    // Extract size of the images used in training. 
    Mat szMat = file["size"].mat();
    Size sz = Size(szMat.at<double>(1,0),szMat.at<double>(0,0));

    // Extract maximum number of EigenVectors. 
    // This is the max(numImagesUsedInTraining, w * h * 3)
    // where w = width, h = height of the training images. 
    int numEigenFaces = eigenVectors.size().height; 
    cout <<  "DONE" << endl; 

    cout << "Extracting mean face and eigen faces ... "; 
    // Extract mean vector and reshape it to obtain average face
    averageFace = meanVector.reshape(3,sz.height);
    
    // Reshape Eigenvectors to obtain EigenFaces
    for(int i = 0; i < numEigenFaces; i++)
    {
            Mat row = eigenVectors.row(i); 
            Mat eigenFace = row.reshape(3,sz.height);
            eigenFaces.push_back(eigenFace);
    }
    cout << "DONE" << endl; 

    // Read new test image. This image was not used in traning. 
    string imageFilename("test/satya1.jpg");
    cout << "Read image " << imageFilename << " and vectorize ... ";
    im = imread(imageFilename);
    im.convertTo(im, CV_32FC3, 1/255.0);
    
    // Reshape image to one long vector and subtract the mean vector
    imVector = im.clone(); 
    imVector = imVector.reshape(1, 1) - meanVector; 
    cout << "DONE" << endl; 


    // Show mean face first
    output = averageFace.clone(); 

    cout << "Usage:" << endl 
    << "\tChange the slider to change the number of EigenFaces" << endl
    << "\tHit ESC to terminate program." << endl;
    
    namedWindow("Result", CV_WINDOW_AUTOSIZE);
    int sliderValue; 

    // Changing the slider value changes the number of EigenVectors
    // used in reconstructFace.
    createTrackbar( "No. of EigenFaces", "Result", &sliderValue, numEigenFaces, reconstructFace);
    
    // Display original image and the reconstructed image size by side
    displayResult(im, output);
    

    waitKey(0);
    destroyAllWindows(); 
    return 0;
}

Python:


# Import necessary packages
import os
import sys
import cv2
import numpy as np

'''
 Display result
 Left = Original Image
 Right = Reconstructed Face
'''
def displayResult(left, right)    :
    output = np.hstack((left,right))    
    output = cv2.resize(output, (0,0), fx=4, fy=4)
    cv2.imshow("Result", output)

# Recontruct face using mean face and EigenFaces
def reconstructFace(*args):
    # Start with the mean / average face
    output = averageFace
    
    for i in range(0,args[0]):
        '''
        The weight is the dot product of the mean subtracted
        image vector with the EigenVector
        '''
        weight = np.dot(imVector, eigenVectors[i])
        output = output + eigenFaces[i] * weight

    
    displayResult(im, output)
    


if __name__ == '__main__':

    # Read model file
    modelFile = "pcaParams.yml"
    print("Reading model file " + modelFile, end=" ... ", flush=True)
    file = cv2.FileStorage(modelFile, cv2.FILE_STORAGE_READ)
    
    # Extract mean vector
    mean = file.getNode("mean").mat()
    
    # Extract Eigen Vectors
    eigenVectors = file.getNode("eigenVectors").mat()
    
    # Extract size of the images used in training.
    sz = file.getNode("size").mat()
    sz = (int(sz[0,0]), int(sz[1,0]), int(sz[2,0]))
    
    ''' 
    Extract maximum number of EigenVectors. 
    This is the max(numImagesUsedInTraining, w * h * 3)
    where w = width, h = height of the training images. 
    '''

    numEigenFaces = eigenVectors.shape[0]
    print("DONE")

    # Extract mean vector and reshape it to obtain average face
    averageFace = mean.reshape(sz)

    # Reshape Eigenvectors to obtain EigenFaces
    eigenFaces = [] 
    for eigenVector in eigenVectors:
        eigenFace = eigenVector.reshape(sz)
        eigenFaces.append(eigenFace)


    # Read new test image. This image was not used in traning. 
    imageFilename = "test/satya2.jpg"
    print("Read image " + imageFilename + " and vectorize ", end=" ... ");
    im = cv2.imread(imageFilename)
    im = np.float32(im)/255.0

    # Reshape image to one long vector and subtract the mean vector
    imVector = im.flatten() - mean; 
    print("Done");
    
    # Show mean face first
    output = averageFace
    
    # Create window for displaying result
    cv2.namedWindow("Result", cv2.WINDOW_AUTOSIZE)

    # Changing the slider value changes the number of EigenVectors
    # used in reconstructFace.
    cv2.createTrackbar( "No. of EigenFaces", "Result", 0, numEigenFaces, reconstructFace)

    # Display original image and the reconstructed image size by side
    displayResult(im, output)

    cv2.waitKey(0)
    cv2.destroyAllWindows()

您可以创建模型pcaParams.yml使用createPCAModel.cpp和createPCAModel.py。该代码使用CelebA数据集的前1000个图像,并将它们首先缩放到一半大小。所以这个PCA模型是在大小(89x109)的图像上训练的。除了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/


引用链接

[1] https://github.com/luohenyueji/OpenCV-Practical-Exercise: https://github.com/luohenyueji/OpenCV-Practical-Exercise

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

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

相关推荐

当Frida来“敲”门(frida是什么)

0x1渗透测试瓶颈目前,碰到越来越多的大客户都会将核心资产业务集中在统一的APP上,或者对自己比较重要的APP,如自己的主业务,办公APP进行加壳,流量加密,投入了很多精力在移动端的防护上。而现在挖...

服务端性能测试实战3-性能测试脚本开发

前言在前面的两篇文章中,我们分别介绍了性能测试的理论知识以及性能测试计划制定,本篇文章将重点介绍性能测试脚本开发。脚本开发将分为两个阶段:阶段一:了解各个接口的入参、出参,使用Python代码模拟前端...

Springboot整合Apache Ftpserver拓展功能及业务讲解(三)

今日分享每天分享技术实战干货,技术在于积累和收藏,希望可以帮助到您,同时也希望获得您的支持和关注。架构开源地址:https://gitee.com/msxyspringboot整合Ftpserver参...

Linux和Windows下:Python Crypto模块安装方式区别

一、Linux环境下:fromCrypto.SignatureimportPKCS1_v1_5如果导包报错:ImportError:Nomodulenamed'Crypt...

Python 3 加密简介(python des加密解密)

Python3的标准库中是没多少用来解决加密的,不过却有用于处理哈希的库。在这里我们会对其进行一个简单的介绍,但重点会放在两个第三方的软件包:PyCrypto和cryptography上,我...

怎样从零开始编译一个魔兽世界开源服务端Windows

第二章:编译和安装我是艾西,上期我们讲述到编译一个魔兽世界开源服务端环境准备,那么今天跟大家聊聊怎么编译和安装我们直接进入正题(上一章没有看到的小伙伴可以点我主页查看)编译服务端:在D盘新建一个文件夹...

附1-Conda部署安装及基本使用(conda安装教程)

Windows环境安装安装介质下载下载地址:https://www.anaconda.com/products/individual安装Anaconda安装时,选择自定义安装,选择自定义安装路径:配置...

如何配置全世界最小的 MySQL 服务器

配置全世界最小的MySQL服务器——如何在一块IntelEdison为控制板上安装一个MySQL服务器。介绍在我最近的一篇博文中,物联网,消息以及MySQL,我展示了如果Partic...

如何使用Github Action来自动化编译PolarDB-PG数据库

随着PolarDB在国产数据库领域荣膺桂冠并持续获得广泛认可,越来越多的学生和技术爱好者开始关注并涉足这款由阿里巴巴集团倾力打造且性能卓越的关系型云原生数据库。有很多同学想要上手尝试,却卡在了编译数据...

面向NDK开发者的Android 7.0变更(ndk android.mk)

订阅Google官方微信公众号:谷歌开发者。与谷歌一起创造未来!受Android平台其他改进的影响,为了方便加载本机代码,AndroidM和N中的动态链接器对编写整洁且跨平台兼容的本机...

信创改造--人大金仓(Kingbase)数据库安装、备份恢复的问题纪要

问题一:在安装KingbaseES时,安装用户对于安装路径需有“读”、“写”、“执行”的权限。在Linux系统中,需要以非root用户执行安装程序,且该用户要有标准的home目录,您可...

OpenSSH 安全漏洞,修补操作一手掌握

1.漏洞概述近日,国家信息安全漏洞库(CNNVD)收到关于OpenSSH安全漏洞(CNNVD-202407-017、CVE-2024-6387)情况的报送。攻击者可以利用该漏洞在无需认证的情况下,通...

Linux:lsof命令详解(linux lsof命令详解)

介绍欢迎来到这篇博客。在这篇博客中,我们将学习Unix/Linux系统上的lsof命令行工具。命令行工具是您使用CLI(命令行界面)而不是GUI(图形用户界面)运行的程序或工具。lsoflsof代表&...

幻隐说固态第一期:固态硬盘接口类别

前排声明所有信息来源于网络收集,如有错误请评论区指出更正。废话不多说,目前固态硬盘接口按速度由慢到快分有这几类:SATA、mSATA、SATAExpress、PCI-E、m.2、u.2。下面我们来...

新品轰炸 影驰SSD多款产品登Computex

分享泡泡网SSD固态硬盘频道6月6日台北电脑展作为全球第二、亚洲最大的3C/IT产业链专业展,吸引了众多IT厂商和全球各地媒体的热烈关注,全球存储新势力—影驰,也积极参与其中,为广大玩家朋友带来了...