在开始之前,你得先做如下准备:
pip install opencv-python
安装即可。pip install dlib
安装,如果报错的话,再自行百度吧,我是折腾了一下午才弄好。shape_predictor_68_face_landmarks.dat
代码部分实现起来非常简单,不过十几行的事,不过需要注意的是,通过cv2.imread
读取的图片是BRG通道的,需要转成RGB通道,不然通过pyplot
显示图片会变色。
import cv2
import dlib
import matplotlib.pyplot as plt
import numpy as np
predictor_path = 'shape_predictor_68_face_landmarks.dat'
test_img = 'test.png'
img = cv2.imread(test_img)
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictor_path)
faces = detector(img, 0)
if len(faces):
print '==> Found %d face in this image.' % len(faces)
for i in range(len(faces)):
landmarks = np.matrix([[p.x, p.y] for p in predictor(img, faces[i]).parts()])
for point in landmarks:
pos = (point[0, 0], point[0, 1])
cv2.circle(img, pos, 3, color=(0, 255, 0),thickness=3)
else:
print 'Face not found!'
# opencv读取图片是BRG通道的,需要专成RGB
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.figure(figsize=(10, 8))
plt.subplot(121)
plt.imshow(plt.imread(test_img))
plt.axis('off')
plt.subplot(122)
plt.imshow(img)
plt.axis('off')
plt.show()
68点人脸检测
我们可以通过cv2.VideoCapture(0)
调起摄像头,camera.read
会返回两个参数,第一个代表是否获取到图像帧,第二个代表图像帧内容,剩下的部分就跟上面一样了,传给dlib进行人脸检测就好了。
# -*- coding: utf-8 -*-
# @author: Awesome_Tang
# @date: 2018-12-31
# @version: python2.7
import cv2
import dlib
import numpy as np
import os
class Config(object):
predictor_path = 'shape_predictor_68_face_landmarks.dat'
test_img = 'test.jpg'
width = 640
height = 480
class FaceDetective():
def __init__(self):
self.detector = dlib.get_frontal_face_detector()
self.predictor = dlib.shape_predictor(Config.predictor_path)
def check_file(self,path):
if os.path.exists(path):
img = cv2.imread(path)
return img
else:
raise IOError('No such file : "%s", please check!' % path)
def detective(self, frame):
faces = self.detector(frame, 0)
if len(faces):
print '==> Found %d face in this frame.' % len(faces)
for i in range(len(faces)):
landmarks = np.matrix([[p.x, p.y] for p in self.predictor(frame, faces[i]).parts()])
for point in landmarks:
pos = (point[0, 0], point[0, 1])
cv2.circle(frame, pos, 3, color=(0, 0, 255),thickness=3)
else:
print 'Face not found!'
return frame
def run_camera(self):
camera = cv2.VideoCapture(0)
camera.set(cv2.CAP_PROP_FRAME_WIDTH, Config.width)
camera.set(cv2.CAP_PROP_FRAME_HEIGHT, Config.height)
while True:
detected, frame = camera.read()
if detected:
frame = cv2.flip(frame, 1)
frame = self.detective(frame)
cv2.imshow("AwesomeTang", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
camera.release()
cv2.destroyAllWindows()
def single_image(self,img_path):
img = self.check_file(img_path)
img = self.detective(img)
cv2.namedWindow("AwesomeTang", 0)
cv2.resizeWindow("AwesomeTang", Config.width, Config.height)
cv2.imshow("AwesomeTang",img)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == '__main__':
p = FaceDetective()
#p.single_image(Config.test_img)
p.run_camera()
skr~ skr~~