Loads images from a directory or video, resizes them to a uniform size, then converts and stacks them into a single [N, 3, H, W] PyTorch tensor.
(path='data/truck', interval=1, PIXEL_LIMIT=255000)
| 9 | import numpy as np |
| 10 | |
| 11 | def load_images_as_tensor(path='data/truck', interval=1, PIXEL_LIMIT=255000): |
| 12 | """ |
| 13 | Loads images from a directory or video, resizes them to a uniform size, |
| 14 | then converts and stacks them into a single [N, 3, H, W] PyTorch tensor. |
| 15 | """ |
| 16 | sources = [] |
| 17 | |
| 18 | # --- 1. Load image paths or video frames --- |
| 19 | if osp.isdir(path): |
| 20 | print(f"Loading images from directory: {path}") |
| 21 | filenames = sorted([x for x in os.listdir(path) if x.lower().endswith(('.png', '.jpg', '.jpeg'))]) |
| 22 | for i in range(0, len(filenames), interval): |
| 23 | img_path = osp.join(path, filenames[i]) |
| 24 | try: |
| 25 | sources.append(Image.open(img_path).convert('RGB')) |
| 26 | except Exception as e: |
| 27 | print(f"Could not load image {filenames[i]}: {e}") |
| 28 | elif path.lower().endswith('.mp4'): |
| 29 | print(f"Loading frames from video: {path}") |
| 30 | cap = cv2.VideoCapture(path) |
| 31 | if not cap.isOpened(): raise IOError(f"Cannot open video file: {path}") |
| 32 | frame_idx = 0 |
| 33 | while True: |
| 34 | ret, frame = cap.read() |
| 35 | if not ret: break |
| 36 | if frame_idx % interval == 0: |
| 37 | rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) |
| 38 | sources.append(Image.fromarray(rgb_frame)) |
| 39 | frame_idx += 1 |
| 40 | cap.release() |
| 41 | else: |
| 42 | raise ValueError(f"Unsupported path. Must be a directory or a .mp4 file: {path}") |
| 43 | |
| 44 | if not sources: |
| 45 | print("No images found or loaded.") |
| 46 | return torch.empty(0) |
| 47 | |
| 48 | print(f"Found {len(sources)} images/frames. Processing...") |
| 49 | |
| 50 | # --- 2. Determine a uniform target size for all images based on the first image --- |
| 51 | # This is necessary to ensure all tensors have the same dimensions for stacking. |
| 52 | first_img = sources[0] |
| 53 | W_orig, H_orig = first_img.size |
| 54 | scale = math.sqrt(PIXEL_LIMIT / (W_orig * H_orig)) if W_orig * H_orig > 0 else 1 |
| 55 | W_target, H_target = W_orig * scale, H_orig * scale |
| 56 | k, m = round(W_target / 14), round(H_target / 14) |
| 57 | while (k * 14) * (m * 14) > PIXEL_LIMIT: |
| 58 | if k / m > W_target / H_target: k -= 1 |
| 59 | else: m -= 1 |
| 60 | TARGET_W, TARGET_H = max(1, k) * 14, max(1, m) * 14 |
| 61 | print(f"All images will be resized to a uniform size: ({TARGET_W}, {TARGET_H})") |
| 62 | |
| 63 | # --- 3. Resize images and convert them to tensors in the [0, 1] range --- |
| 64 | tensor_list = [] |
| 65 | # Define a transform to convert a PIL Image to a CxHxW tensor and normalize to [0,1] |
| 66 | to_tensor_transform = transforms.ToTensor() |
| 67 | |
| 68 | for img_pil in sources: |