OpenCV自带了函数 detectMultiScale() 可以实现对行人和人脸的检测,实现简单,但识别效果相对较差。
行人检测
在行人检测上,OpenCV采用的是HOG(特征检测算法)+SVM算法
import cv2 def is_inside(o, i): ox, oy, ow, oh = o ix, iy, iw, ih = i return ox > ix and oy > iy and ox + ow < ix + iw and oy + oh < iy + ih def draw_person(image, person): x, y, w, h = person cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 2) # 使用opencv的hog特征进行行人检测 img = cv2.imread('xingren.jpeg') hog = cv2.HOGDescriptor() hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector()) found, w = hog.detectMultiScale(img) print(found, w) foundList = [] for ri, r in enumerate(found): flag = 0 for qi, q in enumerate(found): if ri != qi and is_inside(r, q): flag = 1 if(flag == 0): foundList.append(r) for person in foundList: draw_person(img, person) cv2.imwrite("./test1.jpg", img)
人脸检测
在人脸检测上,OpenCV采用的是Harr特征,Haar特征值反映了图像的灰度变化情况。例如:脸部的一些特征能由矩形特征简单的描述,如:眼睛要比脸颊颜色要深,鼻梁两侧比鼻梁颜色要深,嘴巴比周围颜色要深等。
import cv2 # 使用人脸识别分类器 classfier = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_alt2.xml") # 读取图片 image = cv2.imread("nba.jpeg") # 转为灰度图 gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) faces = classfier.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(3, 3)) print("发现{0}个人脸!".format(len(faces))) for faceRect in faces: x, y, w, h = faceRect cv2.rectangle(image, (x, y), (x + w, y + w), (0, 255, 0), 2) cv2.imwrite("./face1.jpg", image)
参考资料:
https://www.cnblogs.com/gzshan/p/10702752.html
https://zhuanlan.zhihu.com/p/442915954 OpenCV项目实战---人脸检测
https://blog.csdn.net/qq_42621977/article/details/89321747 python_openCV例程遇到:'cv::CascadeClassifier::detectMultiScale'
https://blog.csdn.net/weixin_51098062/article/details/122524709 基于opencv的人脸检测