安装opencv-python:pip install opencv-python
1.使用opencv定位人脸
导入文件包
import cv2
import os
import matplotlib.pyplot as plt
def detect(filename):
face_cascade=cv2.CascadeClassifier('/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/cv2/data/haarcascade_frontalface_default.xml')
img=cv2.imread(filename)
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces=face_cascade.detectMultiScale(gray,1.3,5)
for(x,y,w,h)in faces:
img=cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
plt.imshow(img)
plt.axis('off')
plt.show()
detect('IMG_4408.jpg')
安装face-recognition:
face-recognition依赖于dlib,dlib依赖于opencv
dlib安装是上网搜的
然后就可以pip install face-recognition
2.使用face-recognition识别多人脸
import face_recognition
import cv2
import matplotlib.pyplot as plt
image=face_recognition.load_image_file("IMG_1946.JPG")
face_locations=face_recognition.face_locations(image)
face_num2=len(face_locations)
print(face_num2)
org=cv2.imread("IMG_1946.JPG")
for i in range(0,face_num2):
top=face_locations[i][0]
right=face_locations[i][1]
bottom=face_locations[i][2]
left=face_locations[i][3]
start=(left,top)
end=(right,bottom)
color=(0,255,255)
thickness=2
img=cv2.rectangle(org,start,end,color,thickness)
plt.imshow(img)
plt.axis('off')
plt.show
3.使用face-recognition确定人脸轮廓
import cv2
import dlib
import matplotlib.pyplot as plt
path="IMG_1946.JPG"
img=cv2.imread(path)
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
detector=dlib.get_frontal_face_detector()
predictor=dlib.shape_predictor('/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/face_recognition_models/models/shape_predictor_68_face_landmarks.dat')
dets=detector(gray,1)
for face in dets:
shape=predictor(img,face)
for pt in shape.parts():
pt_pos=(pt.x,pt.y)
img=cv2.circle(img,pt_pos,2,(0,255,0),2)
plt.imshow(img)
plt.axis('off')
plt.show()
4.心得
(1)安装opencv的时候很慢很慢,一开始以为是我电脑出问题了重新下载了好几次,最后发现没问题只是需要漫长的等待而已。
(2)('/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/cv2/data/haarcascade_frontalface_default.xml')这一段的位置之前写错了一直找不到文件,后来找到正确的位置并且要确保没有打错,然后成功了。
(3)
faces=face_cascade.detectMultiScale(gray,1.3,5)
这行一直报错,后来发现是1.3打成了1,3,所以一定要检查不要打错标点!!!
(4)做第二部分多人脸识别的时候出现了打不开图片的情况,后来换了一张照片就打开了,需要确保照片和文件在一个文件夹且不能通过重命名更改图片格式为jpg,那样是打不开的。