最近閑來(lái)無(wú)事,和一個(gè)學(xué)妹完成了一個(gè)SRT,主要是關(guān)于元宇宙什么的,不過(guò)我在其中主要的工作是用python寫(xiě)一個(gè)人臉識(shí)別系統(tǒng),發(fā)到這里和大家分享一下
注:我利用了幾個(gè)包,包括opencv,dlib,numpy等,所有包都會(huì)顯示在代碼開(kāi)頭import后
第一步,利用PyCharm先做灰度圖
想要識(shí)別表情,計(jì)算機(jī)就需要轉(zhuǎn)換人臉圖片轉(zhuǎn)化為灰度的圖,計(jì)算機(jī)不如人腦聰明,要把這張圖變成到電腦看得懂的形式。
import cv2 as cv
img=cv.imread('img.png')
#灰度
gray_img=cv.cvtColor(img,cv.COLOR_BGR2GRAY)
cv.imshow('gray',gray_img)
cv.imwrite('gray_face1.jpg',gray_img)
#修改尺寸
cv.imshow('read_img',img)
cv.waitKey(0)
cv.destroyAllWindows()
第二步,改變灰度圖大小
每張圖片大小都是不固定的,一運(yùn)行忽然很大總會(huì)嚇你一跳,也不便于觀察,這一步,我們先把灰度圖的尺寸改變一下
import cv2 as cv
img=cv.imread('img.png')
resize_img=cv.resize(img,dsize=(200,200))
cv.imshow('img',img)
cv.imshow('resize_img',resize_img)
print('修改前:',img.shape)
print('修改后:',resize_img.shape)
while True:
if ord('q')==cv.waitKey(0):
break
cv.destroyAllWindows()
第三步,鎖定人臉
基礎(chǔ)部分都學(xué)完了,該做正事了,這一步我們要鎖定人臉,好讓后續(xù)的工作繼續(xù)進(jìn)行
import cv2 as cv
img=cv.imread('3575ce750fbfb4906ac6d74909de2d6.jpg')
def face_detect_demo():
gary = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
face_detect=cv.CascadeClassifier('C:/Users/SGB/Downloads/opencv/sources/data/haarcascades/haarcascade_frontalface_alt2.xml')//調(diào)用了一個(gè)數(shù)據(jù)包
face=face_detect.detectMultiScale(gary)
for x,y,w,h in face:
cv.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2)
cv.imshow('result',img)
face_detect_demo()
while True:
if ord('q')==cv.waitKey(0):
break
cv.destroyAllWindows()
運(yùn)行結(jié)果
第四步,鎖定人臉上關(guān)鍵的點(diǎn)
為了識(shí)別表情,我們需要把臉上關(guān)鍵的點(diǎn)都給打印出來(lái),比方說(shuō)眉毛,眼睛,嘴巴等,我用的是前人訓(xùn)練出來(lái)的68點(diǎn)制。
import cv2
import numpy as np
import dlib
img_path = "3575ce750fbfb4906ac6d74909de2d6.jpg"
# 加載dlib 人臉檢測(cè)器
detector = dlib.get_frontal_face_detector()
# 加載dlib 人臉關(guān)鍵點(diǎn)
predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
# 讀入人臉圖片
img = cv2.imread(img_path)
cv2.imshow('img', img)
cv2.waitKey(0)
# 轉(zhuǎn)化為灰度圖
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('img_gray', img_gray)
cv2.waitKey(0)
# 檢測(cè)人臉
dets = detector(img_gray, 1)
# 遍歷每張人臉
for face in dets:
# 獲取人臉關(guān)鍵點(diǎn)(對(duì)遍歷到的這張臉進(jìn)行關(guān)鍵點(diǎn)檢測(cè))
shape = predictor(img_gray, face)
# 獲取每個(gè)點(diǎn)的坐標(biāo),并標(biāo)記在圖片上
for pt in shape.parts():
# 轉(zhuǎn)換坐標(biāo)
pt_pos = (pt.x, pt.y)
# 畫(huà)點(diǎn)
img_face = cv2.circle(img, pt_pos, 1, (0,255,0), 2)
cv2.imshow('face', img_face)
cv2.waitKey(0)
運(yùn)行結(jié)果
?第五步,打開(kāi)攝像頭,對(duì)人臉進(jìn)行關(guān)鍵點(diǎn)打印
打開(kāi)攝像頭,對(duì)人臉進(jìn)行打印關(guān)鍵點(diǎn)的操作。
import cv2
import numpy as np
import dlib
# 加載dlib 人臉檢測(cè)器
detector = dlib.get_frontal_face_detector()
# 加載dlib 人臉關(guān)鍵點(diǎn)
predictor = dlib.shape_predictor('./shape_predictor_68_face_landmarks.dat')
# 打開(kāi)攝像頭
cap = cv2.VideoCapture(0)
while(1):
flag, frame = cap.read()#獲取視頻內(nèi)容
frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)#加載灰度圖像
b, g, r = cv2.split(frame)
frame_RGB = cv2.merge((r, g ,b))
rets = detector(frame_gray, 0)#定位
for face in rets:
pots = predictor(frame_gray, face)#點(diǎn)
for i in pots.parts():
pos_pot = (i.x, i.y)
frame_face = cv2.circle(frame, pos_pot, 1, (0,255,0), 2)
cv2.imshow('face', frame_face)
k = cv2.waitKey(1)
if k & 0xff == ord('q'):#關(guān)閉攝像頭用Q
break
cap.release()
cv2.destroyAllWindows()
第五步,打開(kāi)攝像頭進(jìn)行表情分析
利用之前的關(guān)鍵點(diǎn),對(duì)其進(jìn)行算法分析,比方說(shuō)眉毛下壓是生氣,眼睛瞇起來(lái)是開(kāi)心等。
"""
從視屏中識(shí)別人臉,并實(shí)時(shí)標(biāo)出面部特征點(diǎn)
"""
import sys
import dlib # 人臉識(shí)別的庫(kù)dlib
import numpy as np # 數(shù)據(jù)處理的庫(kù)numpy
import cv2 # 圖像處理的庫(kù)OpenCv
img_path = "img.png"
class face_emotion():
def __init__(self):
# 使用特征提取器get_frontal_face_detector
self.detector = dlib.get_frontal_face_detector()
# dlib的68點(diǎn)模型,使用作者訓(xùn)練好的特征預(yù)測(cè)器
self.predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
# 建cv2攝像頭對(duì)象,這里使用電腦自帶攝像頭,如果接了外部攝像頭,則自動(dòng)切換到外部攝像頭
self.cap = cv2.VideoCapture(0)
# 設(shè)置視頻參數(shù),propId設(shè)置的視頻參數(shù),value設(shè)置的參數(shù)值
self.cap.set(3, 480)
# 截圖screenshoot的計(jì)數(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()
# 返回兩個(gè)值:
# 一個(gè)布爾值true/false,用來(lái)判斷讀取視頻是否成功/是否到視頻末尾
# 圖像對(duì)象,圖像的三維矩陣
flag, im_rd = self.cap.read()
# 每幀數(shù)據(jù)延時(shí)1ms,延時(shí)為0讀取的是靜態(tài)幀
k = cv2.waitKey(1)
# 取灰度
img_gray = cv2.cvtColor(im_rd, cv2.COLOR_RGB2GRAY)
#im_rd的意思是img
# 使用人臉檢測(cè)器檢測(cè)每一幀圖像中的人臉。并返回人臉數(shù)rects
faces = self.detector(img_gray, 0)
# 待會(huì)要顯示在屏幕上的字體
font = cv2.FONT_HERSHEY_SIMPLEX
# 如果檢測(cè)到人臉
if (len(faces) != 0):
# 對(duì)每個(gè)人臉都標(biāo)出68個(gè)特征點(diǎn)
for i in range(len(faces)):
# enumerate方法同時(shí)返回?cái)?shù)據(jù)對(duì)象的索引和數(shù)據(jù),k為索引,d為faces中的對(duì)象
for k, d in enumerate(faces):
# 用紅色矩形框出人臉
cv2.rectangle(im_rd, (d.left(), d.top()), (d.right(), d.bottom()), (0, 0, 255))
# 計(jì)算人臉熱別框邊長(zhǎng)
self.face_width = d.right() - d.left()
# 使用預(yù)測(cè)器得到68點(diǎn)數(shù)據(jù)的坐標(biāo)
shape = self.predictor(im_rd, d)
# 圓圈顯示每個(gè)特征點(diǎn)
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.5,
# (255, 255, 255))
# 分析任意n點(diǎn)的位置關(guān)系來(lái)作為表情識(shí)別的依據(jù)
mouth_width = (shape.part(54).x - shape.part(48).x) / self.face_width # 嘴巴咧開(kāi)程度
mouth_higth = (shape.part(66).y - shape.part(62).y) / self.face_width # 嘴巴張開(kāi)程度
# print("嘴巴寬度與識(shí)別框?qū)挾戎龋?,mouth_width_arv)
# print("嘴巴高度與識(shí)別框高度之比:",mouth_higth_arv)
# 通過(guò)兩個(gè)眉毛上的10個(gè)特征點(diǎn),分析挑眉程度和皺眉程度
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) # 計(jì)算眉毛的傾斜程度
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) # 擬合出曲線的斜率和實(shí)際眉毛的傾斜方向是相反的
brow_hight = (brow_sum / 10) / self.face_width # 眉毛高度占比
brow_width = (frown_sum / 5) / self.face_width # 眉毛距離占比
# print("眉毛高度與識(shí)別框高度之比:",round(brow_arv/self.face_width,3))
# print("眉毛間距與識(shí)別框高度之比:",round(frown_arv/self.face_width,3))
# 眼睛睜開(kāi)程度
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("眼睛睜開(kāi)距離與識(shí)別框高度之比:",round(eye_open/self.face_width,3))
# 分情況討論
# 張嘴,可能是開(kāi)心或者驚訝
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)
# 沒(méi)有張嘴,可能是正常和生氣
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)
# 標(biāo)出人臉數(shù)
cv2.putText(im_rd, "Faces: " + str(len(faces)), (20, 50), font, 1, (0, 0, 255), 1, cv2.LINE_AA)
else:
# 沒(méi)有檢測(cè)到人臉
cv2.putText(im_rd, "No Face", (20, 50), font, 1, (0, 0, 255), 1, cv2.LINE_AA)
# 添加說(shuō)明
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()
到這步的時(shí)候,其實(shí)已經(jīng)花了接近一周的時(shí)間,項(xiàng)目也接近結(jié)束,不過(guò)在這個(gè)基礎(chǔ)之上,我想,是否可以照葫蘆畫(huà)瓢,再做出一個(gè)圖片表情識(shí)別,做了一下午,居然真的被我弄出來(lái)了,算是瞎貓碰到死耗子。
?
"""
從視屏中識(shí)別人臉,并實(shí)時(shí)標(biāo)出面部特征點(diǎn)
"""
import sys
import dlib # 人臉識(shí)別的庫(kù)dlib
import imutils
import numpy as np # 數(shù)據(jù)處理的庫(kù)numpy
import cv2 # 圖像處理的庫(kù)OpenCv
img_path = "img_4.png"
class face_emotion():
def __init__(self):
# 使用特征提取器get_frontal_face_detector
self.detector = dlib.get_frontal_face_detector()
# dlib的68點(diǎn)模型,使用作者訓(xùn)練好的特征預(yù)測(cè)器
self.predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
self.image = cv2.imread("img.png")
self.image = imutils.resize(self.image, width=500)
gray = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
self.cap = cv2.imread("img.png")
# 截圖screenshoot的計(jì)數(shù)器
def learning_face(self):
# 眉毛直線擬合數(shù)據(jù)緩沖
line_brow_x = []
line_brow_y = []
# cap.isOpened() 返回true/false 檢查初始化是否成功
while (1):
# 返回兩個(gè)值:
# 圖像對(duì)象,圖像的三維矩陣
im_rd = cv2.imread(img_path)
# 每幀數(shù)據(jù)延時(shí)1ms,延時(shí)為0讀取的是靜態(tài)幀
k = cv2.waitKey(1)
# 取灰度
img_gray = cv2.cvtColor(im_rd, cv2.COLOR_RGB2GRAY)
# 使用人臉檢測(cè)器檢測(cè)每一幀圖像中的人臉。并返回人臉數(shù)rects
faces = self.detector(img_gray, 0)
# 待會(huì)要顯示在屏幕上的字體
font = cv2.FONT_HERSHEY_SIMPLEX
# 如果檢測(cè)到人臉
if (len(faces) != 0):
# 對(duì)每個(gè)人臉都標(biāo)出68個(gè)特征點(diǎn)
for i in range(len(faces)):
# enumerate方法同時(shí)返回?cái)?shù)據(jù)對(duì)象的索引和數(shù)據(jù),k為索引,d為faces中的對(duì)象
for k, d in enumerate(faces):
# 用紅色矩形框出人臉
cv2.rectangle(im_rd, (d.left(), d.top()), (d.right(), d.bottom()), (0, 0, 255))
# 計(jì)算人臉熱別框邊長(zhǎng)
self.face_width = d.right() - d.left()
# 使用預(yù)測(cè)器得到68點(diǎn)數(shù)據(jù)的坐標(biāo)
shape = self.predictor(im_rd, d)
# 圓圈顯示每個(gè)特征點(diǎn)
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.5,
# (255, 255, 255))
# 分析任意n點(diǎn)的位置關(guān)系來(lái)作為表情識(shí)別的依據(jù)
mouth_width = (shape.part(54).x - shape.part(48).x) / self.face_width # 嘴巴咧開(kāi)程度
mouth_higth = (shape.part(66).y - shape.part(62).y) / self.face_width # 嘴巴張開(kāi)程度
# print("嘴巴寬度與識(shí)別框?qū)挾戎龋?,mouth_width_arv)
# print("嘴巴高度與識(shí)別框高度之比:",mouth_higth_arv)
# 通過(guò)兩個(gè)眉毛上的10個(gè)特征點(diǎn),分析挑眉程度和皺眉程度
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) # 計(jì)算眉毛的傾斜程度
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) # 擬合出曲線的斜率和實(shí)際眉毛的傾斜方向是相反的
brow_hight = (brow_sum / 10) / self.face_width # 眉毛高度占比
brow_width = (frown_sum / 5) / self.face_width # 眉毛距離占比
# print("眉毛高度與識(shí)別框高度之比:",round(brow_arv/self.face_width,3))
# print("眉毛間距與識(shí)別框高度之比:",round(frown_arv/self.face_width,3))
# 眼睛睜開(kāi)程度
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("眼睛睜開(kāi)距離與識(shí)別框高度之比:",round(eye_open/self.face_width,3))
# 分情況討論
# 張嘴,可能是開(kāi)心或者驚訝
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)
# 沒(méi)有張嘴,可能是正常和生氣
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)
# 標(biāo)出人臉數(shù)
cv2.putText(im_rd, "Faces: " + str(len(faces)), (20, 50), font, 1, (0, 0, 255), 1, cv2.LINE_AA)
else:
# 沒(méi)有檢測(cè)到人臉
cv2.putText(im_rd, "No Face", (20, 50), font, 1, (0, 0, 255), 1, cv2.LINE_AA)
# 添加說(shuō)明
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)
# 刪除建立的窗口
cv2.destroyAllWindows()
if __name__ == "__main__":
my_face = face_emotion()
my_face.learning_face()
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-476304.html
運(yùn)行結(jié)果,有不足的地方還請(qǐng)指正,謝謝大家??!?文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-476304.html
到了這里,關(guān)于利用PYTHON編寫(xiě)人臉表情識(shí)別系統(tǒng)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!