git:https://github.com/linyi0604/Computer-Vision
1 # coding:utf-8
2
3 import cv2 4
5 filename = "../data/mm3.jpg"
6
7
8 def detect(filename): 9 # 创建检测人脸的对象 要在opencv的目录下找到xml文件,放置到自己项目中
10 face_cascade = cv2.CascadeClassifier("../data/haarcascade_frontalface_default.xml") 11 # 读取图像
12 img = cv2.imread(filename) 13 # 转为灰度图像
14 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 15 # 进行人脸检测
16 faces = face_cascade.detectMultiScale(gray, 1.3, 5) 17 """
18 faces = face_cascade.detectMultiScale(img, scaleFactor, minNeighbors) 19 参数: 20 img: 识别的原图 21 scaleFactor: 迭代时图像的压缩率 22 minNeighbors: 每个人脸矩形保留近邻数目的最小值 23
24 返回值: 25 一个列表,列表里边每一项是一个框起人脸的矩形(x, y, w, h) 26
27 """
28 print(faces) 29 for (x, y, w, h) in faces: 30 # 画出矩形框
31 img = cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2) 32
33 cv2.imshow("Vikings Detected", img) 34 cv2.waitKey() 35
36
37 detect(filename)