Datasets:

Modalities:
Image
ArXiv:
License:
JeffreyJsam commited on
Commit
c087755
·
verified ·
1 Parent(s): 0bbdb4d

Update utils/sample_swim.py

Browse files
Files changed (1) hide show
  1. utils/sample_swim.py +110 -0
utils/sample_swim.py CHANGED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ sample_swim.py
3
+
4
+ Streams and saves a sample of paired images and labels from a Hugging Face dataset repository.
5
+
6
+ Default configuration:
7
+ - Repo: "JeffreyJsam/SWiM-SpacecraftWithMasks"
8
+ - Image subdir: "Baseline/images/val/000"
9
+ - Label subdir: "Baseline/labels/val/000"
10
+ - Saves the first 500 matched image/txt files by default.
11
+
12
+ This script is useful for quick local inspection, prototyping, or lightweight evaluation
13
+ without downloading the full dataset.
14
+
15
+ Usage:
16
+ python utils/sample_swim.py --output-dir ./samples --count 100
17
+
18
+ Arguments:
19
+ --repo-id Hugging Face dataset repository ID
20
+ --image-subdir Path to image subdirectory inside the dataset repo
21
+ --label-subdir Path to corresponding label subdirectory
22
+ --output-dir Directory to save downloaded files
23
+ --count Number of samples to download
24
+ """
25
+
26
+ import argparse
27
+ from io import BytesIO
28
+ from pathlib import Path
29
+ from huggingface_hub import list_repo_tree, hf_hub_url
30
+ from huggingface_hub.hf_api import RepoFile
31
+ import fsspec
32
+ from PIL import Image
33
+ from tqdm import tqdm
34
+
35
+ def sample_dataset(
36
+ repo_id: str,
37
+ image_subdir: str,
38
+ label_subdir: str,
39
+ output_dir: str,
40
+ max_files: int = 500,
41
+ ):
42
+
43
+
44
+
45
+ image_files = list_repo_tree(
46
+ repo_id=repo_id,
47
+ path_in_repo=image_subdir,
48
+ repo_type="dataset",
49
+ recursive=True
50
+ )
51
+
52
+ count = 0
53
+ for img_file in tqdm(image_files, desc="Downloading samples"):
54
+ if not isinstance(img_file, RepoFile) or not img_file.path.lower().endswith((".png")):
55
+ continue
56
+
57
+ # Relative path after the image_subdir (e.g., img_0001.png)
58
+ rel_path = Path(img_file.path).relative_to(image_subdir)
59
+ label_path = f"{label_subdir}/{rel_path.with_suffix('.txt')}" # Change extension to .txt
60
+
61
+ image_url = hf_hub_url(repo_id=repo_id, filename=img_file.path, repo_type="dataset")
62
+ label_url = hf_hub_url(repo_id=repo_id, filename=label_path, repo_type="dataset")
63
+
64
+ local_image_path = Path(output_dir) / img_file.path
65
+ local_label_path = Path(output_dir) / label_path
66
+
67
+ local_image_path.parent.mkdir(parents=True, exist_ok=True)
68
+ local_label_path.parent.mkdir(parents=True, exist_ok=True)
69
+
70
+ try:
71
+ # Download and save the image
72
+ with fsspec.open(image_url) as f:
73
+ image = Image.open(BytesIO(f.read()))
74
+ image.save(local_image_path)
75
+
76
+ # Download and save the corresponding .txt label
77
+ with fsspec.open(label_url) as f:
78
+ txt_content = f.read()
79
+ with open(local_label_path, "wb") as out_f:
80
+ out_f.write(txt_content)
81
+
82
+ # print(f"[{count+1}] {rel_path} and {rel_path.with_suffix('.txt')}")
83
+ count += 1
84
+ except Exception as e:
85
+ print(f" Failed {rel_path}: {e}")
86
+
87
+ if count >= max_files:
88
+ break
89
+
90
+ print(f" Downloaded {count} image/txt pairs.")
91
+ print(f" Saved under: {Path(output_dir).resolve()}")
92
+
93
+ def parse_args():
94
+ parser = argparse.ArgumentParser(description="Stream and sample paired images + txt labels from a Hugging Face folder-structured dataset.")
95
+ parser.add_argument("--repo-id", required=False, default = "JeffreyJsam/SWiM-SpacecraftWithMasks",help="Hugging Face dataset repo ID.")
96
+ parser.add_argument("--image-subdir", required=False, default = "Baseline/images/val/000", help="Subdirectory path for images.")
97
+ parser.add_argument("--label-subdir", required=False, default="Baseline/labels/val/000", help="Subdirectory path for txt masks.")
98
+ parser.add_argument("--output-dir", default="./Sampled-SWiM", help="Where to save sampled data.")
99
+ parser.add_argument("--count", type=int, default=500, help="How many samples to download.")
100
+ return parser.parse_args()
101
+
102
+ if __name__ == "__main__":
103
+ args = parse_args()
104
+ sample_dataset(
105
+ repo_id=args.repo_id,
106
+ image_subdir=args.image_subdir,
107
+ label_subdir=args.label_subdir,
108
+ output_dir=args.output_dir,
109
+ max_files=args.count,
110
+ )