人脸检测

2 篇文章 0 订阅
1 篇文章 0 订阅

大家应该都知道,目前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')





 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值