peopledetect.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 as cv
  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. cv.rectangle(img, (x+pad_w, y+pad_h), (x+w-pad_w, y+h-pad_h), (0, 255, 0), thickness)
  22. def main():
  23. import sys
  24. from glob import glob
  25. import itertools as it
  26. hog = cv.HOGDescriptor()
  27. hog.setSVMDetector( cv.HOGDescriptor_getDefaultPeopleDetector() )
  28. default = [cv.samples.findFile('basketball2.png')] if len(sys.argv[1:]) == 0 else []
  29. for fn in it.chain(*map(glob, default + sys.argv[1:])):
  30. print(fn, ' - ',)
  31. try:
  32. img = cv.imread(fn)
  33. if img is None:
  34. print('Failed to load image file:', fn)
  35. continue
  36. except:
  37. print('loading error')
  38. continue
  39. found, _w = hog.detectMultiScale(img, winStride=(8,8), padding=(32,32), scale=1.05)
  40. found_filtered = []
  41. for ri, r in enumerate(found):
  42. for qi, q in enumerate(found):
  43. if ri != qi and inside(r, q):
  44. break
  45. else:
  46. found_filtered.append(r)
  47. draw_detections(img, found)
  48. draw_detections(img, found_filtered, 3)
  49. print('%d (%d) found' % (len(found_filtered), len(found)))
  50. cv.imshow('img', img)
  51. ch = cv.waitKey()
  52. if ch == 27:
  53. break
  54. print('Done')
  55. if __name__ == '__main__':
  56. print(__doc__)
  57. main()
  58. cv.destroyAllWindows()