| 27 | sample_frames: int, resolution: int, do_resize: bool = True, **kwargs |
| 28 | ) -> VideoProcessor: |
| 29 | class CustomVideoProcessor(VideoProcessor): |
| 30 | def __init__(self, sample_frames: int, resolution: int, do_resize: bool = True, **kwargs): |
| 31 | self.sample_frames = sample_frames |
| 32 | self.resolution = resolution |
| 33 | super().__init__(do_resize=do_resize, **kwargs) |
| 34 | |
| 35 | def extract_frames(self, frames: List[PIL.Image]) -> List[PIL.Image]: |
| 36 | num_frames = len(frames) |
| 37 | |
| 38 | if num_frames >= 2 * self.sample_frames: |
| 39 | selected_indices = np.linspace( |
| 40 | 0, 2 * self.sample_frames - 1, self.sample_frames, dtype=int |
| 41 | ) |
| 42 | extracted_frames = [frames[i] for i in selected_indices] |
| 43 | elif num_frames >= self.sample_frames: |
| 44 | selected_indices = np.linspace(0, num_frames - 1, self.sample_frames, dtype=int) |
| 45 | extracted_frames = [frames[i] for i in selected_indices] |
| 46 | else: |
| 47 | selected_indices = np.linspace(0, num_frames - 1, self.sample_frames, dtype=int) |
| 48 | extracted_frames = [frames[i % num_frames] for i in selected_indices] |
| 49 | return extracted_frames |
| 50 | |
| 51 | def __call__( |
| 52 | self, |
| 53 | video: Optional[Union[torch.Tensor, List[PIL.Image], List[List[PIL.Image]]]], |
| 54 | height: Optional[int] = None, |
| 55 | width: Optional[int] = None, |
| 56 | ) -> torch.Tensor: |
| 57 | if height == None: |
| 58 | height = self.resolution |
| 59 | if width == None: |
| 60 | width = self.resolution |
| 61 | processed_video = None |
| 62 | if isinstance(video, torch.Tensor): |
| 63 | frames = [Image.fromarray(frame.numpy()) for frame in video] |
| 64 | extract_frames = self.extract_frames(frames) |
| 65 | processed_video = self.preprocess_video(extract_frames, height, width) |
| 66 | else: |
| 67 | processed_video = self.preprocess_video(video, height, width) |
| 68 | if len(processed_video.shape) == 5 and processed_video.size(0) == 1: |
| 69 | processed_video = processed_video.squeeze(0) |
| 70 | return processed_video |
| 71 | |
| 72 | return CustomVideoProcessor(sample_frames, resolution, do_resize, **kwargs) |
| 73 |
no outgoing calls
no test coverage detected