opencv/samples/python/peopledetect.py

72 lines
2.0 KiB
Python
Raw Normal View History

2013-03-06 07:41:02 +01:00
#!/usr/bin/env python
2015-12-15 00:33:55 +01:00
'''
example to detect upright people in images using HOG features
Usage:
peopledetect.py <image_names>
Press any key to continue, ESC to stop.
'''
# Python 2/3 compatibility
from __future__ import print_function
2012-10-17 01:18:30 +02:00
import numpy as np
import cv2
def inside(r, q):
rx, ry, rw, rh = r
qx, qy, qw, qh = q
return rx > qx and ry > qy and rx + rw < qx + qw and ry + rh < qy + qh
2015-12-15 00:33:55 +01:00
2012-10-17 01:18:30 +02:00
def draw_detections(img, rects, thickness = 1):
for x, y, w, h in rects:
# the HOG detector returns slightly larger rectangles than the real objects.
# so we slightly shrink the rectangles to get a nicer output.
pad_w, pad_h = int(0.15*w), int(0.05*h)
cv2.rectangle(img, (x+pad_w, y+pad_h), (x+w-pad_w, y+h-pad_h), (0, 255, 0), thickness)
if __name__ == '__main__':
import sys
from glob import glob
import itertools as it
2015-12-15 00:33:55 +01:00
print(__doc__)
2012-10-17 01:18:30 +02:00
hog = cv2.HOGDescriptor()
hog.setSVMDetector( cv2.HOGDescriptor_getDefaultPeopleDetector() )
default = ['../data/basketball2.png '] if len(sys.argv[1:]) == 0 else []
2015-12-15 00:33:55 +01:00
for fn in it.chain(*map(glob, default + sys.argv[1:])):
print(fn, ' - ',)
2012-10-17 01:18:30 +02:00
try:
img = cv2.imread(fn)
2013-03-06 07:41:02 +01:00
if img is None:
print('Failed to load image file:', fn)
2013-03-06 07:41:02 +01:00
continue
2012-10-17 01:18:30 +02:00
except:
print('loading error')
2012-10-17 01:18:30 +02:00
continue
found, w = hog.detectMultiScale(img, winStride=(8,8), padding=(32,32), scale=1.05)
found_filtered = []
for ri, r in enumerate(found):
for qi, q in enumerate(found):
if ri != qi and inside(r, q):
break
else:
found_filtered.append(r)
draw_detections(img, found)
draw_detections(img, found_filtered, 3)
print('%d (%d) found' % (len(found_filtered), len(found)))
2012-10-17 01:18:30 +02:00
cv2.imshow('img', img)
ch = 0xFF & cv2.waitKey()
if ch == 27:
break
cv2.destroyAllWindows()