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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
# Pixel-Based Maze Evaluation (Pure Vision)

Pure computer vision-based evaluation for maze-solving generation tasks. Compares generated maze solutions against ground-truth solution images using pixel-level analysis — no VLMs/LLMs involved.

| Script | Input | What it evaluates |
|--------|-------|-------------------|
| `image_gen_evaluation.py` | PNG images | Whether a generated maze-solution **image** is correct (blue path vs solution) |
| `video_gen_evaluation.py` | MP4 videos | Whether a generated maze-solution **video** is correct (green marker trajectory vs solution) |

The video script works by:
1. Extracting frames from the generated video (default: 192 frames @ 24fps)
2. Tracking the green marker position across all frames to form the generated path
3. Comparing the accumulated path with the reference solution image

## Installation

```bash
pip install opencv-python numpy pillow scipy scikit-image
```

## Usage

### Image Evaluation

```bash
# Evaluate a single image
python image_gen_evaluation.py --single "/path/to/generated_image.png"

# Evaluate an entire directory (default model: nano_banana_pro)
python image_gen_evaluation.py --model_name nano_banana_pro

# Custom directories
python image_gen_evaluation.py \
  --input_dir "/path/to/generated/images" \
  --solution_dir "/path/to/solution/images" \
  --output_dir "/path/to/output/results" \
  --model_name my_model
```

### Video Evaluation

```bash
# Evaluate a single video
python video_gen_evaluation.py --single "/path/to/generated_video.mp4"

# Evaluate an entire directory (default model: veo3)
python video_gen_evaluation.py --model_name veo3

# Custom directories
python video_gen_evaluation.py \
  --input_dir "/path/to/generated/videos" \
  --solution_dir "/path/to/solution/images" \
  --output_dir "/path/to/output/results" \
  --model_name my_model

# Specify number of frames to extract
python video_gen_evaluation.py --num_frames 192

# Loop through round directories
for dir in /path/to/video_results/veo3/dfs/easy_round*; do
    python video_gen_evaluation.py --input_dir "$dir" --model_name veo3
done
```

### Batch Evaluation (All Algorithms / Difficulties / Rounds)

To evaluate a model across all maze algorithms (`dfs`, `wilson`), difficulty levels (`easy`, `medium`, `hard`), and generation rounds, run from this directory:

```bash
BASE_DIR=/path/to/maze_solving_task   # contains image_results/, video_results/, data/solution/

# Images (e.g. gpt_image_1.5; also: nano_banana, nano_banana_pro, qwen_image)
for round in 1 2 3; do
    for algo in dfs wilson; do
        for difficulty in easy medium hard; do
            python image_gen_evaluation.py \
                --input_dir ${BASE_DIR}/image_results/gpt_image_1.5/${algo}/${difficulty}_round${round} \
                --solution_dir ${BASE_DIR}/data/solution \
                --model_name gpt_image_1.5
        done
    done
done

# Videos (e.g. wan2.2; also: veo3, sora2)
for round in 1 2 3 4 5; do
    for algo in dfs wilson; do
        for difficulty in easy medium hard; do
            python video_gen_evaluation.py \
                --input_dir ${BASE_DIR}/video_results/wan2.2/${algo}/${difficulty}_round${round} \
                --solution_dir ${BASE_DIR}/data/solution \
                --model_name wan2.2
        done
    done
done
```

Adjust the model name and round range to match what was generated.

### Default Paths

When flags are omitted, the scripts fall back to these defaults:

| Flag | Default | Relative to |
|------|---------|-------------|
| `--input_dir` | `./image_results/<model_name>` or `./video_results/<model_name>` | current working directory |
| `--solution_dir` | `./data/solution` | current working directory |
| `--output_dir` | `../evaluation_results/pixel_based_evaluation/<image\|video>_evaluation_results/<model_name>` | current working directory |

Unless you run the scripts from a directory that contains `image_results/`/`video_results/` and `data/solution/`, pass `--input_dir` and `--solution_dir` explicitly (as in the batch examples above).

**Note**: for sora2 models (`--model_name` containing `sora`), the video script automatically extracts 360 frames (12s @ 30fps) instead of the default 192, unless `--num_frames` is set to a non-default value.

## Video Path Extraction Methods

### 1. Green Marker Tracking (Default)

`--extraction_method green_marker_tracking`

- Tracks the position of the green marker in each frame
- Accumulates all green marker positions to form the generated path
- Works well when the video shows a moving green marker tracing the solution

### 2. Frame Differencing

`--extraction_method frame_differencing`

- Uses frame-to-frame differences to detect marker movement
- Detects new green pixels that appear between consecutive frames
- Alternative method for videos with different marker behaviors

## Evaluation Metrics

### 1. Wall Crossing Detection

**Purpose**: Detect if the generated path crosses black walls (invalid move)

**Method**:
- **Image**: Extract blue path and black wall pixels from the generated image; apply 3px erosion tolerance (handles anti-aliasing); flag as crossing only if ratio > 1%
- **Video**: Accumulate the path from all frames; check against the **solution's** wall structure (not video frame walls); apply significant erosion (1/4 cell size) to only detect interior crossing; use raw path (no dilation) to avoid false positives at edges; flag only if ratio > 5%

**Output**:
- `wall_crossing_detected`: Boolean
- `wall_crossing_pixels`: Number of crossing pixels
- `wall_crossing_ratio`: Fraction of path crossing walls

### 2. Layout Matching

**Purpose**: Verify maze structure and marker positions match the solution

**Method**:
- Compare black wall regions using IoU
- Compare green square (start) and red square (end) centroid positions
- **Image**: single image check, position tolerance 20 pixels
- **Video**: layout is checked for EACH frame (parallelized with ThreadPoolExecutor) and the **minimum** score across all frames is reported (worst-case detection); position tolerance 50 pixels (video resolution differences)

**Output**:
- `layout_match_score`: Combined score, 0-1 (video: minimum across frames)
- `maze_structure_iou`: Wall structure IoU (video: at worst frame)
- `green_position_match` / `red_position_match`: Boolean
- `green_centroid_distance` / `red_centroid_distance`: Distance in pixels

### 3. Path Matching (Dilate + IoU)

**Purpose**: Compare the generated path with solution blue cells

**Challenge**: The generated path is thin (a blue line in images, a marker trajectory in videos) while solutions have filled blue cells

**Method**:
- **Image**: dilate the thin generated blue line to match cell width
- **Video**: dilate the accumulated green marker path to match cell width
- Compute IoU with solution blue regions, plus precision and recall

**Output**:
- `path_match_iou`: Intersection over Union
- `path_precision`: Fraction of generated path that's correct
- `path_recall`: Fraction of solution path that's covered (pixel-level)
- `target_achievement`: Fraction of solution cells touched by generated path (cell-level, 0-1)
  - More lenient than recall: counts a cell as "achieved" if generated path touches it at all
  - Better reflects route correctness when generated path is thinner than solution cells

### 4. Reflection/Exploration Detection

**Purpose**: Detect if the model shows reasoning behavior (backtracking, exploration)

**Method**:
- Skeletonize the generated path and trace it
- Detect loops (cells visited multiple times)
- Compare path length vs solution path length
- Flag reflection if loops exist OR path is >1.3x longer

**Output**:
- `has_reflection`: Boolean
- `loop_count`: Number of detected loops
- `path_length_ratio`: Generated length / Solution length
- `exploration_score`: Combined exploration metric (0-1)

### 5. Gated Metrics (Video Only, Binary Pass/Fail)

**Purpose**: Provide strict pass/fail criteria for evaluation

**Criteria**:
| Metric | Condition |
|--------|-----------|
| `layout_match_score_gated` | 1 if `maze_structure_iou > 0.8`, else 0 |
| `target_achievement_gated` | 1 if `target_achievement > 0.95`, else 0 |
| `overall_score_gated` | 1 if ALL three conditions are met, else 0 |

**Overall Score Gated Requirements** (all must be true):
1. `layout_match_score_gated == 1` (maze structure IoU > 0.8)
2. `wall_crossing_detected == False` (no wall crossing)
3. `target_achievement_gated == 1` (target achievement > 0.95)

### Video-Specific Metrics

- `total_frames`: Total number of frames extracted from video
- `frames_with_marker`: Number of frames where green marker was detected
- `path_extraction_method`: Method used for path extraction

## Overall Score Calculation

```
overall_score = layout_score * 0.2 + path_iou * 0.5 - wall_penalty

where:
  wall_penalty = 0.3 if wall_crossing_detected else 0.0
```

## Output Files

By default, results are written to `../evaluation_results/pixel_based_evaluation/` (relative to this directory). Override with `--output_dir`.

### Image Evaluation Results

```
../evaluation_results/pixel_based_evaluation/image_evaluation_results/<model_name>/
├── evaluation_results_<timestamp>.json    # Final results
├── evaluation_results_latest.json         # Latest results (overwritten)
├── evaluation_results_incremental.json    # Progress during evaluation
└── visualizations/                        # Visualization images
    └── <image_name>_evaluation.png
```

### Video Evaluation Results

```
../evaluation_results/pixel_based_evaluation/video_evaluation_results/<model_name>/
├── evaluation_results_<round>_<timestamp>.json    # Final results (with round suffix)
├── evaluation_results_<round>_latest.json         # Latest results (overwritten)
├── evaluation_results_<round>_incremental.json    # Progress during evaluation
├── <video_name>_<round>_result.json               # Individual video result
└── visualizations/                                # Visualization images
    └── <video_name>_<round>_evaluation.png
```

**Round suffix handling**: when evaluating directories with round information (e.g. `easy_round1`), the video script automatically extracts the round suffix from the input directory path and appends it to all output filenames (e.g. `_round1`), so results from different rounds can be distinguished.

### Visualization Layout

Each visualization is a 2x2 grid (top-left is the generated image, or the path accumulated from all video frames):

```
┌─────────────────┬─────────────────┐
│  Generated /    │  Solution       │
│  Video Path     │  (reference)    │
├─────────────────┼─────────────────┤
│  Wall Crossing  │  Path Compare   │
│  Overlay        │  Overlay        │
└─────────────────┴─────────────────┘
```

**Color Legend (Path Compare)**:
- Green: Solution path only (missed by generated)
- Red: Generated path only (extra exploration)
- Yellow: Overlap (correct path)

**Color Legend (Wall Crossing)**:
- Yellow: Actual wall crossing (counted)
- Image: Orange = edge touch (tolerated, not counted)
- Video: Light blue = valid path (not crossing walls)

## File Naming Convention

| | Pattern | Example |
|---|---------|---------|
| Generated image | `{algo}_{difficulty}_{size}_n{idx}_{variant}_targeted_solution.png` | `dfs_easy_3x3_n000_var1_fixed_both_targeted_solution.png` |
| Generated video | `{algo}_{difficulty}_{size}_n{idx}_{variant}.mp4` | `dfs_easy_3x3_n000_var1_fixed_both.mp4` |
| Solution image | `{algo}_{difficulty}_{size}_n{idx}_{variant}_solution.png` | `dfs_easy_3x3_n000_var1_fixed_both_solution.png` |

## Example Output

Video evaluation result (image results contain the same fields minus the video-specific and gated ones):

```json
{
  "filename": "dfs_easy_3x3_n000_var1_fixed_both.mp4",
  "solution_file": "dfs_easy_3x3_n000_var1_fixed_both_solution.png",
  "wall_crossing_detected": false,
  "wall_crossing_pixels": 0,
  "wall_crossing_ratio": 0.0,
  "layout_match_score": 0.988,
  "maze_structure_iou": 0.85,
  "green_position_match": true,
  "red_position_match": true,
  "path_match_iou": 0.369,
  "path_precision": 0.554,
  "path_recall": 0.525,
  "target_achievement": 0.98,
  "has_reflection": true,
  "loop_count": 20,
  "path_length_ratio": 1.95,
  "exploration_score": 1.0,
  "total_frames": 192,
  "frames_with_marker": 180,
  "path_extraction_method": "green_marker_tracking",
  "overall_score": 0.382,
  "layout_match_score_gated": 1,
  "target_achievement_gated": 1,
  "overall_score_gated": 1
}
```

**Gating example breakdown**:
- `maze_structure_iou = 0.85` → `layout_match_score_gated = 1` (0.85 > 0.8)
- `wall_crossing_detected = false` → passes wall crossing check
- `target_achievement = 0.98` → `target_achievement_gated = 1` (0.98 > 0.95)
- All three conditions met → `overall_score_gated = 1`

## Summary Statistics

After evaluating a directory, each script outputs aggregated statistics (gated/video-specific blocks appear for video evaluation only):

```json
{
  "summary": {
    "wall_crossing": {
      "count": 5,
      "rate": 0.05
    },
    "path_matching": {
      "mean_iou": 0.45,
      "std_iou": 0.15,
      "mean_precision": 0.62,
      "mean_recall": 0.71,
      "mean_target_achievement": 0.92
    },
    "layout_matching": {
      "mean_score": 0.95,
      "green_match_rate": 0.98,
      "red_match_rate": 0.97
    },
    "reflection": {
      "count": 42,
      "rate": 0.42
    },
    "overall": {
      "mean_score": 0.51,
      "std_score": 0.18,
      "min_score": 0.10,
      "max_score": 0.85
    },
    "gated_metrics": {
      "layout_match_score_gated_count": 80,
      "layout_match_score_gated_rate": 0.80,
      "target_achievement_gated_count": 75,
      "target_achievement_gated_rate": 0.75,
      "overall_score_gated_count": 70,
      "overall_score_gated_rate": 0.70
    },
    "video_specific": {
      "avg_frames_with_marker": 175.5
    }
  }
}
```

## Tuning Parameters

Image evaluation (`image_gen_evaluation.py`):

| Parameter | Default | Description |
|-----------|---------|-------------|
| `tolerance_pixels` | 3 | Wall erosion for edge tolerance |
| `min_crossing_ratio` | 0.01 | Min ratio to flag wall crossing |
| `position_tolerance` | 20.0 | Max centroid distance for position match |
| `dilation_size` | auto | Size to dilate thin lines (auto-detected) |

Video evaluation (`video_gen_evaluation.py`):

| Parameter | Default | Description |
|-----------|---------|-------------|
| `num_frames` | 192 | Number of frames to extract from each video |
| `min_crossing_ratio` | 0.05 | Min ratio to flag wall crossing (5%) |
| `position_tolerance` | 50.0 | Max centroid distance for position match |
| `wall_erosion` | cell_size/4 | Erosion applied to walls before crossing check |
| `dilation_size` | auto | Size to dilate paths (auto-detected from cell size) |
| `BLACK_THRESHOLD` | 30 | Grayscale threshold for wall detection |
| `WHITE_THRESHOLD` | 200 | Grayscale threshold for walkable path detection |

## Image vs Video Evaluation Differences

| Aspect | Image Evaluation | Video Evaluation |
|--------|-----------------|------------------|
| Input | PNG image files | MP4 video files |
| Path Source | Blue path in generated image | Accumulated green marker positions |
| Frame Processing | Single image | 192 frames per video |
| Layout Check | Single image check | Minimum score across ALL frames |
| Wall Reference | Solution's walls only | Solution's walls only |
| Position Tolerance | 20 pixels | 50 pixels |
| Parallel Processing | N/A | ThreadPoolExecutor for frames |
| Gated Metrics | N/A | Binary pass/fail (see above) |

## Comparison with VLM-based Evaluation

| Aspect | These Scripts (Vision) | VLM-based (Gemini) |
|--------|------------------------|-------------------|
| Speed | Fast (~0.5s/image, ~5-10s/video) | Slow (~5s/image, ~30s/video) |
| Cost | Free | API costs |
| Consistency | Deterministic | May vary |
| Interpretability | Pixel-level metrics | Natural language |
| Edge cases | May miss semantic issues | Better reasoning |

## Logging

Evaluation logs are saved to:
```
./evaluation_logs/
├── maze_vis_evaluation_<timestamp>.log          # image evaluation
└── maze_video_vis_evaluation_<timestamp>.log    # video evaluation
```