关键词搜索

源码搜索 ×
×

Python开发案例,opencv_python模块实现照片中人脸进行颜值预测,网友们请谨慎使用!

发布2021-08-28浏览461次

详情内容

前言

利用python教程对照片中人脸进行颜值预测!

所需工具

Python版本:3.5.4(64bit)

相关模块:

opencv_python模块、sklearn模块、numpy模块、dlib模块以及一些Python自带的模块。

环境搭建

(1)安装相应版本的Python并添加到环境变量中;

(2)pip安装相关模块中提到的模块。

例如:

若pip安装报错,请自行到:

http://www.lfd.uci.edu/~gohlke/pythonlibs/

下载pip安装报错模块的whl文件,并使用:

pip install whl文件路径+whl文件名安装。

例如:

(已在相关文件中提供了编译好的用于dlib库安装的whl文件——>因为这个库最不好装)

参考文献链接

【1】xxxPh.D.的博客

http://www.learnopencv.com/computer-vision-for-predicting-facial-attractiveness/

【2】华南理工大学某实验室

http://www.hcii-lab.net/data/SCUT-FBP/EN/introduce.html

主要思路

(1)模型训练

用了PCA算法对特征进行了压缩降维;

然后用随机森林训练模型。

数据源于网络,据说数据“发源地”就是华南理工大学某实验室,因此我在参考文献上才加上了这个实验室的链接。

(2)提取人脸关键点

主要使用了dlib库。

使用官方提供的模型构建特征提取器。

(3)特征生成

完全参考了xxxPh.D.的博客。

(4)颜值预测

利用之前的数据和模型进行颜值预测。

使用方式

有特殊疾病者请慎重尝试预测自己的颜值,本人不对颜值预测的结果和带来的所有负面影响负责!!!

言归正传。

环境搭建完成后,解压相关文件中的Face_Value.rar文件,cmd窗口切换到解压后的*.py文件所在目录。

例如:

打开test_img文件夹,将需要预测颜值的照片放入并重命名为test.jpg。

例如:

若嫌麻烦或者有其他需求,请自行修改:

getLandmarks.py文件中第13行。

最后依次运行:

train_model.py(想直接用我模型的请忽略此步)

  1. # 模型训练脚本
  2. import numpy as np
  3. from sklearn import decomposition
  4. from sklearn.ensemble import RandomForestRegressor
  5. from sklearn.externals import joblib
  6. # 特征和对应的分数路径
  7. features_path = './data/features_ALL.txt'
  8. ratings_path = './data/ratings.txt'
  9. # 载入数据
  10. # 共500组数据
  11. # 其中前480组数据作为训练集,后20组数据作为测试集
  12. features = np.loadtxt(features_path, delimiter=',')
  13. features_train = features[0: -20]
  14. features_test = features[-20: ]
  15. ratings = np.loadtxt(ratings_path, delimiter=',')
  16. ratings_train = ratings[0: -20]
  17. ratings_test = ratings[-20: ]
  18. # 训练模型
  19. # 这里用PCA算法对特征进行了压缩和降维。
  20. # 降维之后特征变成了20维,也就是说特征一共有500行,每行是一个人的特征向量,每个特征向量有20个元素。
  21. # 用随机森林训练模型
  22. pca = decomposition.PCA(n_components=20)
  23. pca.fit(features_train)
  24. features_train = pca.transform(features_train)
  25. features_test = pca.transform(features_test)
  26. regr = RandomForestRegressor(n_estimators=50, max_depth=None, min_samples_split=10, random_state=0)
  27. regr = regr.fit(features_train, ratings_train)
  28. joblib.dump(regr, './model/face_rating.pkl', compress=1)
  29. # 训练完之后提示训练结束
  30. print('Generate Model Successfully!')

getLandmarks.py

  1. # 人脸关键点提取脚本
  2. import cv2
  3. import dlib
  4. import numpy
  5. # 模型路径
  6. PREDICTOR_PATH = './model/shape_predictor_68_face_landmarks.dat'
  7. # 使用dlib自带的frontal_face_detector作为人脸提取器
  8. detector = dlib.get_frontal_face_detector()
  9. # 使用官方提供的模型构建特征提取器
  10. predictor = dlib.shape_predictor(PREDICTOR_PATH)
  11. face_img = cv2.imread("test_img/test.jpg")
  12. # 使用detector进行人脸检测,rects为返回的结果
  13. rects = detector(face_img, 1)
  14. # 如果检测到人脸
  15. if len(rects) >= 1:
  16. print("{} faces detected".format(len(rects)))
  17. else:
  18. print('No faces detected')
  19. exit()
  20. with open('./results/landmarks.txt', 'w') as f:
  21. f.truncate()
  22. for faces in range(len(rects)):
  23. # 使用predictor进行人脸关键点识别
  24. landmarks = numpy.matrix([[p.x, p.y] for p in predictor(face_img, rects[faces]).parts()])
  25. face_img = face_img.copy()
  26. # 使用enumerate函数遍历序列中的元素以及它们的下标
  27. for idx, point in enumerate(landmarks):
  28. pos = (point[0, 0], point[0, 1])
  29. f.write(str(point[0, 0]))
  30. f.write(',')
  31. f.write(str(point[0, 1]))
  32. f.write(',')
  33. f.write('\n')
  34. f.close()
  35. # 成功后提示
  36. print('Get landmarks successfully')

getFeatures.py

  1. # 特征生成脚本
  2. # 具体原理请参见参考论文
  3. import math
  4. import numpy
  5. import itertools
  6. def facialRatio(points):
  7. x1 = points[0]
  8. y1 = points[1]
  9. x2 = points[2]
  10. y2 = points[3]
  11. x3 = points[4]
  12. y3 = points[5]
  13. x4 = points[6]
  14. y4 = points[7]
  15. dist1 = math.sqrt((x1-x2)**2 + (y1-y2)**2)
  16. dist2 = math.sqrt((x3-x4)**2 + (y3-y4)**2)
  17. ratio = dist1/dist2
  18. return ratio
  19. def generateFeatures(pointIndices1, pointIndices2, pointIndices3, pointIndices4, allLandmarkCoordinates):
  20. size = allLandmarkCoordinates.shape
  21. if len(size) > 1:
  22. allFeatures = numpy.zeros((size[0], len(pointIndices1)))
  23. for x in range(0, size[0]):
  24. landmarkCoordinates = allLandmarkCoordinates[x, :]
  25. ratios = []
  26. for i in range(0, len(pointIndices1)):
  27. x1 = landmarkCoordinates[2*(pointIndices1[i]-1)]
  28. y1 = landmarkCoordinates[2*pointIndices1[i] - 1]
  29. x2 = landmarkCoordinates[2*(pointIndices2[i]-1)]
  30. y2 = landmarkCoordinates[2*pointIndices2[i] - 1]
  31. x3 = landmarkCoordinates[2*(pointIndices3[i]-1)]
  32. y3 = landmarkCoordinates[2*pointIndices3[i] - 1]
  33. x4 = landmarkCoordinates[2*(pointIndices4[i]-1)]
  34. y4 = landmarkCoordinates[2*pointIndices4[i] - 1]
  35. points = [x1, y1, x2, y2, x3, y3, x4, y4]
  36. ratios.append(facialRatio(points))
  37. allFeatures[x, :] = numpy.asarray(ratios)
  38. else:
  39. allFeatures = numpy.zeros((1, len(pointIndices1)))
  40. landmarkCoordinates = allLandmarkCoordinates
  41. ratios = []
  42. for i in range(0, len(pointIndices1)):
  43. x1 = landmarkCoordinates[2*(pointIndices1[i]-1)]
  44. y1 = landmarkCoordinates[2*pointIndices1[i] - 1]
  45. x2 = landmarkCoordinates[2*(pointIndices2[i]-1)]
  46. y2 = landmarkCoordinates[2*pointIndices2[i] - 1]
  47. x3 = landmarkCoordinates[2*(pointIndices3[i]-1)]
  48. y3 = landmarkCoordinates[2*pointIndices3[i] - 1]
  49. x4 = landmarkCoordinates[2*(pointIndices4[i]-1)]
  50. y4 = landmarkCoordinates[2*pointIndices4[i] - 1]
  51. points = [x1, y1, x2, y2, x3, y3, x4, y4]
  52. ratios.append(facialRatio(points))
  53. allFeatures[0, :] = numpy.asarray(ratios)
  54. return allFeatures
  55. def generateAllFeatures(allLandmarkCoordinates):
  56. a = [18, 22, 23, 27, 37, 40, 43, 46, 28, 32, 34, 36, 5, 9, 13, 49, 55, 52, 58]
  57. combinations = itertools.combinations(a, 4)
  58. i = 0
  59. pointIndices1 = []
  60. pointIndices2 = []
  61. pointIndices3 = []
  62. pointIndices4 = []
  63. for combination in combinations:
  64. pointIndices1.append(combination[0])
  65. pointIndices2.append(combination[1])
  66. pointIndices3.append(combination[2])
  67. pointIndices4.append(combination[3])
  68. i = i+1
  69. pointIndices1.append(combination[0])
  70. pointIndices2.append(combination[2])
  71. pointIndices3.append(combination[1])
  72. pointIndices4.append(combination[3])
  73. i = i+1
  74. pointIndices1.append(combination[0])
  75. pointIndices2.append(combination[3])
  76. pointIndices3.append(combination[1])
  77. pointIndices4.append(combination[2])
  78. i = i+1
  79. return generateFeatures(pointIndices1, pointIndices2, pointIndices3, pointIndices4, allLandmarkCoordinates)
  80. landmarks = numpy.loadtxt("./results/landmarks.txt", delimiter=',', usecols=range(136))
  81. featuresALL = generateAllFeatures(landmarks)
  82. numpy.savetxt("./results/my_features.txt", featuresALL, delimiter=',', fmt = '%.04f')
  83. print("Generate Feature Successfully!")

Predict.py

  1. # 颜值预测脚本
  2. from sklearn.externals import joblib
  3. import numpy as np
  4. from sklearn import decomposition
  5. pre_model = joblib.load('./model/face_rating.pkl')
  6. features = np.loadtxt('./data/features_ALL.txt', delimiter=',')
  7. my_features = np.loadtxt('./results/my_features.txt', delimiter=',')
  8. pca = decomposition.PCA(n_components=20)
  9. pca.fit(features)
  10. predictions = []
  11. if len(my_features.shape) > 1:
  12. for i in range(len(my_features)):
  13. feature = my_features[i, :]
  14. feature_transfer = pca.transform(feature.reshape(1, -1))
  15. predictions.append(pre_model.predict(feature_transfer))
  16. print('照片中的人颜值得分依次为(满分为5分):')
  17. k = 1
  18. for pre in predictions:
  19. print('第%d个人:' % k, end='')
  20. print(str(pre)+'分')
  21. k += 1
  22. else:
  23. feature = my_features
  24. feature_transfer = pca.transform(feature.reshape(1, -1))
  25. predictions.append(pre_model.predict(feature_transfer))
  26. print('照片中的人颜值得分为(满分为5分):')
  27. k = 1
  28. for pre in predictions:
  29. print(str(pre)+'分')
  30. k += 1

文章到这里就结束了,感谢你的观看,下篇文章预测NBA比赛结果。

为了感谢读者们,我想把我最近收藏的一些编程干货分享给大家,回馈每一个读者,希望能帮到你们。

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载