Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/python/peopledetect.py
16337 views
1
#!/usr/bin/env python
2
3
'''
4
example to detect upright people in images using HOG features
5
6
Usage:
7
peopledetect.py <image_names>
8
9
Press any key to continue, ESC to stop.
10
'''
11
12
# Python 2/3 compatibility
13
from __future__ import print_function
14
15
import numpy as np
16
import cv2 as cv
17
18
19
def inside(r, q):
20
rx, ry, rw, rh = r
21
qx, qy, qw, qh = q
22
return rx > qx and ry > qy and rx + rw < qx + qw and ry + rh < qy + qh
23
24
25
def draw_detections(img, rects, thickness = 1):
26
for x, y, w, h in rects:
27
# the HOG detector returns slightly larger rectangles than the real objects.
28
# so we slightly shrink the rectangles to get a nicer output.
29
pad_w, pad_h = int(0.15*w), int(0.05*h)
30
cv.rectangle(img, (x+pad_w, y+pad_h), (x+w-pad_w, y+h-pad_h), (0, 255, 0), thickness)
31
32
33
if __name__ == '__main__':
34
import sys
35
from glob import glob
36
import itertools as it
37
38
print(__doc__)
39
40
hog = cv.HOGDescriptor()
41
hog.setSVMDetector( cv.HOGDescriptor_getDefaultPeopleDetector() )
42
43
default = ['../data/basketball2.png '] if len(sys.argv[1:]) == 0 else []
44
45
for fn in it.chain(*map(glob, default + sys.argv[1:])):
46
print(fn, ' - ',)
47
try:
48
img = cv.imread(fn)
49
if img is None:
50
print('Failed to load image file:', fn)
51
continue
52
except:
53
print('loading error')
54
continue
55
56
found, w = hog.detectMultiScale(img, winStride=(8,8), padding=(32,32), scale=1.05)
57
found_filtered = []
58
for ri, r in enumerate(found):
59
for qi, q in enumerate(found):
60
if ri != qi and inside(r, q):
61
break
62
else:
63
found_filtered.append(r)
64
draw_detections(img, found)
65
draw_detections(img, found_filtered, 3)
66
print('%d (%d) found' % (len(found_filtered), len(found)))
67
cv.imshow('img', img)
68
ch = cv.waitKey()
69
if ch == 27:
70
break
71
cv.destroyAllWindows()
72
73