学习目标

原理



实现

import cv2 as cv
print(cv.__file__)
路径:E:\Anaconda3\envs\test_py3.6\Lib\site-packages\cv2\data


代码实现
import cv2 as cv
import matplotlib.pyplot as plt
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']
#1,以灰度图的形式读取图片
img = cv.imread("ll.jpg")
gray = cv.cvtColor(img , cv.COLOR_BGR2GRAY)
#2,实例化OpenCV人脸 和 眼睛识别的分类器
face_cas = cv.CascadeClassifier("haarcascade_frontalface_default.xml")
face_cas.load("haarcascade_frontalface_default.xml") #加载已训练好的人脸识别模型
eyes_cas = cv.CascadeClassifier("haarcascade_eye.xml")
eyes_cas.load("haarcascade_eye.xml") #加载已训练好的眼睛识别模型
#3,调用识别人脸
'''gray: 输入灰度图像;
scaleFactor: 图像缩放比例,即在前一张图像的基础上,将图像缩小的比例,默认为 1.1;
minNeighbors: 每个矩形应该保留的邻居数,这个参数可以理解为减少误检的一个参数。默认为 3,可以根据实际情况调整;
minSize: 目标矩形的最小大小,小于这个尺寸的矩形会被忽略,默认为 (30, 30),这里设置为 (32, 32)。'''
faceRects = face_cas.detectMultiScale( gray,scaleFactor=1.2,minNeighbors=10,minSize=(32,32))
for faceRect in faceRects: #遍历所有检测到的人脸矩形框
x,y,w,h = faceRect #获取当前人脸矩形框的坐标和大小
#框出人脸
cv.rectangle(img,(x,y),(x+h,y+w),(0,255,0),3)
#4,在识别出的人脸中进行眼睛检测
roi_color = img[y:y+h,x:x+w] #提取当前人脸区域的彩色图像
roi_gray = gray[y:y+h,x:x+w] #提取当前人脸区域的灰度图像
eyes = eyes_cas.detectMultiScale(roi_gray) #在当前人脸区域检测眼睛,并返回检测到的眼睛矩形框数组
for (ex,ey,ew,eh) in eyes: #遍历所有检测到的眼睛矩形框
cv.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
#检测结果绘制
plt.figure(figsize=(8,6),dpi=100)
plt.imshow(img[:,:,::-1]),plt.title("检测结果")
plt.show()
结果展示
