File size: 19,581 Bytes
f69e256 | 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 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 | """Generate 'Spot the Contour Diff' visual benchmark dataset.
Two panels are shown side by side. Each panel contains the same set of closed
contours (Fourier-descriptor blobs) at the same positions, with each contour
pair tagged by an uppercase letter label that appears at the same position in
both panels. Some contours in the right panel have a different shape from the
corresponding contour in the left panel. The task is to list the letter labels
of contour pairs whose shape differs between the two panels.
Blob generation is reused from the sibling ``contour_silhouette_count`` task.
"""
from __future__ import annotations
import argparse
import json
import math
import random
import sys
from pathlib import Path
from typing import Any, Dict, List, Tuple
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
from tqdm import tqdm
# Reuse blob generation and stroke helpers from contour_silhouette_count.
_SIBLING = Path(__file__).resolve().parent.parent / "contour_silhouette_count"
sys.path.insert(0, str(_SIBLING))
from creation import ( # type: ignore # noqa: E402
STROKE_WIDTH,
_draw_blob_outline,
blob_bounding_radius,
blob_hausdorff,
fourier_blob,
)
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
NUM_ITEMS = 15
MIN_DIFFS = 4
MAX_DIFFS = 7
PANEL_W = 900
PANEL_H = 900
PADDING = 18 # visible gap between blob outlines
EDGE_PADDING = 18 # gap between blob bounding circle and panel edge
HAUSDORFF_THRESH = 5.0 # changed blob must differ from original by at least this
HAUSDORFF_MAX = 20.0 # …but not by more than this (keep diffs subtle)
BG_COLOR = "#0a1020"
BORDER_COLOR = "#7aa6ff"
BORDER_WIDTH = 2.0
HIGHLIGHT_COLOR = "#dc1e1e"
LABEL_BADGE_COLOR = "#f5d76e"
LABEL_TEXT_COLOR = "#1a1a1a"
LABEL_BADGE_PAD = 8.0 # gap between bounding circle and badge centre offset
MARGIN_PX = 60
GAP_PX = 100
LABEL_HEIGHT = 44
QUESTION = (
"Two panels are shown side by side. Each panel contains the same set of "
"closed contours at the same positions. Some contours in the right "
"panel have a different shape from the corresponding contour in the "
"left panel. Count the number of contour pairs whose shape differs "
"between the two panels and report the integer count. "
"Provide your final answer enclosed in <answer>...</answer> tags."
)
def _index_to_label(i: int) -> str:
"""Map 0->A, 1->B, ..., 25->Z, 26->AA, 27->AB, ..."""
letters = []
n = i
while True:
letters.append(chr(ord("A") + (n % 26)))
n = n // 26 - 1
if n < 0:
break
return "".join(reversed(letters))
# ---------------------------------------------------------------------------
# Blob generation / swapping
# ---------------------------------------------------------------------------
def _generate_blob(rng: random.Random) -> np.ndarray:
r0 = rng.uniform(38.0, 52.0)
return fourier_blob(rng, r0=r0, K_range=(4, 6), amp_scale=0.22)
def _polygon_area(poly: np.ndarray) -> float:
x = poly[:, 0]
y = poly[:, 1]
return 0.5 * abs(float(np.dot(x, np.roll(y, -1)) - np.dot(y, np.roll(x, -1))))
# Minimum fractional difference in enclosed area between the original and the
# swapped contour. Together with HAUSDORFF_THRESH this guarantees that the
# swap differs both in OUTLINE shape and in ENCLOSED REGION.
MIN_AREA_RATIO_DIFF = 0.18
def _sample_different_blob(
rng: random.Random,
old: np.ndarray,
old_radius: float,
max_tries: int = 800,
) -> np.ndarray:
"""Sample a new blob with Hausdorff distance >= HAUSDORFF_THRESH from
``old``, area differing by at least MIN_AREA_RATIO_DIFF, and bounding
radius no larger than ``old_radius``."""
old_area = _polygon_area(old)
for _ in range(max_tries):
cand = _generate_blob(rng)
if blob_bounding_radius(cand) > old_radius:
continue
d = blob_hausdorff(cand, old)
if not (HAUSDORFF_THRESH <= d <= HAUSDORFF_MAX):
continue
cand_area = _polygon_area(cand)
if old_area > 0 and abs(cand_area - old_area) / old_area < MIN_AREA_RATIO_DIFF:
continue
return cand
raise RuntimeError("Could not sample a sufficiently different blob.")
# ---------------------------------------------------------------------------
# Layout
# ---------------------------------------------------------------------------
def _place_items(
rng: random.Random,
radii: List[float],
max_tries_per_item: int = 5000,
) -> List[Tuple[float, float]]:
order = sorted(range(len(radii)), key=lambda i: -radii[i])
centers: List[Tuple[float, float] | None] = [None] * len(radii)
for i in order:
r = radii[i]
placed = False
for _ in range(max_tries_per_item):
x = rng.uniform(r + EDGE_PADDING, PANEL_W - r - EDGE_PADDING)
y = rng.uniform(r + EDGE_PADDING, PANEL_H - r - EDGE_PADDING)
ok = True
for j, c in enumerate(centers):
if c is None or j == i:
continue
min_dist = radii[i] + radii[j] + PADDING
dx = x - c[0]
dy = y - c[1]
if dx * dx + dy * dy < min_dist * min_dist:
ok = False
break
if ok:
centers[i] = (x, y)
placed = True
break
if not placed:
raise RuntimeError(f"Could not place blob {i} (r={r:.1f}) without overlap.")
return [c for c in centers] # type: ignore[return-value]
# ---------------------------------------------------------------------------
# Sample construction
# ---------------------------------------------------------------------------
def build_sample(
rng: random.Random,
num_items: int,
num_diffs: int,
) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
left_blobs = [_generate_blob(rng) for _ in range(num_items)]
radii = [blob_bounding_radius(b) for b in left_blobs]
right_blobs: List[np.ndarray] = [b.copy() for b in left_blobs]
changed_idx = rng.sample(range(num_items), num_diffs)
for i in changed_idx:
right_blobs[i] = _sample_different_blob(rng, left_blobs[i], radii[i])
centers = _place_items(rng, radii)
changed_set = set(changed_idx)
items: List[Dict[str, Any]] = []
for i in range(num_items):
x, y = centers[i]
items.append({
"index": i,
"label": _index_to_label(i),
"x": x,
"y": y,
"bounding_radius": radii[i],
"left_pts": left_blobs[i],
"right_pts": right_blobs[i],
"changed": i in changed_set,
})
diffs: List[Dict[str, Any]] = [
{
"index": i,
"label": items[i]["label"],
"x": items[i]["x"],
"y": items[i]["y"],
"bounding_radius": items[i]["bounding_radius"],
}
for i in sorted(changed_idx)
]
return items, diffs
# ---------------------------------------------------------------------------
# Rendering
# ---------------------------------------------------------------------------
def _panel_origins() -> Tuple[Tuple[float, float], Tuple[float, float]]:
oy = MARGIN_PX + LABEL_HEIGHT
ox_left = MARGIN_PX
ox_right = MARGIN_PX + PANEL_W + GAP_PX
return (ox_left, oy), (ox_right, oy)
def _canvas_size() -> Tuple[int, int]:
w = MARGIN_PX + PANEL_W + GAP_PX + PANEL_W + MARGIN_PX
h = MARGIN_PX + LABEL_HEIGHT + PANEL_H + MARGIN_PX
return w, h
def _badge_offset(
x: float,
y: float,
radius: float,
badge_r: float,
) -> Tuple[float, float]:
"""Legacy compass-based fallback (unused — kept for backward compatibility)."""
margin = radius + badge_r + LABEL_BADGE_PAD
candidates = [
(1.0, -1.0), (1.0, 1.0), (-1.0, -1.0), (-1.0, 1.0),
(1.0, 0.0), (0.0, -1.0), (-1.0, 0.0), (0.0, 1.0),
]
inset = badge_r + 2.0
for sx, sy in candidates:
norm = math.hypot(sx, sy) or 1.0
dx = sx / norm * margin
dy = sy / norm * margin
bx = x + dx
by = y + dy
if (inset <= bx <= PANEL_W - inset
and inset <= by <= PANEL_H - inset):
return dx, dy
return margin / math.sqrt(2), -margin / math.sqrt(2)
def _plan_label_positions(
items: List[Dict[str, Any]],
other_clearance: float = 14.0,
label_clearance: float = 24.0,
n_angles: int = 16,
radial_steps: Tuple[float, ...] = (0.0, 6.0, 14.0, 24.0),
) -> List[Tuple[float, float]]:
"""Choose label-badge centres (in LEFT-panel local coords) using a
multi-candidate, best-score search.
Returns one (px, py) per item. Identical coordinates are reused for the
right panel (just translated by that panel's origin) since both panels
have the same width/height and contour positions.
"""
n = len(items)
# Pre-compute badge radii and translated point sets (panel-local).
badge_rs: List[float] = []
other_pts_list: List[np.ndarray] = []
for it in items:
label = it["label"]
badge_rs.append(22.0 + 6.0 * (len(label) - 1))
# Translate the LEFT contour's points into panel-local coords.
other_pts_list.append(it["left_pts"] + np.array([it["x"], it["y"]]))
placements: List[Tuple[float, float]] = []
placed_centres: List[Tuple[float, float]] = []
for i, it in enumerate(items):
x, y = it["x"], it["y"]
radius = it["bounding_radius"]
badge_r = badge_rs[i]
inset = badge_r + 2.0
base_margin = radius + badge_r + LABEL_BADGE_PAD
# Other contours' points (everything except self).
if n > 1:
other_pts = np.concatenate(
[other_pts_list[j] for j in range(n) if j != i], axis=0
)
else:
other_pts = np.zeros((0, 2))
def evaluate(oc: float, lc: float):
best = None
best_score = -1e18
for a_idx in range(n_angles):
ang = 2.0 * math.pi * a_idx / n_angles
cos_a = math.cos(ang)
sin_a = math.sin(ang)
for off in radial_steps:
margin = base_margin + off
px = x + cos_a * margin
py = y + sin_a * margin
# Panel-bounds gate.
if not (inset <= px <= PANEL_W - inset
and inset <= py <= PANEL_H - inset):
continue
# Other-contour clearance.
if other_pts.shape[0] > 0:
dx = other_pts[:, 0] - px
dy = other_pts[:, 1] - py
other_d = float(np.sqrt(np.min(dx * dx + dy * dy)))
else:
other_d = 1e6
if other_d < oc:
continue
# Label-clearance gate.
if placed_centres:
label_d = min(
math.hypot(px - lx, py - ly)
for lx, ly in placed_centres
)
else:
label_d = 1e6
if label_d < lc:
continue
score = other_d + 0.5 * label_d - 0.4 * off
if score > best_score:
best_score = score
best = (px, py)
return best
chosen = evaluate(other_clearance, label_clearance)
# Soft fallback: progressively relax other_clearance.
relax = other_clearance
while chosen is None and relax > 1.0:
relax *= 0.6
chosen = evaluate(relax, max(4.0, label_clearance * 0.6))
if chosen is None:
# Last-resort: legacy compass.
dx, dy = _badge_offset(x, y, radius, badge_r)
chosen = (x + dx, y + dy)
placements.append(chosen)
placed_centres.append(chosen)
return placements
def _draw_panel(
ax: plt.Axes,
items: List[Dict[str, Any]],
side: str,
ox: float,
oy: float,
label_positions: List[Tuple[float, float]],
) -> None:
key = "left_pts" if side == "left" else "right_pts"
for it in items:
translated = it[key] + np.array([ox + it["x"], oy + it["y"]])
_draw_blob_outline(ax, translated, STROKE_WIDTH, color="white", zorder=3)
# Letter-label badges removed: the task is now a count, not a label-list,
# so explicit per-contour anchors are no longer needed (and would let a
# model match in text space rather than visually).
def _render(
out_path: Path,
items: List[Dict[str, Any]],
diffs: List[Dict[str, Any]] | None = None,
) -> None:
w, h = _canvas_size()
dpi = 100
fig, ax = plt.subplots(1, 1, figsize=(w / dpi, h / dpi), dpi=dpi)
ax.set_xlim(0, w)
ax.set_ylim(h, 0)
ax.set_aspect("equal")
ax.axis("off")
fig.patch.set_facecolor(BG_COLOR)
ax.set_facecolor(BG_COLOR)
(ox_left, oy), (ox_right, _) = _panel_origins()
for ox in (ox_left, ox_right):
border = mpatches.Rectangle(
(ox, oy), PANEL_W, PANEL_H,
facecolor="none", edgecolor=BORDER_COLOR,
linewidth=BORDER_WIDTH, zorder=1,
)
ax.add_patch(border)
label_positions = _plan_label_positions(items)
_draw_panel(ax, items, "left", ox_left, oy, label_positions)
_draw_panel(ax, items, "right", ox_right, oy, label_positions)
ax.text(
ox_left + PANEL_W / 2, MARGIN_PX + LABEL_HEIGHT * 0.5,
"Left", ha="center", va="center",
fontsize=16, fontweight="bold", color="#cfe0ff",
)
ax.text(
ox_right + PANEL_W / 2, MARGIN_PX + LABEL_HEIGHT * 0.5,
"Right", ha="center", va="center",
fontsize=16, fontweight="bold", color="#cfe0ff",
)
if diffs:
for diff in diffs:
hl_r = diff["bounding_radius"] + 12
for ox in (ox_left, ox_right):
cx = ox + diff["x"]
cy = oy + diff["y"]
ring = mpatches.Circle(
(cx, cy), hl_r,
facecolor="none", edgecolor=HIGHLIGHT_COLOR,
linewidth=2.5, zorder=10,
)
ax.add_patch(ring)
fig.savefig(out_path, facecolor=BG_COLOR)
plt.close(fig)
def render_pair(out_path: Path, items: List[Dict[str, Any]]) -> None:
_render(out_path, items)
def render_answer(
out_path: Path,
items: List[Dict[str, Any]],
diffs: List[Dict[str, Any]],
) -> None:
_render(out_path, items, diffs)
# ---------------------------------------------------------------------------
# Annotation
# ---------------------------------------------------------------------------
def _answer_string(diffs: List[Dict[str, Any]]) -> str:
return str(len(diffs))
def build_annotation(
image_name: str,
items: List[Dict[str, Any]],
diffs: List[Dict[str, Any]],
) -> Dict[str, Any]:
return {
"image": image_name,
"num_items": len(items),
"num_differences": len(diffs),
"differences": [
{
"index": d["index"],
"label": d["label"],
"x": d["x"],
"y": d["y"],
"bounding_radius": d["bounding_radius"],
}
for d in diffs
],
"question": QUESTION,
"answer": _answer_string(diffs),
}
# ---------------------------------------------------------------------------
# Dataset generation
# ---------------------------------------------------------------------------
def generate_dataset(
rng: random.Random,
count: int,
output_dir: Path,
num_items: int = NUM_ITEMS,
min_diffs: int = MIN_DIFFS,
max_diffs: int = MAX_DIFFS,
) -> None:
images_dir = output_dir / "images"
answers_dir = output_dir / "answers"
images_dir.mkdir(parents=True, exist_ok=True)
answers_dir.mkdir(parents=True, exist_ok=True)
annotations: List[Dict[str, Any]] = []
data_items: List[Dict[str, Any]] = []
# Force evenly-spaced num_diffs across [min_diffs, max_diffs].
if count > 1:
forced = [int(round(min_diffs + i * (max_diffs - min_diffs) / (count - 1))) for i in range(count)]
else:
forced = [min_diffs]
print(f"forced contour diff counts: {forced}")
for idx in tqdm(range(count), desc="Generating contour diff pairs"):
num_diffs = forced[idx]
for attempt in range(200):
try:
items, diffs = build_sample(rng, num_items, num_diffs)
break
except RuntimeError:
continue
else:
raise RuntimeError(f"Failed to build sample {idx} after many retries")
image_name = f"contour_diff_{idx:05d}.png"
img_path = images_dir / image_name
ans_path = answers_dir / image_name
render_pair(img_path, items)
render_answer(ans_path, items, diffs)
rel_image = f"images/{image_name}"
annotations.append(build_annotation(rel_image, items, diffs))
data_items.append({
"image": rel_image,
"question": QUESTION,
"answer": _answer_string(diffs),
})
with (output_dir / "annotations.jsonl").open("w", encoding="utf-8") as fh:
for rec in annotations:
fh.write(json.dumps(rec) + "\n")
data_json = {
"task": "spot_the_contour_diff",
"category": "visual_attribute_transfer",
"count": len(data_items),
"items": data_items,
}
with (output_dir / "data.json").open("w", encoding="utf-8") as fh:
json.dump(data_json, fh, indent=2)
fh.write("\n")
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(
description="Generate 'Spot the Contour Diff' visual benchmark dataset."
)
p.add_argument("--output-root", type=Path, default=".")
p.add_argument("--count", type=int, default=20)
p.add_argument("--seed", type=int, default=42)
p.add_argument("--difficulty", type=int, default=5,
help="Integer difficulty >=0; scales diff count and subtlety.")
return p.parse_args()
def main() -> None:
args = parse_args()
rng = random.Random(args.seed)
d = max(0, int(args.difficulty))
N_d = 10 + 2 * d
N_0 = 10
s = math.sqrt(max(1.0, N_d / N_0))
global PANEL_W, PANEL_H
PANEL_W = int(round(PANEL_W * s))
PANEL_H = int(round(PANEL_H * s))
global HAUSDORFF_THRESH, HAUSDORFF_MAX
HAUSDORFF_THRESH = max(18.0, 22.0 - 0.4 * d)
HAUSDORFF_MAX = max(HAUSDORFF_THRESH + 12.0, 50.0 - 1.0 * d)
total_contours = 10 + 2 * d
min_diffs = 5
max_diffs = 5 + 2 * d
generate_dataset(rng, args.count, args.output_root,
num_items=total_contours,
min_diffs=min_diffs, max_diffs=max_diffs)
print(f"Saved {args.count} image pairs to {args.output_root}")
if __name__ == "__main__":
main()
|