test_camshift.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #!/usr/bin/env python
  2. '''
  3. Camshift tracker
  4. ================
  5. This is a demo that shows mean-shift based tracking
  6. You select a color objects such as your face and it tracks it.
  7. This reads from video camera (0 by default, or the camera number the user enters)
  8. http://www.robinhewitt.com/research/track/camshift.html
  9. '''
  10. # Python 2/3 compatibility
  11. from __future__ import print_function
  12. import sys
  13. PY3 = sys.version_info[0] == 3
  14. if PY3:
  15. xrange = range
  16. import numpy as np
  17. import cv2 as cv
  18. from tst_scene_render import TestSceneRender
  19. from tests_common import NewOpenCVTests, intersectionRate
  20. class camshift_test(NewOpenCVTests):
  21. framesNum = 300
  22. frame = None
  23. selection = None
  24. drag_start = None
  25. show_backproj = False
  26. track_window = None
  27. render = None
  28. errors = 0
  29. def prepareRender(self):
  30. self.render = TestSceneRender(self.get_sample('samples/data/pca_test1.jpg'), deformation = True)
  31. def runTracker(self):
  32. framesCounter = 0
  33. self.selection = True
  34. xmin, ymin, xmax, ymax = self.render.getCurrentRect()
  35. self.track_window = (xmin, ymin, xmax - xmin, ymax - ymin)
  36. while True:
  37. framesCounter += 1
  38. self.frame = self.render.getNextFrame()
  39. hsv = cv.cvtColor(self.frame, cv.COLOR_BGR2HSV)
  40. mask = cv.inRange(hsv, np.array((0., 60., 32.)), np.array((180., 255., 255.)))
  41. if self.selection:
  42. x0, y0, x1, y1 = self.render.getCurrentRect() + 50
  43. x0 -= 100
  44. y0 -= 100
  45. hsv_roi = hsv[y0:y1, x0:x1]
  46. mask_roi = mask[y0:y1, x0:x1]
  47. hist = cv.calcHist( [hsv_roi], [0], mask_roi, [16], [0, 180] )
  48. cv.normalize(hist, hist, 0, 255, cv.NORM_MINMAX)
  49. self.hist = hist.reshape(-1)
  50. self.selection = False
  51. if self.track_window and self.track_window[2] > 0 and self.track_window[3] > 0:
  52. self.selection = None
  53. prob = cv.calcBackProject([hsv], [0], self.hist, [0, 180], 1)
  54. prob &= mask
  55. term_crit = ( cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 1 )
  56. _track_box, self.track_window = cv.CamShift(prob, self.track_window, term_crit)
  57. trackingRect = np.array(self.track_window)
  58. trackingRect[2] += trackingRect[0]
  59. trackingRect[3] += trackingRect[1]
  60. if intersectionRate(self.render.getCurrentRect(), trackingRect) < 0.4:
  61. self.errors += 1
  62. if framesCounter > self.framesNum:
  63. break
  64. self.assertLess(float(self.errors) / self.framesNum, 0.4)
  65. def test_camshift(self):
  66. self.prepareRender()
  67. self.runTracker()
  68. if __name__ == '__main__':
  69. NewOpenCVTests.bootstrap()