peopledetect.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #!/usr/bin/env python
  2. '''
  3. example to detect upright people in images using HOG features
  4. Usage:
  5. peopledetect.py <image_names>
  6. Press any key to continue, ESC to stop.
  7. '''
  8. # Python 2/3 compatibility
  9. from __future__ import print_function
  10. import numpy as np
  11. import cv2
  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. def draw_detections(img, rects, thickness = 1):
  17. for x, y, w, h in rects:
  18. # the HOG detector returns slightly larger rectangles than the real objects.
  19. # so we slightly shrink the rectangles to get a nicer output.
  20. pad_w, pad_h = int(0.15*w), int(0.05*h)
  21. cv2.rectangle(img, (x+pad_w, y+pad_h), (x+w-pad_w, y+h-pad_h), (0, 255, 0), thickness)
  22. if __name__ == '__main__':
  23. import sys
  24. from glob import glob
  25. import itertools as it
  26. print(__doc__)
  27. hog = cv2.HOGDescriptor()
  28. hog.setSVMDetector( cv2.HOGDescriptor_getDefaultPeopleDetector() )
  29. default = ['../data/basketball2.png '] if len(sys.argv[1:]) == 0 else []
  30. for fn in it.chain(*map(glob, default + sys.argv[1:])):
  31. print(fn, ' - ',)
  32. try:
  33. img = cv2.imread(fn)
  34. if img is None:
  35. print('Failed to load image file:', fn)
  36. continue
  37. except:
  38. print('loading error')
  39. continue
  40. found, w = hog.detectMultiScale(img, winStride=(8,8), padding=(32,32), scale=1.05)
  41. found_filtered = []
  42. for ri, r in enumerate(found):
  43. for qi, q in enumerate(found):
  44. if ri != qi and inside(r, q):
  45. break
  46. else:
  47. found_filtered.append(r)
  48. draw_detections(img, found)
  49. draw_detections(img, found_filtered, 3)
  50. print('%d (%d) found' % (len(found_filtered), len(found)))
  51. cv2.imshow('img', img)
  52. ch = 0xFF & cv2.waitKey()
  53. if ch == 27:
  54. break
  55. cv2.destroyAllWindows()