1 #!/usr/bin/env python 2 3 import numpy as np 4 import cv2 5 6 help_message = ''' 7 USAGE: peopledetect.py <image_names> ... 8 9 Press any key to continue, ESC to stop. 10 ''' 11 12 def inside(r, q): 13 rx, ry, rw, rh = r 14 qx, qy, qw, qh = q 15 return rx > qx and ry > qy and rx + rw < qx + qw and ry + rh < qy + qh 16 17 def draw_detections(img, rects, thickness = 1): 18 for x, y, w, h in rects: 19 # the HOG detector returns slightly larger rectangles than the real objects. 20 # so we slightly shrink the rectangles to get a nicer output. 21 pad_w, pad_h = int(0.15*w), int(0.05*h) 22 cv2.rectangle(img, (x+pad_w, y+pad_h), (x+w-pad_w, y+h-pad_h), (0, 255, 0), thickness) 23 24 25 if __name__ == '__main__': 26 import sys 27 from glob import glob 28 import itertools as it 29 30 print help_message 31 32 hog = cv2.HOGDescriptor() 33 hog.setSVMDetector( cv2.HOGDescriptor_getDefaultPeopleDetector() ) 34 35 for fn in it.chain(*map(glob, sys.argv[1:])): 36 print fn, ' - ', 37 try: 38 img = cv2.imread(fn) 39 if img is None: 40 print 'Failed to load image file:', fn 41 continue 42 except: 43 print 'loading error' 44 continue 45 46 found, w = hog.detectMultiScale(img, winStride=(8,8), padding=(32,32), scale=1.05) 47 found_filtered = [] 48 for ri, r in enumerate(found): 49 for qi, q in enumerate(found): 50 if ri != qi and inside(r, q): 51 break 52 else: 53 found_filtered.append(r) 54 draw_detections(img, found) 55 draw_detections(img, found_filtered, 3) 56 print '%d (%d) found' % (len(found_filtered), len(found)) 57 cv2.imshow('img', img) 58 ch = 0xFF & cv2.waitKey() 59 if ch == 27: 60 break 61 cv2.destroyAllWindows() 62