File size: 6,918 Bytes
2063000
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.10"
# dependencies = [
#     "datasets",
#     "matplotlib",
#     "pillow",
# ]
# ///

"""
Visualize object detection predictions from a HuggingFace dataset.

This script loads a dataset with object detection predictions and visualizes
the bounding boxes on sample images.

Examples:
    # Visualize the first sample with detections
    uv run visualize-detections.py my-username/detected-objects --first-with-detections

    # Visualize a specific sample
    uv run visualize-detections.py my-username/detected-objects --index 0

    # Visualize multiple random samples
    uv run visualize-detections.py my-username/detected-objects --num-samples 5

    # Save visualizations to files instead of displaying
    uv run visualize-detections.py my-username/detected-objects --num-samples 3 --output-dir ./visualizations

    # Visualize specific split
    uv run visualize-detections.py my-username/detected-objects --split train --num-samples 5
"""

import argparse
import random
from pathlib import Path

import matplotlib.patches as patches
import matplotlib.pyplot as plt
from datasets import load_dataset


def parse_args():
    """Parse command line arguments."""
    parser = argparse.ArgumentParser(
        description="Visualize object detection predictions",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=__doc__,
    )

    parser.add_argument(
        "dataset_id", help="HuggingFace dataset ID (e.g., 'username/dataset')"
    )
    parser.add_argument(
        "--index",
        type=int,
        default=None,
        help="Index of sample to visualize (default: random)",
    )
    parser.add_argument(
        "--num-samples",
        type=int,
        default=1,
        help="Number of samples to visualize (default: 1)",
    )
    parser.add_argument(
        "--first-with-detections",
        action="store_true",
        help="Find and visualize the first sample with detections",
    )
    parser.add_argument(
        "--split", default="train", help="Dataset split to use (default: 'train')"
    )
    parser.add_argument(
        "--image-column",
        default="image",
        help="Name of the image column (default: 'image')",
    )
    parser.add_argument(
        "--objects-column",
        default="objects",
        help="Name of the objects column (default: 'objects')",
    )
    parser.add_argument(
        "--output-dir",
        type=str,
        default=None,
        help="Directory to save visualizations (default: show interactively)",
    )
    parser.add_argument(
        "--figsize-width",
        type=int,
        default=15,
        help="Figure width in inches (default: 15)",
    )
    parser.add_argument(
        "--figsize-height",
        type=int,
        default=20,
        help="Figure height in inches (default: 20)",
    )
    parser.add_argument(
        "--bbox-color",
        default="red",
        help="Color for bounding boxes (default: 'red')",
    )
    parser.add_argument(
        "--show-scores",
        action="store_true",
        default=True,
        help="Show confidence scores on bounding boxes",
    )

    return parser.parse_args()


def visualize_sample(
    sample,
    image_column="image",
    objects_column="objects",
    figsize=(15, 20),
    bbox_color="red",
    show_scores=True,
    title=None,
):
    """Visualize a single sample with bounding boxes."""
    image = sample[image_column]
    objects = sample[objects_column]

    fig, ax = plt.subplots(1, figsize=figsize)
    ax.imshow(image, cmap="gray" if image.mode == "L" else None)

    # Draw bounding boxes
    num_detections = len(objects["bbox"])
    for i in range(num_detections):
        bbox = objects["bbox"][i]
        score = objects["score"][i]
        category = objects["category"][i]

        x, y, w, h = bbox
        rect = patches.Rectangle(
            (x, y), w, h, linewidth=2, edgecolor=bbox_color, facecolor="none"
        )
        ax.add_patch(rect)

        if show_scores:
            label = f"{score:.2f}"
            ax.text(
                x,
                y - 5,
                label,
                color=bbox_color,
                fontsize=10,
                bbox=dict(facecolor="white", alpha=0.7),
            )

    # Set title
    if title:
        ax.set_title(title, fontsize=14, pad=20)
    else:
        ax.set_title(f"Detections: {num_detections}", fontsize=14, pad=20)

    ax.axis("off")
    plt.tight_layout()

    return fig, ax


def main():
    args = parse_args()

    # Load dataset
    print(f"๐Ÿ“‚ Loading dataset: {args.dataset_id} (split: {args.split})")
    dataset = load_dataset(args.dataset_id, split=args.split)
    print(f"โœ… Loaded {len(dataset)} samples")

    # Determine indices to visualize
    if args.index is not None:
        indices = [args.index]
    elif args.first_with_detections:
        # Find first sample with detections
        print("๐Ÿ” Finding first sample with detections...")
        first_idx = None
        for idx in range(len(dataset)):
            sample = dataset[idx]
            if len(sample[args.objects_column]["bbox"]) > 0:
                first_idx = idx
                break

        if first_idx is None:
            print("โŒ No samples with detections found in dataset")
            return

        print(f"โœ… Found first sample with detections at index {first_idx}")
        indices = [first_idx]
    else:
        # Select random samples
        indices = random.sample(range(len(dataset)), min(args.num_samples, len(dataset)))

    # Create output directory if saving
    if args.output_dir:
        output_path = Path(args.output_dir)
        output_path.mkdir(parents=True, exist_ok=True)
        print(f"๐Ÿ’พ Saving visualizations to: {output_path}")

    # Visualize samples
    figsize = (args.figsize_width, args.figsize_height)

    for idx in indices:
        sample = dataset[idx]
        num_detections = len(sample[args.objects_column]["bbox"])

        print(f"\n๐Ÿ–ผ๏ธ  Sample {idx}: {num_detections} detections")

        # Create visualization
        title = f"Sample {idx} - {num_detections} detections"
        fig, ax = visualize_sample(
            sample,
            image_column=args.image_column,
            objects_column=args.objects_column,
            figsize=figsize,
            bbox_color=args.bbox_color,
            show_scores=args.show_scores,
            title=title,
        )

        # Save or show
        if args.output_dir:
            output_file = output_path / f"sample_{idx}.png"
            plt.savefig(output_file, dpi=150, bbox_inches="tight")
            print(f"   Saved: {output_file}")
            plt.close(fig)
        else:
            plt.show()

    if args.output_dir:
        print(f"\nโœ… Saved {len(indices)} visualizations to {args.output_dir}")


if __name__ == "__main__":
    main()