使用detector.run()来检测人脸,但是有的时候准确率不是很高,
可以看出来,有些裤子或者背景图像都被认为是人脸了
代码:
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 14 15:57:54 2021
"""
import dlib
import cv2
detector=dlib.get_frontal_face_detector()
cap=cv2.VideoCapture(0)
while True:
# ret,frame=cap.read()
#if not cap.isOpened():
# cv2.putText(frame,'请打开摄像头',(10,10),cv2.FONT_HERSHEY_PLAIN,2,(0,0,255),2)
frame=cv2.imread("lyj1.png")
det,scores,idex=detector.run(frame,1,-1)
facesnum=len(det)
cv2.putText(frame,'faces:{}'.format(facesnum),(10,30),cv2.FONT_HERSHEY_PLAIN,2,(0,0,255),2)
for i,d in enumerate(det):
cv2.rectangle(frame,(d.left(),d.top()),(d.right(),d.bottom()),[0,255,0],2)
#cv2.putText(frame,"dectection{},score:{},face_type:{}".format(d,scores[i],idex[i]),(10,50),cv2.FONT_HERSHEY_PLAIN,1,(0,0,255),1)
cv2.putText(frame,"dectection:{}".format(d),(10,50),cv2.FONT_HERSHEY_PLAIN,1,(0,0,255),2)
cv2.putText(frame,"score:{}".format(scores[i]),(10,70),cv2.FONT_HERSHEY_PLAIN,1,(0,0,255),2)
cv2.putText(frame,"face_type:{}".format(idex[i]),(10,90),cv2.FONT_HERSHEY_PLAIN,1,(0,0,255),2)
cv2.putText(frame,'press ESC quit',(10,450),cv2.FONT_HERSHEY_PLAIN,2,(0,0,255),2)
cv2.imshow('image',frame)
if cv2.waitKey(10) == 27:
break
cv2.destroyAllWindows()
使用dlib提供的人脸特征来检测人脸,效果会好得多
可以看出来,比上面检测的人脸个数少了7个,基本都正确的识别出来了
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 14 14:54:23 2021
@author:
"""
import dlib
import cv2
import os
predictor_path='shape_predictor_5_face_landmarks.dat'
detector=dlib.get_frontal_face_detector()
sp=dlib.shape_predictor(os.path.join("F:\code\Pythoncode\dlib\shape_predictor_5_face_landmarks.dat",predictor_path))
#cap=cv2.VideoCapture(0)
while True:
#ret,frame=cap.read()
frame=cv2.imread("lyj1.png")
#if not cap.isOpened():
#print("打开摄像头")
dets=detector(frame,1)
print(frame.shape)
num_faces=len(dets)
if num_faces==0:
print("没有发现人脸")
cv2.putText(frame,'faces:{}'.format(num_faces),(10,30),cv2.FONT_HERSHEY_PLAIN,2,(0,0,255),2)
faces=dlib.full_object_detections()
for detection in dets:
faces.append(sp(frame,detection))
print(detection.left())
cv2.rectangle(frame,(detection.left(),detection.top()),(detection.right(),detection.bottom()),[0,255,0],3)
cv2.putText(frame,'press ESC quit',(10,450),cv2.FONT_HERSHEY_PLAIN,2,(0,0,255),2)
cv2.imshow('image',frame)
if cv2.waitKey(10) == 27:
break
cv2.destroyAllWindows()