媒体大数据 OpenCV+Dlib+FR人脸识别和对齐
1.demo_1:人脸识别定位(仅opencv)
首先需要下载安装opencv-python
pip install opencv-python
运行以下代码
import cv2
def detect(filename):
face_cascade = cv2.CascadeClassifier('C:/Users/zxy/Anaconda3/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml')
// 此处的链接是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)
cv2.imshow('Person Detected!', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == '__main__':
detect('facedemo2.jpg') //
结果如下↓
2.demo_2人脸识别定位(face_recognition)
需要安装dlib包和face_recognition包
pip install dlib
pip install face_recognition
其中安装dlib包会遇到很多坑,个人遇到的是版本问题。此外还需要下载包
shape_predictor_68_face_landmarks.dat
运行以下程序
import cv2
import dlib
path = "facedemo2.jpg"
img = cv2.imread(path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#人脸分类器
detector = dlib.get_frontal_face_detector()
#获取人脸检测器
predictor = dlib.shape_predictor(r"F:\python39\Lib\site-packages\shape_predictor_68_face_landmarks.dat")
dets = detector(gray, 1)
for face in dets:
shape = predictor(img, face) # 寻找人脸的68个标定点
# 遍历所有点,打印出其坐标,并圈出来
for pt in shape.parts():
pt_pos = (pt.x, pt.y)
cv2.circle(img, pt_pos, 2, (0, 255, 0), 1)
cv2.imshow("image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()