""" Create a visual grid of all training crops with bounding boxes. """ from pathlib import Path from PIL import Image, ImageDraw, ImageFont import json TRAIN_DIR = Path(__file__).resolve().parent / "finetune_data" # Load annotations with open(TRAIN_DIR / "crops_annotation.json") as f: crops = json.load(f) # Create grid: 3 columns x 5 rows cols = 4 rows = (len(crops) + cols - 1) // cols # Get first crop to determine size first_crop = Image.open(TRAIN_DIR / "crops" / crops[0]["image_path"]) crop_w, crop_h = first_crop.size # Grid parameters padding = 20 grid_w = cols * (crop_w + padding) + padding grid_h = rows * (crop_h + padding + 40) + padding # Extra space for label grid = Image.new("RGB", (grid_w, grid_h), (40, 40, 40)) draw = ImageDraw.Draw(grid) font = ImageFont.load_default() # Place crops in grid for idx, crop_info in enumerate(crops): col = idx % cols row = idx // cols x_pos = col * (crop_w + padding) + padding y_pos = row * (crop_h + padding + 40) + padding # Load and paste crop crop_img = Image.open(TRAIN_DIR / "crops" / crop_info["image_path"]) grid.paste(crop_img, (x_pos, y_pos)) # Draw bounding box on grid box = crop_info["box"] x1 = x_pos + box["x1_in_crop"] y1 = y_pos + box["y1_in_crop"] x2 = x_pos + box["x2_in_crop"] y2 = y_pos + box["y2_in_crop"] draw.rectangle([x1, y1, x2, y2], outline=(0, 255, 0), width=2) # Label label = f"{crop_info['image_id']:2d}. {crop_info['tag']}" draw.text((x_pos, y_pos + crop_h + 5), label, fill=(255, 255, 255), font=font) # Save as JPG out_path = TRAIN_DIR / "training_crops_grid.jpg" grid.save(out_path, quality=85) print(f"Training data grid saved: {out_path}") print(f"Grid size: {grid.width}x{grid.height}") print(f"Crops: {len(crops)} units") print(f"Green boxes = bounding boxes")