utils.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. from __future__ import division
  2. from time import sleep
  3. from threading import Thread
  4. from numpy import array, diag, dot, cos, sin
  5. from src import RectangularArea
  6. class BoundingBoxArea(RectangularArea):
  7. def __init__(self, x, y, points):
  8. super(BoundingBoxArea, self).__init__(x, y, 0, 0)
  9. self.points = array(points).T
  10. self.update_bounds()
  11. def translate_points(self, tx, ty):
  12. self.points += [[tx], [ty]]
  13. def scale_points(self, scale, cx, cy):
  14. self.translate_points(-cx, -cy)
  15. self.points = dot(diag([scale, scale]), self.points)
  16. self.translate_points(cx, cy)
  17. def rotate_points(self, angle, cx, cy):
  18. cosa = cos(angle)
  19. sina = sin(angle)
  20. mat = array([[cosa, -sina], [sina, cosa]])
  21. self.translate_points(-cx, -cy)
  22. self.points = dot(mat, self.points)
  23. self.translate_points(cx, cy)
  24. def update_bounds(self):
  25. min_x, min_y = self.points.min(1)
  26. max_x, max_y = self.points.max(1)
  27. self.set_size(max_x - min_x, max_y - min_y)
  28. if min_x or min_y:
  29. self.translate(min_x, min_y)
  30. self.translate_points(-min_x, -min_y)
  31. FLICK_UPDATE_RATE = 30
  32. class Flick(object):
  33. def __init__(self, callback, seconds, start_amount=1.0):
  34. self.callback = callback
  35. self.amount = start_amount
  36. self.iterations = int(seconds * FLICK_UPDATE_RATE)
  37. self.reduce_rate = start_amount / self.iterations
  38. def iteration(self):
  39. self.callback(self.amount)
  40. self.amount -= self.reduce_rate
  41. self.iterations -= 1
  42. return self.is_not_done()
  43. def is_not_done(self):
  44. return self.iterations > 0
  45. def is_done(self):
  46. return self.iterations <= 0
  47. class FlickThread(Thread):
  48. def __init__(self):
  49. super(FlickThread, self).__init__()
  50. self.flicks = []
  51. def run(self):
  52. while True:
  53. self.flicks = filter(Flick.iteration, self.flicks)
  54. sleep(1 / FLICK_UPDATE_RATE)
  55. def add(self, flick):
  56. self.flicks.append(flick)