肖战真的没我帅!我自己写的Python颜值检测说的!
颜值评分不知道大家有没有玩过,今天我们就来自己写一个玩玩。
环境搭建
所需工具
**Python版本:**3.5.4(64bit)
相关模块:
opencv_python模块、sklearn模块、numpy模块、dlib模块以及一些Python自带的模块。
实现思路
(1)模型训练
(2)提取人脸关键点
(3)特征生成
(4)颜值预测
使用方式
有特殊疾病者请慎重尝试预测自己的颜值,本人不对颜值预测的结果和带来的所有负面影响负责!!!(总之你肯定比肖战帅!!)
言归正传。
环境搭建完成后,解压相关文件中的Face_Value.rar文件,cmd窗口切换到解压后的*.py文件所在目录。
例如:
打开test_img文件夹,将需要预测颜值的照片放入并重命名为test.jpg。
例如:
最后依次运行:
# 人脸关键点提取脚本 import cv2 import dlib import numpy # 模型路径 PREDICTOR_PATH = ./model/shape_predictor_68_face_landmarks.dat # 使用dlib自带的frontal_face_detector作为人脸提取器 detector = dlib.get_frontal_face_detector() # 使用官方提供的模型构建特征提取器 predictor = dlib.shape_predictor(PREDICTOR_PATH) face_img = cv2.imread("test_img/test.jpg") # 使用detector进行人脸检测,rects为返回的结果 rects = detector(face_img, 1) # 如果检测到人脸 if len(rects) >= 1: print("{} faces detected".format(len(rects))) else: print(No faces detected) exit() with open(./results/landmarks.txt, w) as f: f.truncate() for faces in range(len(rects)): # 使用predictor进行人脸关键点识别 landmarks = numpy.matrix([[p.x, p.y] for p in predictor(face_img, rects[faces]).parts()]) face_img = face_img.copy() # 使用enumerate函数遍历序列中的元素以及它们的下标 for idx, point in enumerate(landmarks): pos = (point[0, 0], point[0, 1]) f.write(str(point[0, 0])) f.write(,) f.write(str(point[0, 1])) f.write(,) f.write( ) f.close() # 成功后提示 print(Get landmarks successfully)
# 颜值预测脚本 from sklearn.externals import joblib import numpy as np from sklearn import decomposition pre_model = joblib.load(./model/face_rating.pkl) features = np.loadtxt(./data/features_ALL.txt, delimiter=,) my_features = np.loadtxt(./results/my_features.txt, delimiter=,) pca = decomposition.PCA(n_components=20) pca.fit(features) predictions = [] if len(my_features.shape) > 1: for i in range(len(my_features)): feature = my_features[i, :] feature_transfer = pca.transform(feature.reshape(1, -1)) predictions.append(pre_model.predict(feature_transfer)) print(照片中的人颜值得分依次为(满分为5分):) k = 1 for pre in predictions: print(第%d个人: % k, end=) print(str(pre)+分) k += 1 else: feature = my_features feature_transfer = pca.transform(feature.reshape(1, -1)) predictions.append(pre_model.predict(feature_transfer)) print(照片中的人颜值得分为(满分为5分):) k = 1 for pre in predictions: print(str(pre)+分) k += 1
你是Python小白吗?是的话就进我的学习圈吧