MCPcopy Create free account
hub / github.com/ImprintLab/Medical-SAM2 / load_video_frames

Function load_video_frames

sam2_train/utils/misc.py:163–213  ·  view source on GitHub ↗

Load the video frames from a directory of JPEG files (" .jpg" format). The frames are resized to image_size x image_size and are loaded to GPU if `offload_video_to_cpu` is `False` and to CPU if `offload_video_to_cpu` is `True`. You can load a frame asynchronously by se

(
    video_path,
    image_size,
    offload_video_to_cpu,
    img_mean=(0.485, 0.456, 0.406),
    img_std=(0.229, 0.224, 0.225),
    async_loading_frames=False,
)

Source from the content-addressed store, hash-verified

161
162
163def load_video_frames(
164 video_path,
165 image_size,
166 offload_video_to_cpu,
167 img_mean=(0.485, 0.456, 0.406),
168 img_std=(0.229, 0.224, 0.225),
169 async_loading_frames=False,
170):
171 """
172 Load the video frames from a directory of JPEG files ("<frame_index>.jpg" format).
173
174 The frames are resized to image_size x image_size and are loaded to GPU if
175 `offload_video_to_cpu` is `False` and to CPU if `offload_video_to_cpu` is `True`.
176
177 You can load a frame asynchronously by setting `async_loading_frames` to `True`.
178 """
179 if isinstance(video_path, str) and os.path.isdir(video_path):
180 jpg_folder = video_path
181 else:
182 raise NotImplementedError("Only JPEG frames are supported at this moment")
183
184 frame_names = [
185 p
186 for p in os.listdir(jpg_folder)
187 if os.path.splitext(p)[-1] in [".jpg", ".jpeg", ".JPG", ".JPEG"]
188 ]
189 frame_names.sort(key=lambda p: int(os.path.splitext(p)[0]))
190 num_frames = len(frame_names)
191 if num_frames == 0:
192 raise RuntimeError(f"no images found in {jpg_folder}")
193 img_paths = [os.path.join(jpg_folder, frame_name) for frame_name in frame_names]
194 img_mean = torch.tensor(img_mean, dtype=torch.float32)[:, None, None]
195 img_std = torch.tensor(img_std, dtype=torch.float32)[:, None, None]
196
197 if async_loading_frames:
198 lazy_images = AsyncVideoFrameLoader(
199 img_paths, image_size, offload_video_to_cpu, img_mean, img_std
200 )
201 return lazy_images, lazy_images.video_height, lazy_images.video_width
202
203 images = torch.zeros(num_frames, 3, image_size, image_size, dtype=torch.float32)
204 for n, img_path in enumerate(tqdm(img_paths, desc="frame loading (JPEG)")):
205 images[n], video_height, video_width = _load_img_as_tensor(img_path, image_size)
206 if not offload_video_to_cpu:
207 images = images.cuda()
208 img_mean = img_mean.cuda()
209 img_std = img_std.cuda()
210 # normalize by mean and std
211 images -= img_mean
212 images /= img_std
213 return images, video_height, video_width
214
215def load_video_frames_from_data(
216 imgs_tensor,

Callers 1

init_stateMethod · 0.90

Calls 2

_load_img_as_tensorFunction · 0.85

Tested by

no test coverage detected