| """Generate stroke_gesture_count samples. |
| |
| Each sample produces a SINGLE side-by-side image: Template on the left, |
| Field on the right, separated by a thin divider. |
| |
| The Template panel shows a single white brush stroke with a specific |
| curvature profile, and the Field (900x900 dark canvas) shows 25-35 |
| scattered brush strokes, some matching the template's shape exactly |
| (translated only) and the rest being distractors. |
| |
| The task: count how many strokes in the field match the template's shape. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import io |
| import json |
| import random |
| from pathlib import Path |
| from typing import List, Tuple, Optional |
|
|
| import matplotlib |
| matplotlib.use("Agg") |
| import matplotlib.pyplot as plt |
| import matplotlib.patches as mpatches |
| from matplotlib.patches import Rectangle |
| import numpy as np |
| from PIL import Image |
| from scipy.interpolate import splprep, splev |
| from scipy.spatial.distance import directed_hausdorff |
| from tqdm import tqdm |
|
|
|
|
| QUESTION = ( |
| "This image has two panels separated by a thin vertical divider. " |
| "The left panel shows the Template: a single white brush stroke with a " |
| "specific curvature profile. The right panel shows the Field: many white " |
| "brush strokes scattered across the canvas, all at the same thickness. " |
| "Both panels use the SAME pixel scale and stroke width. Count the number " |
| "of strokes in the Field that have the exact same shape as the Template " |
| "(translation only — same curvature, same orientation, no rotation or " |
| "mirroring) and report the integer count. " |
| "Provide your final answer enclosed in <answer>...</answer> tags." |
| ) |
|
|
| STROKE_WIDTH = 4.0 |
| BG_COLOR = "#0a1020" |
| HEADER_BG = "#11182a" |
| BORDER_COLOR = "#7aa6ff" |
| LABEL_COLOR = "#cfe0ff" |
| STROKE_COLOR = "white" |
| LABEL_TEXT_COLOR = "#ffd24a" |
| LABEL_FONT_SIZE = 13 |
|
|
|
|
| |
| |
| |
|
|
| def _random_control_points(rng: random.Random, n_pts: int = 5, |
| target_length: float = 120.0) -> np.ndarray: |
| """Generate n_pts control points that create an interesting curve. |
| |
| Returns control points centered around the origin. |
| The resulting curve will have arc length approximately target_length. |
| """ |
| |
| |
| scale = target_length / (n_pts - 1) |
| pts = [] |
| for i in range(n_pts): |
| x = i * scale * rng.uniform(0.6, 1.4) |
| y = rng.uniform(-scale * 1.2, scale * 1.2) |
| pts.append([x, y]) |
| pts = np.array(pts, dtype=np.float64) |
| |
| centroid = pts.mean(axis=0) |
| pts -= centroid |
| return pts |
|
|
|
|
| def _sample_bspline(control_points: np.ndarray, |
| n_samples: int = 300) -> np.ndarray: |
| """Dense-sample a B-spline through the given control points. |
| |
| Returns (n_samples, 2) array of points along the curve. |
| """ |
| k = min(3, len(control_points) - 1) |
| tck, u = splprep([control_points[:, 0], control_points[:, 1]], |
| s=0, k=k) |
| u_fine = np.linspace(0, 1, n_samples) |
| x, y = splev(u_fine, tck) |
| return np.column_stack([x, y]) |
|
|
|
|
| def _arc_length(curve: np.ndarray) -> float: |
| """Compute arc length of a polyline.""" |
| diffs = np.diff(curve, axis=0) |
| return float(np.sum(np.sqrt(np.sum(diffs**2, axis=1)))) |
|
|
|
|
| def _curve_bbox(curve: np.ndarray) -> Tuple[float, float, float, float]: |
| """Return (xmin, ymin, xmax, ymax) of a curve.""" |
| return (curve[:, 0].min(), curve[:, 1].min(), |
| curve[:, 0].max(), curve[:, 1].max()) |
|
|
|
|
| def _hausdorff_distance(c1: np.ndarray, c2: np.ndarray) -> float: |
| """Symmetric Hausdorff distance between two point sets.""" |
| d1 = directed_hausdorff(c1, c2)[0] |
| d2 = directed_hausdorff(c2, c1)[0] |
| return max(d1, d2) |
|
|
|
|
| def generate_template_stroke(rng: random.Random) -> Tuple[np.ndarray, np.ndarray]: |
| """Generate a template stroke. |
| |
| Returns (control_points, sampled_curve) where the curve is centered |
| around origin. |
| """ |
| for _ in range(100): |
| n_pts = rng.randint(4, 5) |
| lo = max(40.0, 120.0 - TEMPLATE_LENGTH_STD) |
| hi = 120.0 + TEMPLATE_LENGTH_STD |
| target_len = rng.uniform(lo, hi) |
| cp = _random_control_points(rng, n_pts, target_len) |
| curve = _sample_bspline(cp, 300) |
|
|
| length = _arc_length(curve) |
| if length < max(40.0, lo - 10.0) or length > hi + 30.0: |
| continue |
|
|
| |
| bbox = _curve_bbox(curve) |
| w = bbox[2] - bbox[0] |
| h = bbox[3] - bbox[1] |
| if w < 20 or h < 15: |
| continue |
| if w > 250 or h > 250: |
| continue |
|
|
| |
| centroid = curve.mean(axis=0) |
| curve -= centroid |
| cp -= centroid |
| return cp, curve |
|
|
| raise RuntimeError("Could not generate template stroke") |
|
|
|
|
| DISTRACTOR_HAUSDORFF_MIN = 15.0 |
| TEMPLATE_LENGTH_STD = 35.0 |
|
|
|
|
| def generate_distractor_stroke(rng: random.Random, |
| template_curve: np.ndarray, |
| min_hausdorff: float = 15.0, |
| max_hausdorff: float | None = None) -> Tuple[np.ndarray, np.ndarray]: |
| """Generate a distractor stroke that is similar in size but different shape. |
| |
| Returns (control_points, sampled_curve) centered around origin. |
| """ |
| template_length = _arc_length(template_curve) |
|
|
| for _ in range(200): |
| n_pts = rng.randint(4, 5) |
| |
| target_len = template_length * rng.uniform(0.8, 1.2) |
| cp = _random_control_points(rng, n_pts, target_len) |
| curve = _sample_bspline(cp, 300) |
|
|
| length = _arc_length(curve) |
| if length < 60 or length > 200: |
| continue |
|
|
| bbox = _curve_bbox(curve) |
| w = bbox[2] - bbox[0] |
| h = bbox[3] - bbox[1] |
| if w < 15 or h < 10: |
| continue |
| if w > 280 or h > 280: |
| continue |
|
|
| |
| centroid = curve.mean(axis=0) |
| curve -= centroid |
| cp -= centroid |
|
|
| |
| hd = _hausdorff_distance(curve, template_curve) |
| if hd < min_hausdorff: |
| continue |
| if max_hausdorff is not None and hd > max_hausdorff: |
| continue |
|
|
| return cp, curve |
|
|
| raise RuntimeError("Could not generate distractor stroke") |
|
|
|
|
| |
| |
| |
|
|
| def _curves_overlap(centers: List[np.ndarray], curves: List[np.ndarray], |
| new_center: np.ndarray, new_curve: np.ndarray, |
| min_dist: float) -> bool: |
| """Check if a new stroke (at new_center) overlaps any existing strokes. |
| |
| Uses bounding-box pre-filter then checks minimum point-to-point distance |
| between the actual curve samples for any pair whose bboxes are close. |
| """ |
| min_pixel_gap = 14.0 |
| new_shifted = new_curve + new_center |
| new_bbox = _curve_bbox(new_shifted) |
|
|
| for i, (c, crv) in enumerate(zip(centers, curves)): |
| existing_shifted = crv + c |
| existing_bbox = _curve_bbox(existing_shifted) |
|
|
| |
| margin = min_pixel_gap + 5.0 |
| if (new_bbox[2] + margin < existing_bbox[0] or |
| new_bbox[0] - margin > existing_bbox[2] or |
| new_bbox[3] + margin < existing_bbox[1] or |
| new_bbox[1] - margin > existing_bbox[3]): |
| continue |
|
|
| |
| |
| ns = new_shifted[::10] |
| es = existing_shifted[::10] |
| |
| diffs = ns[:, None, :] - es[None, :, :] |
| dists_sq = np.sum(diffs**2, axis=-1) |
| min_d = float(np.sqrt(dists_sq.min())) |
| if min_d < min_pixel_gap: |
| return True |
| return False |
|
|
|
|
| def build_sample(rng: random.Random, width: int, height: int, |
| target_matches: int, total_strokes: int |
| ) -> Tuple[np.ndarray, np.ndarray, List[np.ndarray], List[np.ndarray], int]: |
| """Build a sample. |
| |
| Returns: |
| template_cp: control points for template |
| template_curve: sampled template curve (centered at origin) |
| centers: list of (x, y) center positions for each placed stroke |
| curves: list of sampled curves (each centered at origin) for each stroke |
| realised_matches: verified match count |
| """ |
| for attempt in range(40): |
| try: |
| template_cp, template_curve = generate_template_stroke(rng) |
| except RuntimeError: |
| continue |
|
|
| t_bbox = _curve_bbox(template_curve) |
| max_stroke_extent = max(abs(t_bbox[0]), abs(t_bbox[1]), |
| abs(t_bbox[2]), abs(t_bbox[3])) |
| pad = max_stroke_extent + 30.0 |
| min_center_dist = max_stroke_extent * 1.8 + 10.0 |
|
|
| centers: List[np.ndarray] = [] |
| curves: List[np.ndarray] = [] |
| is_match: List[bool] = [] |
|
|
| |
| placed_matches = 0 |
| for _ in range(target_matches): |
| placed = False |
| for _try in range(500): |
| cx = rng.uniform(pad, width - pad) |
| cy = rng.uniform(pad, height - pad) |
| center = np.array([cx, cy]) |
|
|
| if _curves_overlap(centers, curves, center, template_curve, |
| min_center_dist): |
| continue |
|
|
| |
| shifted = template_curve + center |
| if (shifted[:, 0].min() < 5 or shifted[:, 0].max() > width - 5 or |
| shifted[:, 1].min() < 5 or shifted[:, 1].max() > height - 5): |
| continue |
|
|
| centers.append(center) |
| curves.append(template_curve.copy()) |
| is_match.append(True) |
| placed_matches += 1 |
| placed = True |
| break |
| if not placed: |
| break |
|
|
| if placed_matches != target_matches: |
| continue |
|
|
| |
| distractors_needed = total_strokes - placed_matches |
| fail = False |
| for _ in range(distractors_needed): |
| placed = False |
| for _try in range(300): |
| try: |
| d_cp, d_curve = generate_distractor_stroke( |
| random.Random(rng.randint(0, 2**31 - 1)), |
| template_curve, |
| min_hausdorff=DISTRACTOR_HAUSDORFF_MIN) |
| except RuntimeError: |
| continue |
|
|
| d_bbox = _curve_bbox(d_curve) |
| d_extent = max(abs(d_bbox[0]), abs(d_bbox[1]), |
| abs(d_bbox[2]), abs(d_bbox[3])) |
| d_pad = d_extent + 20.0 |
|
|
| cx = rng.uniform(d_pad, width - d_pad) |
| cy = rng.uniform(d_pad, height - d_pad) |
| center = np.array([cx, cy]) |
|
|
| if _curves_overlap(centers, curves, center, d_curve, |
| min_center_dist * 0.7): |
| continue |
|
|
| shifted = d_curve + center |
| if (shifted[:, 0].min() < 5 or shifted[:, 0].max() > width - 5 or |
| shifted[:, 1].min() < 5 or shifted[:, 1].max() > height - 5): |
| continue |
|
|
| centers.append(center) |
| curves.append(d_curve) |
| is_match.append(False) |
| placed = True |
| break |
| if not placed: |
| fail = True |
| break |
|
|
| if fail: |
| continue |
|
|
| |
| verified_matches = 0 |
| for i, crv in enumerate(curves): |
| hd = _hausdorff_distance(crv, template_curve) |
| if hd < 2.0: |
| verified_matches += 1 |
|
|
| if verified_matches == target_matches: |
| return template_cp, template_curve, centers, curves, verified_matches |
|
|
| raise RuntimeError("Failed to build sample after many attempts") |
|
|
|
|
| |
| |
| |
|
|
| def _render_curve_on_ax(ax, curve: np.ndarray, center: np.ndarray, |
| color: str = "white", linewidth: float = STROKE_WIDTH): |
| """Render a single stroke on a matplotlib axes.""" |
| shifted = curve + center |
| ax.plot(shifted[:, 0], shifted[:, 1], |
| color=color, linewidth=linewidth, |
| solid_capstyle="round", solid_joinstyle="round", |
| antialiased=True, zorder=3) |
|
|
|
|
| def _label_index_to_text(idx: int) -> str: |
| """Map 0->A, 1->B, ..., 25->Z, 26->AA, 27->AB, ...""" |
| s = "" |
| n = idx |
| while True: |
| s = chr(ord("A") + (n % 26)) + s |
| n = n // 26 - 1 |
| if n < 0: |
| break |
| return s |
|
|
|
|
| def _compute_label_positions(width: int, height: int, |
| centers: List[np.ndarray], |
| curves: List[np.ndarray] |
| ) -> List[Tuple[float, float]]: |
| """For each stroke, generate many candidate label positions and pick |
| the one that (a) hugs its own stroke, (b) maximally clears every other |
| stroke, and (c) doesn't collide with previously-placed labels. |
| |
| Strategy: for ~12 anchor points sampled along each stroke, try both |
| perpendicular normals at offsets {12, 18, 24, 30}; plus the two |
| endpoint-tangent extensions. Filter by hard clearance gates, then |
| score by other-stroke clearance and label-label clearance. |
| """ |
| own_max = 22.0 |
| other_clearance = 16.0 |
| label_clearance = 22.0 |
| label_half_w = 9.0 |
| label_half_h = 9.0 |
| offsets = [12.0, 18.0, 24.0, 30.0] |
| n_anchors = 12 |
|
|
| shifted_all = [crv + ctr for crv, ctr in zip(curves, centers)] |
|
|
| positions: List[Tuple[float, float]] = [] |
| placed_label_pts: List[np.ndarray] = [] |
|
|
| for i, sh in enumerate(shifted_all): |
| L = len(sh) |
| if L < 4: |
| positions.append((float(sh[0, 0]), float(sh[0, 1]))) |
| placed_label_pts.append(np.array(positions[-1])) |
| continue |
|
|
| |
| |
| anchor_idxs = sorted(set( |
| [0, L - 1] + |
| [int(round(t * (L - 1))) |
| for t in np.linspace(0.0, 1.0, n_anchors)] |
| )) |
|
|
| candidates: List[Tuple[float, float, float]] = [] |
| for idx in anchor_idxs: |
| anchor = sh[idx] |
| |
| if idx == 0: |
| tan = sh[min(L - 1, 5)] - sh[0] |
| elif idx == L - 1: |
| tan = sh[L - 1] - sh[max(0, L - 6)] |
| else: |
| lo = max(0, idx - 3) |
| hi = min(L - 1, idx + 3) |
| tan = sh[hi] - sh[lo] |
| n = float(np.linalg.norm(tan)) |
| if n < 1e-6: |
| continue |
| t_unit = tan / n |
| normal_l = np.array([-t_unit[1], t_unit[0]]) |
| normal_r = -normal_l |
| directions = [normal_l, normal_r] |
| |
| if idx == 0: |
| directions.append(-t_unit) |
| if idx == L - 1: |
| directions.append(t_unit) |
|
|
| for direction in directions: |
| for offset in offsets: |
| pos = anchor + direction * offset |
| px, py = float(pos[0]), float(pos[1]) |
| if (px - label_half_w < 4 or px + label_half_w > width - 4 or |
| py - label_half_h < 4 or py + label_half_h > height - 4): |
| continue |
|
|
| |
| own_d = float("inf") |
| other_d = float("inf") |
| for j, sh_j in enumerate(shifted_all): |
| diffs = sh_j - np.array([px, py]) |
| d = float(np.sqrt((diffs * diffs).sum(axis=1)).min()) |
| if j == i: |
| if d < own_d: |
| own_d = d |
| else: |
| if d < other_d: |
| other_d = d |
|
|
| |
| if own_d > own_max: |
| continue |
| if other_d < other_clearance: |
| continue |
|
|
| |
| label_d = float("inf") |
| for lp in placed_label_pts: |
| d = float(np.hypot(px - lp[0], py - lp[1])) |
| if d < label_d: |
| label_d = d |
| if label_d < label_clearance: |
| continue |
|
|
| |
| score = other_d + 0.5 * label_d - 0.4 * offset |
| candidates.append((score, px, py)) |
|
|
| if candidates: |
| candidates.sort(reverse=True) |
| _, px, py = candidates[0] |
| best_pos = (px, py) |
| else: |
| |
| best_pos = None |
| for relax in (0.7, 0.5, 0.3): |
| clr = other_clearance * relax |
| for idx in anchor_idxs: |
| anchor = sh[idx] |
| for direction_sign in (1, -1): |
| if idx == 0: |
| tan = sh[min(L - 1, 5)] - sh[0] |
| elif idx == L - 1: |
| tan = sh[L - 1] - sh[max(0, L - 6)] |
| else: |
| tan = sh[min(L - 1, idx + 3)] - sh[max(0, idx - 3)] |
| n = float(np.linalg.norm(tan)) or 1.0 |
| t_unit = tan / n |
| normal = np.array([-t_unit[1] * direction_sign, |
| t_unit[0] * direction_sign]) |
| for offset in offsets: |
| pos = anchor + normal * offset |
| px, py = float(pos[0]), float(pos[1]) |
| if (px - label_half_w < 4 or px + label_half_w > width - 4 or |
| py - label_half_h < 4 or py + label_half_h > height - 4): |
| continue |
| other_d = min( |
| float(np.sqrt(((sh_j - np.array([px, py])) ** 2).sum(axis=1)).min()) |
| for j, sh_j in enumerate(shifted_all) if j != i |
| ) |
| if other_d >= clr: |
| best_pos = (px, py) |
| break |
| if best_pos: |
| break |
| if best_pos: |
| break |
| if best_pos: |
| break |
| if best_pos is None: |
| ep = sh[-1] |
| best_pos = (float(np.clip(ep[0] + 16, 4 + label_half_w, width - 4 - label_half_w)), |
| float(np.clip(ep[1], 4 + label_half_h, height - 4 - label_half_h))) |
|
|
| positions.append(best_pos) |
| placed_label_pts.append(np.array(best_pos)) |
|
|
| return positions |
|
|
|
|
| def render_field(width: int, height: int, |
| centers: List[np.ndarray], curves: List[np.ndarray], |
| labels: Optional[List[str]] = None, |
| label_positions: Optional[List[Tuple[float, float]]] = None) -> Image.Image: |
| """Render the field image. Returns PIL Image.""" |
| fig = plt.figure(figsize=(width / 100, height / 100), dpi=100, |
| facecolor=BG_COLOR) |
| ax = fig.add_axes([0, 0, 1, 1]) |
| ax.set_xlim(0, width) |
| ax.set_ylim(height, 0) |
| ax.axis("off") |
| ax.set_facecolor(BG_COLOR) |
|
|
| for center, curve in zip(centers, curves): |
| _render_curve_on_ax(ax, curve, center) |
|
|
| |
|
|
| buf = io.BytesIO() |
| fig.savefig(buf, format="png", dpi=100, bbox_inches="tight", pad_inches=0, |
| facecolor=fig.get_facecolor()) |
| plt.close(fig) |
| buf.seek(0) |
| return Image.open(buf).convert("RGB") |
|
|
|
|
| def render_template(template_curve: np.ndarray) -> Image.Image: |
| """Render the template panel at the SAME pixel scale as the field. Returns PIL Image.""" |
| t_bbox = _curve_bbox(template_curve) |
| span_x = t_bbox[2] - t_bbox[0] |
| span_y = t_bbox[3] - t_bbox[1] |
|
|
| margin = 40.0 |
| header_h = 34.0 |
| min_width = 200.0 |
|
|
| content_w = span_x + 2 * margin |
| content_h = span_y + 2 * margin |
| canvas_w = max(content_w, min_width) |
| canvas_h = header_h + content_h |
|
|
| |
| margin_x = (canvas_w - span_x) / 2.0 |
| ox = margin_x - t_bbox[0] |
| oy = (header_h + margin) - t_bbox[1] |
| center = np.array([ox, oy]) |
|
|
| fig = plt.figure(figsize=(canvas_w / 100, canvas_h / 100), dpi=100, |
| facecolor="#070b14") |
| ax = fig.add_axes([0, 0, 1, 1]) |
| ax.set_xlim(0, canvas_w) |
| ax.set_ylim(canvas_h, 0) |
| ax.axis("off") |
| ax.set_facecolor("#070b14") |
|
|
| |
| ax.add_patch(Rectangle((0, 0), canvas_w, header_h, |
| facecolor=HEADER_BG, edgecolor="none", zorder=4)) |
| ax.plot([0, canvas_w], [header_h, header_h], |
| color="#2d3a5a", linewidth=1.0, zorder=5) |
| ax.text(canvas_w / 2, header_h / 2, "TEMPLATE", |
| color=LABEL_COLOR, fontsize=14, fontweight="bold", |
| ha="center", va="center", zorder=6, |
| family="DejaVu Sans") |
|
|
| |
| ax.add_patch(Rectangle((1.5, 1.5), canvas_w - 3, canvas_h - 3, |
| facecolor="none", edgecolor=BORDER_COLOR, |
| linewidth=2.0, zorder=6)) |
|
|
| |
| _render_curve_on_ax(ax, template_curve, center, linewidth=STROKE_WIDTH) |
|
|
| buf = io.BytesIO() |
| fig.savefig(buf, format="png", dpi=100, bbox_inches=None, pad_inches=0, |
| facecolor=fig.get_facecolor()) |
| plt.close(fig) |
| buf.seek(0) |
| return Image.open(buf).convert("RGB") |
|
|
|
|
| DIVIDER_WIDTH = 3 |
| DIVIDER_COLOR = (51, 51, 85) |
|
|
|
|
| def render_combined(out_path: Path, template_img: Image.Image, |
| field_img: Image.Image) -> None: |
| """Concatenate template (left) and field (right) with a thin divider, |
| then pad to a square canvas (BG colour) so downstream image-edit |
| models receive a 1:1 input.""" |
| bg = tuple(int(BG_COLOR.lstrip("#")[i:i+2], 16) for i in (0, 2, 4)) |
| tw, th = template_img.size |
| fw, fh = field_img.size |
| inner_h = max(th, fh) |
| inner_w = tw + DIVIDER_WIDTH + fw |
| side = max(inner_w, inner_h) |
| combined = Image.new("RGB", (side, side), bg) |
| x0 = (side - inner_w) // 2 |
| y0 = (side - inner_h) // 2 |
| combined.paste(template_img, (x0, y0 + (inner_h - th) // 2)) |
| for x in range(x0 + tw, x0 + tw + DIVIDER_WIDTH): |
| for y in range(y0, y0 + inner_h): |
| combined.putpixel((x, y), DIVIDER_COLOR) |
| combined.paste(field_img, (x0 + tw + DIVIDER_WIDTH, y0 + (inner_h - fh) // 2)) |
| combined.save(out_path) |
|
|
|
|
| |
| |
| |
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser( |
| description="Generate stroke_gesture_count samples") |
| parser.add_argument("--output-root", type=Path, required=True) |
| parser.add_argument("--count", type=int, default=30) |
| parser.add_argument("--seed", type=int, default=0) |
| parser.add_argument("--width", type=int, default=900) |
| parser.add_argument("--height", type=int, default=900) |
| parser.add_argument("--difficulty", type=int, default=5, |
| help="Integer difficulty >=0; scales matches, total strokes, and distractor similarity.") |
| args = parser.parse_args() |
|
|
| import math |
| d = max(0, int(args.difficulty)) |
| _min_matches = 5 |
| _max_matches = 5 + 2 * d |
| _total_strokes_lo = 25 + 3 * d |
| global DISTRACTOR_HAUSDORFF_MIN, TEMPLATE_LENGTH_STD |
| DISTRACTOR_HAUSDORFF_MIN = max(8.0, 18.0 - 1.0 * d) |
| TEMPLATE_LENGTH_STD = 30.0 + 5.0 * d |
|
|
| |
| |
| n_d = 25 + 3 * d |
| n_0 = 25 |
| s = math.sqrt(max(1.0, n_d / n_0)) |
| args.width = int(round(args.width * s)) |
| args.height = int(round(args.height * s)) |
|
|
| out_root: Path = args.output_root |
| img_dir = out_root / "images" |
| img_dir.mkdir(parents=True, exist_ok=True) |
|
|
| ann_path = out_root / "annotations.jsonl" |
| master_rng = random.Random(args.seed) |
|
|
| |
| if args.count > 1: |
| plan = [int(round(_min_matches + i * (_max_matches - _min_matches) / (args.count - 1))) for i in range(args.count)] |
| else: |
| plan = [_min_matches] |
| print(f"forced stroke_gesture match counts: {plan}") |
|
|
| records = [] |
| with ann_path.open("w") as f: |
| for i in tqdm(range(args.count), desc="stroke_gesture_count"): |
| target = plan[i] |
| total_strokes = master_rng.randint(_total_strokes_lo, |
| _total_strokes_lo + 10) |
| total_strokes = max(total_strokes, target + 20) |
|
|
| built = False |
| for retry in range(20): |
| sub_seed = master_rng.randint(0, 2**31 - 1) |
| sub_rng = random.Random(sub_seed) |
| try: |
| template_cp, template_curve, centers, curves, realised = \ |
| build_sample(sub_rng, args.width, args.height, |
| target_matches=target, |
| total_strokes=total_strokes) |
| except RuntimeError: |
| continue |
| built = True |
| break |
| if not built: |
| raise RuntimeError(f"sample {i} could not be generated") |
|
|
| |
| order = list(range(len(centers))) |
| master_rng.shuffle(order) |
| centers = [centers[k] for k in order] |
| curves = [curves[k] for k in order] |
|
|
| |
| is_match = [] |
| for crv in curves: |
| hd = _hausdorff_distance(crv, template_curve) |
| is_match.append(hd < 2.0) |
|
|
| labels = [_label_index_to_text(k) for k in range(len(centers))] |
| label_positions = _compute_label_positions( |
| args.width, args.height, centers, curves) |
|
|
| matching_labels = sorted( |
| [labels[k] for k, m in enumerate(is_match) if m], |
| key=lambda s: (len(s), s)) |
| answer_str = str(realised) |
|
|
| img_name = f"stroke_gesture_count_{i:05d}.png" |
| tpl_img = render_template(template_curve) |
| fld_img = render_field(args.width, args.height, centers, curves, |
| labels=None, label_positions=None) |
| render_combined(img_dir / img_name, tpl_img, fld_img) |
|
|
| rec = { |
| "image": f"images/{img_name}", |
| "question": QUESTION, |
| "answer": answer_str, |
| "num_matches": realised, |
| "matching_labels": matching_labels, |
| "total_strokes": len(centers), |
| "metadata": { |
| "seed": sub_seed, |
| "template_control_points": template_cp.tolist(), |
| "template_arc_length": float(_arc_length(template_curve)), |
| }, |
| } |
| f.write(json.dumps(rec) + "\n") |
| f.flush() |
| records.append(rec) |
|
|
| data_json = { |
| "task": "stroke_gesture_count", |
| "category": "visual_attribute_transfer", |
| "count": len(records), |
| "items": records, |
| } |
| (out_root / "data.json").write_text(json.dumps(data_json, indent=2)) |
|
|
| |
| from collections import Counter |
| answers = [r["answer"] for r in records] |
| dist = Counter(answers) |
| print(f"\nSaved {len(records)} samples to {out_root}") |
| print(f"Images: {len(records)} (single combined per sample)") |
| print(f"Answer distribution: {dict(sorted(dist.items()))}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|