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