OpenCV python 人脸检测
检测图片:source.jpg
所需xml文件
haarcascade_frontalface_default.xml
import cv2
def main():
# 1.导入图片
img_face = cv2.imread("source.jpg")
img_gary = cv2.cvtColor(img_face, cv2.COLOR_BGR2GRAY)
# 2.脸部识别 级联分类器
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
# 3.执行脸部识别
faces = face_cascade.detectMultiScale(
img_gary,
scaleFactor=1.15,
minNeighbors=6,
minSize=(5, 5)
)
# 4.打印信息
print(faces)
print("发现%d人脸!" % len(faces))
# 5.显示结果
for (x, y, w, h) in faces:
cv2.circle(img_face, (int((x + x + w) / 2), int((y + y + h) / 2)), int(w / 2), (0, 255, 0), 2)
cv2.imshow("img_face", img_face)
cv2.waitKey()
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
处理结果
人脸检测方法二
文件下载地址
链接: https://pan.baidu.com/s/1zgBEWllFIxrgazOIcl0csQ 提取码: 4cuc
import cv2 as cv
import os
# 哈尔级联人脸定位器
fd = cv.CascadeClassifier('./haar/face.xml') # 人脸
ed = cv.CascadeClassifier('./haar/eye.xml') # 眼睛
nd = cv.CascadeClassifier('./haar/nose.xml') # 鼻子
def search_files(directory):
"""
检索目录下的所有wav文件 返回目录字典
{“appple”:[url, url...],
“kiwi”:[url, url...],....}
"""
files_dict = {}
for cur_dir, sub_dirs, files in os.walk(directory):
for file in files:
if file.endswith(".jpg"):
label = cur_dir.split(os.path.sep)[-1]
if label not in files_dict:
files_dict[label] = []
url = os.path.join(cur_dir, file)
files_dict[label].append(url)
return files_dict
# 搜索训练集 文件夹中的图片
files_dir = search_files("./faces/training")
# print(files_dir)
for name, file_paths in files_dir.items():
for file_path in file_paths:
# 读取图片
frame = cv.imread(file_path)
# 人脸检测
faces = fd.detectMultiScale(frame, 1.3, 5)
for l, t, w, h in faces: # 绘制人脸
a, b = int(w / 2), int(h / 2)
cv.ellipse(frame, (l + a, t + b), (a, b), 0, 0, 360, (255, 0, 255), 2)
face = frame[t:t + h, l:l + w]
# 眼睛检测
eyes = ed.detectMultiScale(face, 1.3, 5)
for l, t, w, h in eyes:
a, b = int(w / 2), int(h / 2)
cv.ellipse(face, (l + a, t + b), (a, b), 0, 0, 360, (0, 255, 0), 2)
# 鼻子检测
noses = nd.detectMultiScale(face, 1.3, 5)
for l, t, w, h in noses:
a, b = int(w / 2), int(h / 2)
cv.ellipse(face, (l + a, t + b), (a, b), 0, 0, 360, (0, 255, 255), 2)
# 显示检测结果
cv.imshow('face', frame)
if cv.waitKey(1000) == 27:
break
cv.destroyAllWindows()