Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. class VideoStream:
  2. """
  3. Interface to provide easy iteration and indexing access to imageio
  4. video objects:
  5. self[10] returns the 10^th frame of the video.
  6. self[10:20] returns frames 10-20 as a list
  7. """
  8. def __init__(self, file:str, color:bool=True):
  9. """
  10. file : str
  11. uri of video file
  12. color : bool
  13. Pass true for VideoStream to return color images. Pass false
  14. for VideoStream to return b+w images. Defaults to True.
  15. """
  16. self.video = imageio.get_reader(file, 'ffmpeg')
  17. self.color = color
  18.  
  19. self.duration = self.video.get_meta_data()['duration']
  20. self.fps = self.video.get_meta_data()['fps']
  21. self.nframes = self.video.get_meta_data()['nframes']
  22. if self.color:
  23. self.shape = (*self.video.get_meta_data()['size'][::-1], 3)
  24. else:
  25. self.shape = (*self.video.get_meta_data()['size'][::-1], 1)
  26.  
  27. self.index = 0
  28.  
  29. def __len__(self):
  30. """
  31. Returns number of frames in video.
  32. """
  33. return self.nframes
  34.  
  35. def __getitem__(self, index):
  36. """
  37. Returns single frame if index is int or a list of frames if index is a slice.
  38. """
  39. if isinstance(index, slice):
  40. indices = range(*index.indices(len(self)))
  41. return (self._get_frame(i) for i in indices)
  42. else:
  43. return self._get_frame(index)
  44.  
  45. def __next__(self):
  46. if self.index >= len(self):
  47. raise StopIteration
  48. else:
  49. self.index += 1
  50. return self.__getitem__(self.index-1)
  51.  
  52. def __iter__(self):
  53. return self
  54.  
  55. def _get_frame(self, index:int):
  56. frame = self.video.get_data(index)
  57. if self.color:
  58. return frame
  59. else:
  60. return color.rgb2gray(frame)
  61.  
  62. def set_color(self, color:bool):
  63. """
  64. color : bool
  65. Pass true for VideoStream to return color images. Pass false
  66. for VideoStream to return b+w images.
  67. """
  68. self.color = color
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement