opencv人脸识别

基于自带haarcascade识别(效果一般)

# 基于harrcascade识别,需要下载人脸特征数据
# 基于Haar特征的cascade分类器(classifiers) 是Paul Viola和 Michael Jone在2001年,论文”Rapid Object Detection using a Boosted Cascade of Simple Features”中提出的一种有效的物品检测(object detect)方法。它是一种机器学习方法,通过许多正负样例中训练得到cascade方程,然后将其应用于其他图片


ap = argparse.ArgumentParser()
ap.add_argument(
"-i", "--image", required=True, help="path to input image")
args =
vars(ap.parse_args())


# 读取输入数据,预处理
image = cv2.imread(args["image"])
(h, w) = image.shape[:
2]
width =
1024
r = width / float(w)
dim = (width,
int(h * r))
image = cv2.resize(image, dim,
interpolation=cv2.INTER_AREA)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)


# 人脸检测,识别出来,如果有n张脸,就有n个对象,这里必须用完整路径,切实cv2安装目录的
detector = cv2.CascadeClassifier("E:\Program Files\python37\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml")
detector.load(
'E:\Program Files\python37\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml')
faces = detector.detectMultiScale(gray)


# 遍历每张脸,并画出方框
for (x,y,w,h) in faces:
    cv2.rectangle(image, (x,y), (x+w, y+h), (
0,0,255), 2)

cv2.imshow(
'image', image)
cv2.waitKey(
0)
cv2.destroyAllWindows()

基于dlib(效果很好,推荐,可识别五官)

# 导入工具包
import numpy as np
import argparse
import cv2
import dlib

# 基于dlib识别,底层采用深度学习,效果比基于Haar特征的cascade分类器好,推荐
ap = argparse.ArgumentParser()
ap.add_argument(
"-i", "--image", required=True, help="path to input image")
args =
vars(ap.parse_args())


# 读取输入数据,预处理
image = cv2.imread(args["image"])
(h, w) = image.shape[:
2]
width =
1024
r = width / float(w)
dim = (width,
int(h * r))
image = cv2.resize(image, dim,
interpolation=cv2.INTER_AREA)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)


# 人脸检测,采用dlib
detector = dlib.get_frontal_face_detector()
faces = detector(gray,
1)

# 遍历每张脸,并画出方框
for (k, d) in enumerate(faces): #d返回的是一个位置对象
   
print(type(d))
   
print(d)
    image = cv2.rectangle(image, (d.left(), d.top()), (d.right(), d.bottom()), (
0,0,255), 2)

cv2.imshow(
'image', image)
cv2.waitKey(
0)
cv2.destroyAllWindows()

如果是获取摄像头的可以修改代码:

cameraCapture = cv2.VideoCapture(0)

success, frame = cameraCapture.read()

detector = dlib.get_frontal_face_detector()

while success and cv2.waitKey(1) == -1:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yesunx

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值