Let’s code to identify your emotions.
Coding識別你的喜怒哀樂畅哑。
---《python情緒識別》.BY Andy
一肴楷、原圖
二、情緒識別結(jié)果
三荠呐、代碼實現(xiàn)
'''
@filename:faceEmotions_image.py
'''
import dlib #人臉識別的庫dlib
import numpy as np #數(shù)據(jù)處理的庫numpy
import cv2 #圖像處理的庫OpenCv
from skimage import io #>pip install scikit-image,scipy
class face_emotion():
def __init__(self):
# 使用特征提取器get_frontal_face_detector
self.detector = dlib.get_frontal_face_detector()
# dlib的68點模型赛蔫,使用作者訓練好的特征預測器
self.predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
def learning_face(self):
# 眉毛直線擬合數(shù)據(jù)緩沖
line_brow_x = []
line_brow_y = []
im_rd = cv2.imread("p4.jpg")
img_gray = cv2.cvtColor(im_rd, cv2.COLOR_RGB2GRAY)
faces = self.detector(img_gray, 0) # 檢測到的人臉數(shù)
# 待會要顯示在屏幕上的字體
font = cv2.FONT_HERSHEY_SIMPLEX
if(len(faces)!=0):
# 對每個人臉都標出68個特征點
for k, d in enumerate(faces):
cv2.rectangle(im_rd, (d.left(), d.top()),
(d.right(), d.bottom()), (0, 0, 255))
cv2.rectangle(im_rd, (d.left()-10, d.top()-10),
(d.right()+10, d.bottom()+10), (0, 255, 0))
# 用紅色矩形框出人臉
cv2.rectangle(im_rd, (d.left(), d.top()), (d.right(), d.bottom()), (0, 0, 255))
# 計算人臉熱別框邊長
self.face_width = d.right() - d.left()
# 使用預測器得到68點數(shù)據(jù)的坐標
shape = self.predictor(im_rd, d)
# 圓圈顯示每個特征點
for i in range(68):
cv2.circle(im_rd, (shape.part(i).x, shape.part(i).y), 2, (0, 255, 0), -1, 8)
#cv2.putText(im_rd, str(i), (shape.part(i).x, shape.part(i).y),
# cv2.FONT_HERSHEY_SIMPLEX, 0.3,(255, 255, 255))
# 分析任意n點的位置關系來作為表情識別的依據(jù)
mouth_width = (shape.part(54).x - shape.part(48).x) / self.face_width # 嘴巴咧開程度
mouth_higth = (shape.part(66).y - shape.part(62).y) / self.face_width # 嘴巴張開程度
# print("嘴巴寬度與識別框?qū)挾戎龋?,mouth_width_arv)
# print("嘴巴高度與識別框高度之比:",mouth_higth_arv)
# 通過兩個眉毛上的10個特征點,分析挑眉程度和皺眉程度
brow_sum = 0 # 高度之和
frown_sum = 0 # 兩邊眉毛距離之和
for j in range(17, 21):
brow_sum += (shape.part(j).y - d.top()) + (shape.part(j + 5).y - d.top())
frown_sum += shape.part(j + 5).x - shape.part(j).x
line_brow_x.append(shape.part(j).x)
line_brow_y.append(shape.part(j).y)
# self.brow_k, self.brow_d = self.fit_slr(line_brow_x, line_brow_y) # 計算眉毛的傾斜程度
tempx = np.array(line_brow_x)
tempy = np.array(line_brow_y)
z1 = np.polyfit(tempx, tempy, 1) # 擬合成一次直線
self.brow_k = -round(z1[0], 3) # 擬合出曲線的斜率和實際眉毛的傾斜方向是相反的
brow_hight = (brow_sum / 10) / self.face_width # 眉毛高度占比
brow_width = (frown_sum / 5) / self.face_width # 眉毛距離占比
# print("眉毛高度與識別框高度之比:",round(brow_arv/self.face_width,3))
# print("眉毛間距與識別框高度之比:",round(frown_arv/self.face_width,3))
# 眼睛睜開程度
eye_sum = (shape.part(41).y - shape.part(37).y + shape.part(40).y - shape.part(38).y +
shape.part(47).y - shape.part(43).y + shape.part(46).y - shape.part(44).y)
eye_hight = (eye_sum / 4) / self.face_width
# print("眼睛睜開距離與識別框高度之比:",round(eye_open/self.face_width,3))
# 分情況討論
# 張嘴泥张,可能是開心或者驚訝
if round(mouth_higth >= 0.03):
if eye_hight >= 0.056:
print(f'amazing-->[mouth_higth:{mouth_higth},eye_hight:{eye_hight},self.brow_k:{self.brow_k}]')
cv2.putText(im_rd, "amazing", (d.left(), d.bottom() + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.8,
(0, 0, 255), 2, 4)
else:
print(f'happy-->[mouth_higth:{mouth_higth},eye_hight:{eye_hight},self.brow_k:{self.brow_k}]')
cv2.putText(im_rd, "happy", (d.left(), d.bottom() + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.8,
(0, 0, 255), 2, 4)
# 沒有張嘴呵恢,可能是正常和生氣
else:
if self.brow_k <= -0.2:# modify 0.3 as 0.2 by Andy
print(f'angry-->[mouth_higth:{mouth_higth},eye_hight:{eye_hight},self.brow_k:{self.brow_k}]')
cv2.putText(im_rd, "angry", (d.left(), d.bottom() + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.8,(0, 0, 255), 2, 4)
else:
print(f'nature-->[mouth_higth:{mouth_higth},eye_hight:{eye_hight},self.brow_k:{self.brow_k}]')
cv2.putText(im_rd, "nature", (d.left(), d.bottom() + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.8,
(0, 0, 255), 2, 4)
# 標出人臉數(shù)
cv2.putText(im_rd, "Faces: "+str(len(faces)), (20,50), font, 1, (0, 0, 255), 1, cv2.LINE_AA)
else:
# 沒有檢測到人臉
cv2.putText(im_rd, "No Face", (20, 50), font, 1, (0, 0, 255), 1, cv2.LINE_AA)
# 窗口顯示
cv2.imshow("camera", im_rd)
cv2.imwrite("Andy0"+".jpg", im_rd)
if __name__ == "__main__":
my_face = face_emotion()
my_face.learning_face()
#coding: utf-8
'''
@filename:faceEmotions_video.py
'''
import dlib #人臉識別的庫dlib
import numpy as np #數(shù)據(jù)處理的庫numpy
import cv2 #圖像處理的庫OpenCv
from skimage import io #>pip install scikit-image,scipy
class face_emotion():
def __init__(self):
# 使用特征提取器get_frontal_face_detector
self.detector = dlib.get_frontal_face_detector()
# dlib的68點模型,使用作者訓練好的特征預測器
self.predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
#建cv2攝像頭對象圾结,這里使用電腦自帶攝像頭瑰剃,如果接了外部攝像頭,則自動切換到外部攝像頭
self.cap = cv2.VideoCapture(0)
# 設置視頻參數(shù)筝野,propId設置的視頻參數(shù)晌姚,value設置的參數(shù)值
self.cap.set(3, 480)
# 截圖screenshoot的計數(shù)器
self.cnt = 0
def learning_face(self):
# 眉毛直線擬合數(shù)據(jù)緩沖
line_brow_x = []
line_brow_y = []
# cap.isOpened() 返回true/false 檢查初始化是否成功
while(self.cap.isOpened()):
# cap.read()
# 返回兩個值:
# 一個布爾值true/false,用來判斷讀取視頻是否成功/是否到視頻末尾
# 圖像對象歇竟,圖像的三維矩陣
flag, im_rd = self.cap.read()
# 每幀數(shù)據(jù)延時1ms挥唠,延時為0讀取的是靜態(tài)幀
k = cv2.waitKey(1)
# 取灰度
img_gray = cv2.cvtColor(im_rd, cv2.COLOR_RGB2GRAY)
# 使用人臉檢測器檢測每一幀圖像中的人臉。并返回人臉數(shù)rects
faces = self.detector(img_gray, 0)
# 待會要顯示在屏幕上的字體
font = cv2.FONT_HERSHEY_SIMPLEX
# 如果檢測到人臉
if(len(faces)!=0):
# 對每個人臉都標出68個特征點
for i in range(len(faces)):
# enumerate方法同時返回數(shù)據(jù)對象的索引和數(shù)據(jù)焕议,k為索引宝磨,d為faces中的對象
for k, d in enumerate(faces):
# 用紅色矩形框出人臉
cv2.rectangle(im_rd, (d.left(), d.top()), (d.right(), d.bottom()), (0, 0, 255))
# 計算人臉熱別框邊長
self.face_width = d.right() - d.left()
# 使用預測器得到68點數(shù)據(jù)的坐標
shape = self.predictor(im_rd, d)
# 圓圈顯示每個特征點
for i in range(68):
cv2.circle(im_rd, (shape.part(i).x, shape.part(i).y), 2, (0, 255, 0), -1, 8)
cv2.putText(im_rd, str(i), (shape.part(i).x, shape.part(i).y), cv2.FONT_HERSHEY_SIMPLEX, 0.3,
(255, 255, 255))
# 分析任意n點的位置關系來作為表情識別的依據(jù)
mouth_width = (shape.part(54).x - shape.part(48).x) / self.face_width # 嘴巴咧開程度
mouth_higth = (shape.part(66).y - shape.part(62).y) / self.face_width # 嘴巴張開程度
# print("嘴巴寬度與識別框?qū)挾戎龋?,mouth_width_arv)
# print("嘴巴高度與識別框高度之比:",mouth_higth_arv)
# 通過兩個眉毛上的10個特征點,分析挑眉程度和皺眉程度
brow_sum = 0 # 高度之和
frown_sum = 0 # 兩邊眉毛距離之和
for j in range(17, 21):
brow_sum += (shape.part(j).y - d.top()) + (shape.part(j + 5).y - d.top())
frown_sum += shape.part(j + 5).x - shape.part(j).x
line_brow_x.append(shape.part(j).x)
line_brow_y.append(shape.part(j).y)
print("self:"+str(self))
# self.brow_k, self.brow_d = self.fit_slr(line_brow_x, line_brow_y) # 計算眉毛的傾斜程度
tempx = np.array(line_brow_x)
tempy = np.array(line_brow_y)
z1 = np.polyfit(tempx, tempy, 1) # 擬合成一次直線
self.brow_k = -round(z1[0], 3) # 擬合出曲線的斜率和實際眉毛的傾斜方向是相反的
brow_hight = (brow_sum / 10) / self.face_width # 眉毛高度占比
brow_width = (frown_sum / 5) / self.face_width # 眉毛距離占比
# print("眉毛高度與識別框高度之比:",round(brow_arv/self.face_width,3))
# print("眉毛間距與識別框高度之比:",round(frown_arv/self.face_width,3))
# 眼睛睜開程度
eye_sum = (shape.part(41).y - shape.part(37).y + shape.part(40).y - shape.part(38).y +
shape.part(47).y - shape.part(43).y + shape.part(46).y - shape.part(44).y)
eye_hight = (eye_sum / 4) / self.face_width
# print("眼睛睜開距離與識別框高度之比:",round(eye_open/self.face_width,3))
# 分情況討論
# 張嘴盅安,可能是開心或者驚訝
if round(mouth_higth >= 0.03):
if eye_hight >= 0.056:
cv2.putText(im_rd, "amazing", (d.left(), d.bottom() + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.8,
(0, 0, 255), 2, 4)
else:
cv2.putText(im_rd, "happy", (d.left(), d.bottom() + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.8,
(0, 0, 255), 2, 4)
# 沒有張嘴唤锉,可能是正常和生氣
else:
if self.brow_k <= -0.3:
cv2.putText(im_rd, "angry", (d.left(), d.bottom() + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.8,
(0, 0, 255), 2, 4)
else:
cv2.putText(im_rd, "nature", (d.left(), d.bottom() + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.8,
(0, 0, 255), 2, 4)
# 標出人臉數(shù)
cv2.putText(im_rd, "Faces: "+str(len(faces)), (20,50), font, 1, (0, 0, 255), 1, cv2.LINE_AA)
else:
# 沒有檢測到人臉
cv2.putText(im_rd, "No Face", (20, 50), font, 1, (0, 0, 255), 1, cv2.LINE_AA)
# 添加說明
im_rd = cv2.putText(im_rd, "S: screenshot", (20, 400), font, 0.8, (0, 0, 255), 1, cv2.LINE_AA)
im_rd = cv2.putText(im_rd, "Q: quit", (20, 450), font, 0.8, (0, 0, 255), 1, cv2.LINE_AA)
# 按下s鍵截圖保存
if (k == ord('s')):
self.cnt+=1
cv2.imwrite("screenshoot"+str(self.cnt)+".jpg", im_rd)
# 按下q鍵退出
if(k == ord('q')):
break
# 窗口顯示
cv2.imshow("camera", im_rd)
# 釋放攝像頭
self.cap.release()
# 刪除建立的窗口
cv2.destroyAllWindows()
if __name__ == "__main__":
my_face = face_emotion()
my_face.learning_face()
四、閑聊
??[1].代碼截止2019-04-21
調(diào)試無誤别瞭。
??[2].需要全部代碼及相關文件
窿祥,留言郵箱。