OpenCV 视频人体检测

HOGDescriptor

OpenCV提供了HOGDescriptor函数用于特征提取, 常常被用于做物体检测.

其参数如下.

参数 含义
_winSize sets winSize with given value.
_blockSize sets blockSize with given value.
_blockStride sets blockStride with given value.
_cellSize sets cellSize with given value.
_nbins sets nbins with given value.
_derivAperture sets derivAperture with given value.
_winSigma sets winSigma with given value.
_histogramNormType sets histogramNormType with given value.
_L2HysThreshold sets L2HysThreshold with given value.
_gammaCorrection sets gammaCorrection with given value.
_nlevels sets nlevels with given value.
_signedGradient sets signedGradient with given value.

默认参数值为

1
winSize(64,128), blockSize(16,16), blockStride(8,8), cellSize(8,8), nbins(9), derivAperture(1), winSigma(-1), histogramNormType(HOGDescriptor::L2Hys), L2HysThreshold(0.2), gammaCorrection(true), nlevels(HOGDescriptor::DEFAULT_NLEVELS)

视频人体检测代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#!/usr/local/bin/python
# -*- coding: UTF-8 -*-
import cv2
import numpy as np

def is_inside(o, i):# 判断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(img, (x, y), (x + w, y + h), (0, 255, 255), 2)

capture = cv2.VideoCapture(0) #打开视频,参数为路径;参数为0表示打开笔记本的内置摄像头
print capture.isOpened() #显示打开是否成功
while 1: #循环
ret, img=capture.read() #按帧读取视频 ret-帧状态布尔值,img-图像矩阵
hog = cv2.HOGDescriptor()# 创建HOGDescriptor对象
hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())# 使用OpenCV预训练好的人体识别检测器
found, w = hog.detectMultiScale(img)# 构造了图像金字塔和滑窗,进行检测
print ("w=")
print (w)
found_filtered = []# 存储检测目标
for ri, r in enumerate(found):
for qi, q in enumerate(found):
if ri != qi and is_inside(r, q):
break
else:
found_filtered.append(r)

for person in found_filtered:
draw_person(img, person)
cv2.imshow("Video People Detect", img)
#cv2.imwrite("d_people2.jpg",img)
key=cv2.waitKey(1) #等待键盘输入,间隔1ms waits for a key event infinitely (when [delay]< 0 ) or for [delay] milliseconds,
# print key 鼠标需要点一下视频窗口,使程序接收键盘输入而不是命令行接收键盘输入
if key == 27 : #ESC键的ASCII码
print "detect ESC"
break #退出while循环
capture.release() #释放笔记本摄像头
cv2.destroyAllWindows() #关闭所有图像窗口

运行结果

视频人体检测

实时获取摄像头采集的图像并进行人体检测,效果如下.

img

发现该程序能够较为准确地检测人体.

0%