欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

人脸补全

程序员文章站 2022-05-28 19:39:34
...

人脸补全

需求:

根据人的上半边脸预测下半边脸,用各种算法取得的结果与原图比较

思考:

  • 这是一个回归问题,不是分类问题(人脸数据不固定)
  • 数据集一共包含40个人,每一个人10张照片,分布规律
  • 每一个人取出8张照片作为训练数据,2张照片作为测试数据
  • 样本特征和样本标签如何拆分?上半边脸作为样本特征,下半边脸作为特征标签
  • 效果图

人脸补全

  • 导包
import numpy as np
import pandas as pd
from pandas import Series,DataFrame
import matplotlib.pyplot as plt
%matplotlib inline

from sklearn.datasets import fetch_olivetti_faces
from sklearn.neighbors import KNeighborsRegressor
from sklearn.linear_model import LinearRegression,Ridge,Lasso
  • 处理数据
faces = fetch_olivetti_faces()
data = faces.data
images = faces.images
target = faces.target

X_train = []
y_train = []
X_test = []
y_test = []

for i in range(40):
    for j in range(10):
        face_data = data[i*10+j]
        up_face = face_data[:2048]
        bottom_face = face_data[2048:]
        if j < 8:
            X_train.append(up_face)
            y_train.append(bottom_face)
        else:
            X_test.append(up_face)
            y_test.append(bottom_face)
  • 训练数据
knn = KNeighborsRegressor()
linear = LinearRegression()
ridge = Ridge()
lasso = Lasso()

knn.fit(X_train,y_train)
linear.fit(X_train,y_train)
ridge.fit(X_train,y_train)
lasso.fit(X_train,y_train)
  • 预测数据
y_ = knn.predict(X_test)
line_y_ = linear.predict(X_test)
ridge_y_ = ridge.predict(X_test)
lasso_y_ = lasso.predict(X_test)

# 把所有的预测结果保存的一个列表
pre_results = [y_,line_y_,ridge_y_,lasso_y_]
titles = ['True','KNN','Linear','Ridge','Lasso']
  • 绘图
# 画布
plt.figure(figsize=(10,10))
for i in range(5):
    # 先取出真实的脸
    true_up_face = X_test[i].reshape(32,64)
    true_bottom_face = y_test[i].reshape(32,64)
    true_face = np.concatenate((true_up_face,true_bottom_face),axis=0)
    axes = plt.subplot(5,5,5*i+1)
    axes.set_title(titles[0])
    axes.axis('off')
    plt.imshow(true_face,cmap='gray')
    for index,y_ in enumerate(pre_results):
        # 获取到每一种算法模型预测出的下半边脸的数据
        pre_bottom_face = y_[i].reshape(32,64)
        pre_face = np.concatenate((true_up_face,pre_bottom_face),axis=0)
        axes = plt.subplot(5,5,5*i+index+2)
        axes.set_title(titles[index+1])
        axes.axis('off')
        plt.imshow(pre_face,cmap='gray')