大家应该都知道,目前python已经有很多库可以对人脸进行抓取以及找出人脸的特征,进而对人脸进行识别的应用,推荐的库如cv2,dlib,用法一般如下所示:
(1)cv2识别人脸:
path='E:\我的项目\我的机器学习\haarcascade_frontalface_default.xml'
注意这个识别人脸的xml文件在site_packages包里面找
face_obj=cv2.CascadeClassifier(path)
完整代码:
import cv2 import numpy as np import os.path input_data_path = '/usr/local/tensorflow/sample/tf-she-image/original/ella/' save_path = '/usr/local/tensorflow/sample/tf-she-image/face/ella/' cascade_path = '/usr/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml' faceCascade =cv2.CascadeClassifier(cascade_path) image_count = 16000 face_detect_count = 0 for i in range(image_count): if os.path.isfile(input_data_path + str(i) + '.jpg'): try: img = cv2.imread(input_data_path + str(i) + '.jpg', cv2.IMREAD_COLOR) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) face = faceCascade.detectMultiScale(gray, 1.5, 3) if len(face) > 0: for rect in face: x = rect[0] y = rect[1] w = rect[2] h = rect[3] cv2.imwrite(save_path + 'face-' + str(face_detect_count) + '.jpg', img[y:y + h, x:x + w]) face_detect_count = face_detect_count + 1 else: print('image' + str(i) + ': No Face') except Exception as e: print('image' + str(i) + ': Exception - ' + str(e)) else: print('image' + str(i) + ': No File')
(2)利用dlib进行人脸识别:
import dlib import cv2 import os detector=dlib.get_frontal_face_detector() my_num=0 for root,dir,files in os.walk('my_images'): for file in files: my_num+=1 my_path=os.path.join(root,file) img=cv2.imread(my_path) cv2.imshow(',,',img) print(img.shape) dets,scores,indx=detector.run(img,1) for i,d in enumerate(dets): face=img[d.top():d.bottom(),d.left():d.right()] cv2.imwrite('头疼/{}.jpg'.format(str(my_num)),face) # cv2.imshow('1',face) print('ok')