久久久久久久999_99精品久久精品一区二区爱城_成人欧美一区二区三区在线播放_国产精品日本一区二区不卡视频_国产午夜视频_欧美精品在线观看免费

 找回密碼
 立即注冊

QQ登錄

只需一步,快速開始

搜索
查看: 3804|回復: 2
收起左側

Python人臉識別+表情識別程序

[復制鏈接]
ID:724206 發表于 2020-12-20 22:36 | 顯示全部樓層 |閱讀模式
本人參加比賽時用的人臉識別程序,功能包括人臉識別以及表情識別,表情識別可識別正常、開心、驚訝。能力有限,程序在檢測到人臉時刷新率不是很高,攝像頭畫面有點卡,但在攝像頭前沒有人臉時畫面還是很流暢的,這是由于人臉識別算法和表情識別需要花費太多的時間。

程序太大,無法上傳,我就直接貼出來了。

get_face_from_camera.py/從攝像頭獲取人臉
  1. # 進行人臉錄入 / Face register

  2. import dlib
  3. import numpy as np
  4. import cv2
  5. import os
  6. import shutil
  7. import time

  8. # Dlib 正向人臉檢測器 / Use frontal face detector of Dlib
  9. detector = dlib.get_frontal_face_detector()


  10. class Face_Register:
  11.     def __init__(self):
  12.         self.path_photos_from_camera = "data/data_faces_from_camera_my/"
  13.         self.font = cv2.FONT_ITALIC

  14.         self.existing_faces_cnt = 0         # 已錄入的人臉計數器 / cnt for counting saved faces
  15.         self.ss_cnt = 0                     # 錄入 personX 人臉時圖片計數器 / cnt for screen shots
  16.         self.current_frame_faces_cnt = 0    # 錄入人臉計數器 / cnt for counting faces in current frame

  17.         self.save_flag = 1                  # 之后用來控制是否保存圖像的 flag / The flag to control if save
  18.         self.press_n_flag = 0               # 之后用來檢查是否先按 'n' 再按 's' / The flag to check if press 'n' before 's'

  19.         # FPS
  20.         self.frame_time = 0
  21.         self.frame_start_time = 0
  22.         self.fps = 0

  23.     # 新建保存人臉圖像文件和數據CSV文件夾 / Make dir for saving photos and csv
  24.     def pre_work_mkdir(self):
  25.         # 新建文件夾 / Create folders to save faces images and csv
  26.         if os.path.isdir(self.path_photos_from_camera):
  27.             pass
  28.         else:
  29.             os.mkdir(self.path_photos_from_camera)

  30.     # 刪除之前存的人臉數據文件夾 / Delete the old data of faces
  31.     def pre_work_del_old_face_folders(self):
  32.         # 刪除之前存的人臉數據文件夾, 刪除 "/data_faces_from_camera/person_x/"...
  33.         folders_rd = os.listdir(self.path_photos_from_camera)
  34.         for i in range(len(folders_rd)):
  35.             shutil.rmtree(self.path_photos_from_camera+folders_rd[i])
  36.         if os.path.isfile("data/features_all.csv"):
  37.             os.remove("data/features_all.csv")

  38.     # 如果有之前錄入的人臉, 在之前 person_x 的序號按照 person_x+1 開始錄入 / Start from person_x+1
  39.     def check_existing_faces_cnt(self):
  40.         if os.listdir("data/data_faces_from_camera_my/"):
  41.             # 獲取已錄入的最后一個人臉序號 / Get the order of latest person
  42.             person_list = os.listdir("data/data_faces_from_camera_my/")
  43.             person_num_list = []
  44.             for person in person_list:
  45.                 person_num_list.append(int(person.split('_')[-1]))
  46.             self.existing_faces_cnt = max(person_num_list)

  47.         # 如果第一次存儲或者沒有之前錄入的人臉, 按照 person_1 開始錄入 / Start from person_1
  48.         else:
  49.             self.existing_faces_cnt = 0

  50.     # 獲取處理之后 stream 的幀數 / Update FPS of video stream
  51.     def update_fps(self):
  52.         now = time.time()
  53.         self.frame_time = now - self.frame_start_time
  54.         self.fps = 1.0 / self.frame_time
  55.         self.frame_start_time = now

  56.     # 生成的 cv2 window 上面添加說明文字 / PutText on cv2 window
  57.     def draw_note(self, img_rd):
  58.         # 添加說明 / Add some notes
  59.         cv2.putText(img_rd, "Face Register", (20, 40), self.font, 1, (255, 255, 255), 1, cv2.LINE_AA)
  60.         cv2.putText(img_rd, "FPS:   " + str(self.fps.__round__(2)), (20, 100), self.font, 0.8, (0, 255, 0), 1,
  61.                     cv2.LINE_AA)
  62.         cv2.putText(img_rd, "Faces: " + str(self.current_frame_faces_cnt), (20, 140), self.font, 0.8, (0, 255, 0), 1, cv2.LINE_AA)
  63.         cv2.putText(img_rd, "N: Create face folder", (20, 350), self.font, 0.8, (255, 255, 255), 1, cv2.LINE_AA)
  64.         cv2.putText(img_rd, "S: Save current face", (20, 400), self.font, 0.8, (255, 255, 255), 1, cv2.LINE_AA)
  65.         cv2.putText(img_rd, "Q: Quit", (20, 450), self.font, 0.8, (255, 255, 255), 1, cv2.LINE_AA)

  66.     # 獲取人臉 / Main process of face detection and saving
  67.     def process(self, stream):
  68.         # 1. 新建儲存人臉圖像文件目錄 / Create folders to save photos
  69.         global current_face_dir
  70.         self.pre_work_mkdir()

  71.         # 2. 刪除 "/data/data_faces_from_camera" 中已有人臉圖像文件 / Uncomment if want to delete the saved faces and start from person_1
  72.         if os.path.isdir(self.path_photos_from_camera):
  73.             self.pre_work_del_old_face_folders()

  74.         # 3. 檢查 "/data/data_faces_from_camera" 中已有人臉文件
  75.         self.check_existing_faces_cnt()

  76.         while stream.isOpened():
  77.             flag, img_rd = stream.read()        # Get camera video stream
  78.             kk = cv2.waitKey(1)
  79.             faces = detector(img_rd, 0)         # Use Dlib face detector

  80.             # 4. 按下 'n' 新建存儲人臉的文件夾 / Press 'n' to create the folders for saving faces
  81.             if kk == ord('n'):
  82.                 self.existing_faces_cnt += 1
  83.                 current_face_dir = self.path_photos_from_camera + "person_" + str(self.existing_faces_cnt)
  84.                 os.makedirs(current_face_dir)
  85.                 print('\n')
  86.                 print("新建的人臉文件夾 / Create folders: ", current_face_dir)

  87.                 self.ss_cnt = 0                 # 將人臉計數器清零 / Clear the cnt of screen shots
  88.                 self.press_n_flag = 1           # 已經按下 'n' / Pressed 'n' already

  89.             # 5. 檢測到人臉 / Face detected
  90.             if len(faces) != 0:
  91.                 # 矩形框 / Show the ROI of faces
  92.                 for k, d in enumerate(faces):
  93.                     # 計算矩形框大小 / Compute the size of rectangle box
  94.                     height = (d.bottom() - d.top())
  95.                     width = (d.right() - d.left())
  96.                     hh = int(height/2)
  97.                     ww = int(width/2)

  98.                     # 6. 判斷人臉矩形框是否超出 480x640 / If the size of ROI > 480x640
  99.                     if (d.right()+ww) > 640 or (d.bottom()+hh > 480) or (d.left()-ww < 0) or (d.top()-hh < 0):
  100.                         cv2.putText(img_rd, "OUT OF RANGE", (20, 300), self.font, 0.8, (0, 0, 255), 1, cv2.LINE_AA)
  101.                         color_rectangle = (0, 0, 255)
  102.                         save_flag = 0
  103.                         if kk == ord('s'):
  104.                             print("請調整位置 / Please adjust your position")
  105.                     else:
  106.                         color_rectangle = (255, 255, 255)
  107.                         save_flag = 1

  108.                     cv2.rectangle(img_rd,
  109.                                   tuple([d.left() - ww, d.top() - hh]),
  110.                                   tuple([d.right() + ww, d.bottom() + hh]),
  111.                                   color_rectangle, 2)

  112.                     # 7. 根據人臉大小生成空的圖像 / Create blank image according to the size of face detected
  113.                     img_blank = np.zeros((int(height*2), width*2, 3), np.uint8)

  114.                     if save_flag:
  115.                         # 8. 按下 's' 保存攝像頭中的人臉到本地 / Press 's' to save faces into local images
  116.                         if kk == ord('s'):
  117.                             # 檢查有沒有先按'n'新建文件夾 / Check if you have pressed 'n'
  118.                             if self.press_n_flag:
  119.                                 self.ss_cnt += 1
  120.                                 for ii in range(height*2):
  121.                                     for jj in range(width*2):
  122.                                         img_blank[ii][jj] = img_rd[d.top()-hh + ii][d.left()-ww + jj]
  123.                                 cv2.imwrite(current_face_dir + "/img_face_" + str(self.ss_cnt) + ".jpg", img_blank)
  124.                                 print("寫入本地 / Save into:", str(current_face_dir) + "/img_face_" + str(self.ss_cnt) + ".jpg")
  125.                             else:
  126.                                 print("請先按 'N' 來建文件夾, 按 'S' / Please press 'N' and press 'S'")

  127.             self.current_frame_faces_cnt = len(faces)

  128.             # 9. 生成的窗口添加說明文字 / Add note on cv2 window
  129.             self.draw_note(img_rd)

  130.             # 10. 按下 'q' 鍵退出 / Press 'q' to exit
  131.             if kk == ord('q'):
  132.                 break

  133.             # 11. Update FPS
  134.             self.update_fps()

  135.             cv2.namedWindow("camera", 1)
  136.             cv2.imshow("camera", img_rd)

  137.     def run(self):
  138.         cap = cv2.VideoCapture(0)
  139.         self.process(cap)

  140.         cap.release()
  141.         cv2.destroyAllWindows()


  142. def main():
  143.     Face_Register_con = Face_Register()
  144.     Face_Register_con.run()


  145. if __name__ == '__main__':
  146.     main()
復制代碼




feature.py/提取保存的照片的特征
  1. # 從人臉圖像文件中提取人臉特征存入 "features_all.csv" / Extract features from images and save into "features_all.csv"

  2. import os
  3. import dlib
  4. from skimage import io
  5. import csv
  6. import numpy as np

  7. # 要讀取人臉圖像文件的路徑 / Path of cropped faces
  8. path_images_from_camera = "data/data_faces_from_camera/"

  9. # Dlib 正向人臉檢測器 / Use frontal face detector of Dlib
  10. detector = dlib.get_frontal_face_detector()

  11. # Dlib 人臉 landmark 特征點檢測器 / Get face landmarks
  12. predictor = dlib.shape_predictor('data/data_dlib/shape_predictor_68_face_landmarks.dat')

  13. # Dlib Resnet 人臉識別模型,提取 128D 的特征矢量 / Use Dlib resnet50 model to get 128D face descriptor
  14. face_reco_model = dlib.face_recognition_model_v1("data/data_dlib/dlib_face_recognition_resnet_model_v1.dat")


  15. # 返回單張圖像的 128D 特征 / Return 128D features for single image
  16. # Input:    path_img           <class 'str'>
  17. # Output:   face_descriptor    <class 'dlib.vector'>
  18. def return_128d_features(path_img):
  19.     img_rd = io.imread(path_img)
  20.     faces = detector(img_rd, 1)

  21.     print("%-40s %-20s" % ("檢測到人臉的圖像 / Image with faces detected:", path_img), '\n')

  22.     # 因為有可能截下來的人臉再去檢測,檢測不出來人臉了, 所以要確保是 檢測到人臉的人臉圖像拿去算特征
  23.     # For photos of faces saved, we need to make sure that we can detect faces from the cropped images
  24.     if len(faces) != 0:
  25.         shape = predictor(img_rd, faces[0])
  26.         face_descriptor = face_reco_model.compute_face_descriptor(img_rd, shape)
  27.     else:
  28.         face_descriptor = 0
  29.         print("no face")
  30.     return face_descriptor


  31. # 返回 personX 的 128D 特征均值 / Return the mean value of 128D face descriptor for person X
  32. # Input:    path_faces_personX       <class 'str'>
  33. # Output:   features_mean_personX    <class 'numpy.ndarray'>
  34. def return_features_mean_personX(path_faces_personX):
  35.     features_list_personX = []
  36.     photos_list = os.listdir(path_faces_personX)
  37.     if photos_list:
  38.         for i in range(len(photos_list)):
  39.             # 調用 return_128d_features() 得到 128D 特征 / Get 128D features for single image of personX
  40.             print("%-40s %-20s" % ("正在讀的人臉圖像 / Reading image:", path_faces_personX + "/" + photos_list[i]))
  41.             features_128d = return_128d_features(path_faces_personX + "/" + photos_list[i])
  42.             # 遇到沒有檢測出人臉的圖片跳過 / Jump if no face detected from image
  43.             if features_128d == 0:
  44.                 i += 1
  45.             else:
  46.                 features_list_personX.append(features_128d)
  47.     else:
  48.         print("文件夾內圖像文件為空 / Warning: No images in " + path_faces_personX + '/', '\n')

  49.     # 計算 128D 特征的均值 / Compute the mean
  50.     # personX 的 N 張圖像 x 128D -> 1 x 128D
  51.     if features_list_personX:
  52.         features_mean_personX = np.array(features_list_personX).mean(axis=0)
  53.     else:
  54.         features_mean_personX = np.zeros(128, dtype=int, order='C')
  55.     print(type(features_mean_personX))
  56.     return features_mean_personX


  57. # 獲取已錄入的最后一個人臉序號 / Get the order of latest person
  58. person_list = os.listdir("data/data_faces_from_camera/")
  59. person_num_list = []
  60. for person in person_list:
  61.     person_num_list.append(int(person.split('_')[-1]))
  62. person_cnt = max(person_num_list)

  63. with open("data/features_all.csv", "w", newline="") as csvfile:
  64.     writer = csv.writer(csvfile)
  65.     for person in range(person_cnt):
  66.         # Get the mean/average features of face/personX, it will be a list with a length of 128D
  67.         print(path_images_from_camera + "person_" + str(person + 1))
  68.         features_mean_personX = return_features_mean_personX(path_images_from_camera + "person_" + str(person + 1))
  69.         writer.writerow(features_mean_personX)
  70.         print("特征均值 / The mean of features:", list(features_mean_personX))
  71.         print('\n')
  72.     print("所有錄入人臉數據存入 / Save all the features of faces registered into: data/features_all.csv")
復制代碼


main.py/主程序
  1. import dlib
  2. import cv2
  3. import os
  4. import time
  5. import numpy as np
  6. import pandas as pd
  7. from PIL import Image

  8. # 正向人臉檢測器
  9. detector = dlib.get_frontal_face_detector()

  10. # 特征點檢測器
  11. predictor = dlib.shape_predictor('data/data_dlib/shape_predictor_68_face_landmarks.dat')

  12. # 人臉識別模型,提取 128D 的特征矢量
  13. face_reco_model = dlib.face_recognition_model_v1("data/data_dlib/dlib_face_recognition_resnet_model_v1.dat")


  14. class Face_Recognizer:
  15.     def __init__(self):
  16.         self.feature_known_list = []                # 用來存放所有錄入人臉特征的數組
  17.         self.name_known_list = []                   # 存儲錄入人臉名字

  18.         self.current_frame_face_cnt = 0             # 存儲當前攝像頭中捕獲到的人臉數
  19.         self.current_frame_feature_list = []        # 存儲當前攝像頭中捕獲到的人臉特征
  20.         self.current_frame_name_position_list = []  # 存儲當前攝像頭中捕獲到的所有人臉的名字坐標
  21.         self.current_frame_name_list = []           # 存儲當前攝像頭中捕獲到的所有人臉的名字

  22.         # Update FPS
  23.         self.fps = 0
  24.         self.frame_start_time = 0

  25.     # 讀取錄入人臉特征
  26.     def get_face_database(self):
  27.         if os.path.exists("data/features_all.csv"):
  28.             path_features_known_csv = "data/features_all.csv"
  29.             csv_rd = pd.read_csv(path_features_known_csv, header=None)
  30.             for i in range(csv_rd.shape[0]):
  31.                 features_someone_arr = []
  32.                 for j in range(0, 128):
  33.                     if csv_rd.iloc[i][j] == '':
  34.                         features_someone_arr.append('0')
  35.                     else:
  36.                         features_someone_arr.append(csv_rd.iloc[i][j])
  37.                 self.feature_known_list.append(features_someone_arr)
  38.                 self.name_known_list.append("Person_"+str(i+1))
  39.             print("人臉庫中的人臉數:", len(self.feature_known_list))
  40.             return 1
  41.         else:
  42.             print('##### Warning #####', '\n')
  43.             print("'features_all.csv' not found!")
  44.             print(
  45.                 "Please run 'get_faces_from_camera.py' and 'features.py' before 'main.py'",
  46.                 '\n')
  47.             print('##### End Warning #####')
  48.             return 0

  49.     # 計算兩個128D向量間的歐式距離
  50.     @staticmethod
  51.     def return_euclidean_distance(feature_1, feature_2):
  52.         feature_1 = np.array(feature_1)
  53.         feature_2 = np.array(feature_2)
  54.         dist = np.sqrt(np.sum(np.square(feature_1 - feature_2)))
  55.         return dist

  56.     # 更新 FPS
  57.     def update_fps(self):
  58.         now = time.time()
  59.         self.frame_time = now - self.frame_start_time
  60.         self.fps = 1.0 / self.frame_time
  61.         self.frame_start_time = now

  62.     def draw_note(self, img_rd):
  63.         cv2.putText(img_rd, "Face number: " + str(self.current_frame_face_cnt), (20, 40), cv2.FONT_HERSHEY_SIMPLEX,
  64.                         1, (0, 0, 255), 2, 4)
  65.         for i in range(self.current_frame_face_cnt):
  66.             cv2.putText(img_rd, "person: "+str(self.current_frame_name_list[i]), (20, 120), cv2.FONT_HERSHEY_SIMPLEX,
  67.                         1, (0, 0, 255), 2, 4)

  68.     def draw_name(self, img_rd):
  69.         # 在人臉框下面寫人臉名字
  70.         global img_with_name
  71.         img = Image.fromarray(cv2.cvtColor(img_rd, cv2.COLOR_BGR2RGB))
  72.         # draw = ImageDraw.Draw(img)
  73.         for i in range(self.current_frame_face_cnt):
  74.             img_with_name = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
  75.         return img_with_name

  76.     # 修改顯示人名
  77.     def show_chinese_name(self):
  78.         # Default known name: person_1, person_2, person_3
  79.         if self.current_frame_face_cnt >= 1:
  80.             self.name_known_list[0] = 'xiaoyu'
  81.             self.name_known_list[1] = 'xiaohui'
  82.             self.name_known_list[2] = 'xiaochen'
  83.             self.name_known_list[3] = 'xiaorui'
  84.             self.name_known_list[4] = 'xiaomu'
  85.             self.name_known_list[5] = 'xiaoman'

  86.     # 處理獲取的視頻流,進行人臉識別
  87.     def process(self, stream):
  88.         a = 100
  89.         m = 0
  90.         # 1. 讀取存放所有人臉特征的 csv
  91.         if self.get_face_database():
  92.             while stream.isOpened():
  93.                 flag, img_rd = stream.read()
  94.                 faces = detector(img_rd, 0)
  95.                 kk = cv2.waitKey(1)
  96.                 # 按下 q 鍵退出
  97.                 if kk == ord('q'):
  98.                     break
  99.                 else:
  100.                     self.draw_note(img_rd)
  101.                     self.current_frame_feature_list = []
  102.                     self.current_frame_face_cnt = 0
  103.                     self.current_frame_name_position_list = []
  104.                     self.current_frame_name_list = []

  105.                     # 2. 檢測到人臉
  106.                     if len(faces) != 0:
  107.                         # 3. 獲取當前捕獲到的圖像的所有人臉的特征
  108.                         for i in range(len(faces)):
  109.                             shape = predictor(img_rd, faces[i])
  110.                             self.current_frame_feature_list.append(face_reco_model.compute_face_descriptor(img_rd, shape))
  111.                         # 4. 遍歷捕獲到的圖像中所有的人臉
  112.                         for k in range(len(faces)):
  113.                             # 先默認所有人不認識,是 unknown
  114.                             self.current_frame_name_list.append("unknown")

  115.                             # 每個捕獲人臉的名字坐標
  116.                             self.current_frame_name_position_list.append(tuple(
  117.                                 [faces[k].left(), int(faces[k].bottom() + (faces[k].bottom() - faces[k].top()) / 4)]))

  118.                             # 5. 對于某張人臉,遍歷所有存儲的人臉特征
  119.                             current_frame_e_distance_list = []
  120.                             for i in range(len(self.feature_known_list)):
  121.                                 # 如果 person_X 數據不為空
  122.                                 if str(self.feature_known_list[i][0]) != '0.0':
  123.                                     e_distance_tmp = self.return_euclidean_distance(self.current_frame_feature_list[k],
  124.                                                                                     self.feature_known_list[i])
  125.                                     # print(e_distance_tmp)
  126.                                     current_frame_e_distance_list.append(e_distance_tmp)
  127.                                 else:
  128.                                     # 空數據 person_X
  129.                                     current_frame_e_distance_list.append(999999999)
  130.                             # 6. 尋找出最小的歐式距離匹配
  131.                             similar_person_num = current_frame_e_distance_list.index(min(current_frame_e_distance_list))

  132.                             if min(current_frame_e_distance_list) < 0.4:
  133.                                 self.current_frame_name_list[k] = self.name_known_list[similar_person_num]
  134.                                 a = similar_person_num

  135.                             else:
  136.                                 a = 7
  137.                             n = m
  138.                             m = self.face_emotion(stream)
  139.                             if a == 0:
  140.                                 print("識別結果:小玉")
  141.                             elif a == 1:
  142.                                 print("識別結果:小惠")
  143.                             elif a == 2:
  144.                                 print("識別結果:小晨")
  145.                             elif a == 3:
  146.                                 print("識別結果:小銳")
  147.                             elif a == 4:
  148.                                 print("識別結果:小木")
  149.                             elif a == 5:
  150.                                 print("識別結果:小滿")
  151.                             elif a == 7:
  152.                                 print("識別結果:陌生人")
  153.                             # print(min(current_frame_e_distance_list))
  154.                             if m == 1:
  155.                                 print("表情:正常\n\n")
  156.                                 cv2.putText(img_rd, "emotion: nature", (20, 80), cv2.FONT_HERSHEY_SIMPLEX,
  157.                                                 1, (0, 0, 255), 2, 4)
  158.                             elif m == 2:
  159.                                 print("表情:開心\n\n")
  160.                                 cv2.putText(img_rd, "emotion: happy", (20, 80), cv2.FONT_HERSHEY_SIMPLEX,
  161.                                                 1, (0, 0, 255), 2, 4)
  162.                             elif m == 3:
  163.                                 print("表情:驚訝\n\n")
  164.                                 cv2.putText(img_rd, "emotion: amazing", (20, 80), cv2.FONT_HERSHEY_SIMPLEX,
  165.                                                 1, (0, 0, 255), 2, 4)
  166.                             # 矩形框
  167.                             for kk, d in enumerate(faces):
  168.                                 # 繪制矩形框
  169.                                 cv2.rectangle(img_rd, tuple([d.left(), d.top()]), tuple([d.right(), d.bottom()]),
  170.                                               (0, 255, 255), 2)

  171.                         self.current_frame_face_cnt = len(faces)

  172.                         # 7. 在這里更改顯示的人名
  173.                         self.show_chinese_name()

  174.                         # 8. 寫名字
  175.                         img_with_name = self.draw_name(img_rd)

  176.                     else:
  177.                         print("無人臉\n")
  178.                         img_with_name = img_rd

  179.                 cv2.imshow("camera", img_with_name)

  180.                 # 9. 更新 FPS
  181.                 # self.update_fps()
  182.                 print("\n")

  183.     # OpenCV 調用攝像頭并進行 process
  184.     def run(self):
  185.         cap = cv2.VideoCapture(0)
  186.         cap.set(3, 480)     # 640x480
  187.         self.process(cap)

  188.         cap.release()
  189.         cv2.destroyAllWindows()

  190.     def face_emotion(self, cap):
  191.         a = 0
  192.         line_brow_x = []
  193.         line_brow_y = []
  194.         detector = dlib.get_frontal_face_detector()
  195.         flag, im_rd = cap.read()
  196.         # 每幀數據延時1ms,延時為0讀取的是靜態幀
  197.         k = cv2.waitKey(1)
  198.         # 取灰度
  199.         img_gray = cv2.cvtColor(im_rd, cv2.COLOR_RGB2GRAY)
  200.         # 使用人臉檢測器檢測每一幀圖像中的人臉。并返回人臉數rects
  201.         faces = detector(img_gray, 0)
  202.         # 待會要顯示在屏幕上的字體
  203.         # 如果檢測到人臉
  204.         if (len(faces) != 0):
  205.             # 對每個人臉都標出68個特征點
  206.             for i in range(len(faces)):
  207.                 # enumerate方法同時返回數據對象的索引和數據,k為索引,d為faces中的對象
  208.                 for k, d in enumerate(faces):
  209.                     # 用紅色矩形框出人臉
  210.                     cv2.rectangle(im_rd, (d.left(), d.top()), (d.right(), d.bottom()), (0, 0, 255))
  211.                     # 計算人臉熱別框邊長
  212.                     face_width = d.right() - d.left()
  213.                     # 使用預測器得到68點數據的坐標
  214.                     shape = predictor(im_rd, d)
  215.                     # 分析任意n點的位置關系來作為表情識別的依據
  216.                     mouth_width = (shape.part(54).x - shape.part(48).x) / face_width  # 嘴巴咧開程度
  217.                     mouth_higth = (shape.part(66).y - shape.part(62).y) / face_width  # 嘴巴張開程度
  218.                     # 通過兩個眉毛上的10個特征點,分析挑眉程度和皺眉程度
  219.                     brow_sum = 0  # 高度之和
  220.                     frown_sum = 0  # 兩邊眉毛距離之和
  221.                     for j in range(17, 21):
  222.                         brow_sum += (shape.part(j).y - d.top()) + (shape.part(j + 5).y - d.top())
  223.                         frown_sum += shape.part(j + 5).x - shape.part(j).x
  224.                         line_brow_x.append(shape.part(j).x)
  225.                         line_brow_y.append(shape.part(j).y)
  226.                     # self.brow_k, self.brow_d = self.fit_slr(line_brow_x, line_brow_y)  # 計算眉毛的傾斜程度
  227.                     tempx = np.array(line_brow_x)
  228.                     tempy = np.array(line_brow_y)
  229.                     z1 = np.polyfit(tempx, tempy, 1)  # 擬合成一次直線
  230.                     # brow_k = -round(float(z1[0]), 4)  # 擬合出曲線的斜率和實際眉毛的傾斜方向是相反的
  231.                     # print(self.brow_k)
  232.                     # brow_hight = (brow_sum / 10) / face_width  # 眉毛高度占比
  233.                     # brow_width = (frown_sum / 5) / face_width  # 眉毛距離占比
  234.                     # 眼睛睜開程度
  235.                     eye_sum = (shape.part(41).y - shape.part(37).y + shape.part(40).y - shape.part(38).y +
  236.                                shape.part(47).y - shape.part(43).y + shape.part(46).y - shape.part(44).y)
  237.                     eye_hight = (eye_sum / 4) / face_width
  238.                     # print("眼睛睜開距離與識別框高度之比:",round(eye_open/self.face_width,3))

  239.                     # 分情況討論
  240.                     # 張嘴,可能是開心或者驚訝
  241.                     if round(mouth_higth >= 0.05):
  242.                         if eye_hight >= 0.038:
  243.                             cv2.putText(im_rd, "amazing", (d.left(), d.bottom() + 20), cv2.FONT_HERSHEY_SIMPLEX,
  244.                                         0.8, (0, 0, 255), 2, 4)
  245.                             flag_d = 3
  246.                         else:
  247.                             cv2.putText(im_rd, "happy", (d.left(), d.bottom() + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.8,
  248.                                         (0, 0, 255), 2, 4)
  249.                             flag_d = 2

  250.                     # 沒有張嘴,可能是正常和生氣
  251.                     else:
  252.                         if mouth_width > 0.39:
  253.                             cv2.putText(im_rd, "happy", (d.left(), d.bottom() + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.8,
  254.                                         (0, 0, 255), 2, 4)
  255.                             flag_d = 2
  256.                         else:
  257.                             cv2.putText(im_rd, "nature", (d.left(), d.bottom() + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.8,
  258.                                         (0, 0, 255), 2, 4)
  259.                             flag_d = 1
  260.                     return flag_d

  261. def main():
  262.     Face_Recognizer_con = Face_Recognizer()
  263.     Face_Recognizer_con.run()


  264. if __name__ == '__main__':
  265.     main()
復制代碼



整個文件內容

整個文件內容

評分

參與人數 1黑幣 +50 收起 理由
admin + 50 共享資料的黑幣獎勵!

查看全部評分

回復

使用道具 舉報

ID:328014 發表于 2020-12-21 00:46 | 顯示全部樓層
好東東 可惜源碼沒上傳成功 是大于20兆了嗎?用7z壓縮率比較高
回復

使用道具 舉報

ID:871765 發表于 2021-1-1 13:03 | 顯示全部樓層
請教能不能做一款在一群人里面,識別出其中任意一個人對著鏡頭做“合十膜拜”的動作,要求低成本的單板,有酬任務,謝謝
回復

使用道具 舉報

您需要登錄后才可以回帖 登錄 | 立即注冊

本版積分規則

手機版|小黑屋|51黑電子論壇 |51黑電子論壇6群 QQ 管理員QQ:125739409;技術交流QQ群281945664

Powered by 單片機教程網

快速回復 返回頂部 返回列表
主站蜘蛛池模板: 在线综合视频 | 97日日碰人人模人人澡分享吧 | 成人伊人| 国产高清免费 | 国产电影一区二区在线观看 | 九色综合网 | 羞羞在线视频 | 国产精品国产a | 性视频网| 97精品国产一区二区三区 | 操到爽| 免费一区二区三区 | 粉色午夜视频 | 一区影院 | 一二三四在线视频观看社区 | 久草综合在线视频 | 色综合久久天天综合网 | 欧美偷偷操 | aa级毛片毛片免费观看久 | 91婷婷韩国欧美一区二区 | 男女视频在线观看免费 | 欧美寡妇偷汉性猛交 | 国产乱码久久久久久一区二区 | 国产精品激情小视频 | 日本精品一区二区三区视频 | 日日干夜夜操 | 欧洲妇女成人淫片aaa视频 | 日本在线视频不卡 | 中文区中文字幕免费看 | 欧美视频一区二区三区 | 日韩一区二区三区在线观看 | 国产精品毛片一区二区在线看 | 日日夜夜精品 | 亚洲人a | 一级毛片视频在线观看 | 亚洲午夜在线 | 午夜影院在线观看 | 97视频在线观看网站 | 一区二区免费在线观看 | 欧美亚洲在线视频 | 欧美一区二区三区大片 |