以下代码均在python3.6,opencv4.2.0环境下试了跑一遍,可直接运行。
1、基于OpenCV中自带的HOG的行人检测分类器,实现行人检测
代码语言:javascript复制# *_*coding:utf-8 *_*
import cv2
import numpy as np
img = cv2.imread('person.jpg')
hog = cv2.HOGDescriptor()
hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector()) #使用opencv默认的模型
rects, _ = hog.detectMultiScale(img, winStride=(4,4), padding=(8,8), scale=1.05)
for (x,y,w,h) in rects:
cv2.rectangle(img, (x,y), (x w,y h), (0,0,255), 2)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
运行结果:
2、基于OpenCV中自带的Haar的人脸检测分类器,实现人脸人眼检测
1)人脸检测
代码语言:javascript复制# -*- coding: utf-8 -*-
import cv2
import numpy as np
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
img_path = 'face.jpg'
img = cv2.imread(img_path)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faceRects = face_cascade.detectMultiScale(gray,1.1,5)
for faceRect in faceRects:
x, y, w, h = faceRect
cv2.rectangle(img, (x,y), (x w,y h), (255,0,0), 2, 8, 0)
cv2.namedWindow("image", cv2.WINDOW_AUTOSIZE)
cv2.imshow("image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
运行结果:
2)人脸人眼检测
代码语言:javascript复制# -*- coding: utf-8 -*-
import cv2
import numpy as np
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
eye_cascade = cv2.CascadeClassifier("haarcascade_eye_tree_eyeglasses.xml")
img_path = 'face.jpg'
img = cv2.imread(img_path)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faceRects = face_cascade.detectMultiScale(gray,1.1,5)
l=len(faceRects)
print(l)
for faceRect in faceRects:
x, y, w, h = faceRect
cv2.rectangle(img, (x,y), (x w,y h), (255,0,0), 2, 8, 0)
roi_gray = gray[y:y h,x:x w]
roi_color = img[y:y h,x:x w]
eyes = eye_cascade.detectMultiScale(roi_gray,1.1,1,cv2.CASCADE_SCALE_IMAGE,(2,2))
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color, (ex,ey), (ex ew,ey eh), (0,255,0), 2)
cv2.namedWindow("image", cv2.WINDOW_AUTOSIZE)
cv2.imshow("image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
运行结果:
3、基于OpenCV中自带的LBP的人脸检测分类器,实现人脸检测
代码语言:javascript复制# -*- coding: utf-8 -*-
import cv2
import numpy as np
face_cascade = cv2.CascadeClassifier("lbpcascade_frontalface.xml")
img_path = 'face.jpg'
img = cv2.imread(img_path)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faceRects = face_cascade.detectMultiScale(gray,1.1,5)
for faceRect in faceRects:
x, y, w, h = faceRect
cv2.rectangle(img, (x,y), (x w,y h), (255,0,0), 2, 8, 0)
cv2.namedWindow("image", cv2.WINDOW_AUTOSIZE)
cv2.imshow("image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
运行结果:
以上内容如有错误或者需要补充的,请留言!