FaVOSsubmission commited on
Commit
8d01ebb
·
verified ·
1 Parent(s): 731dbf8

Remove non-dataset files

Browse files
Files changed (3) hide show
  1. README.md +0 -49
  2. eval_jnf_v.py +0 -391
  3. requirements.txt +0 -5
README.md DELETED
@@ -1,49 +0,0 @@
1
- # FaVOS
2
-
3
- ## Download
4
-
5
- ```bash
6
- huggingface-cli download FaVOSsubmission/FaVOS \
7
- --repo-type dataset \
8
- --include "JPEGImages.zip" \
9
- --include "Annotations.zip" \
10
- --include "favos-20.txt" \
11
- --include "favos-40.txt" \
12
- --local-dir data
13
-
14
- unzip -q data/JPEGImages.zip -d data
15
- unzip -q data/Annotations.zip -d data
16
- ```
17
-
18
- ## J&F_v Evaluation
19
-
20
- Assume the dataset is downloaded under `FaVOS/data/`:
21
-
22
- ```text
23
- FaVOS/data/
24
- JPEGImages/
25
- Annotations/
26
- favos-20.txt
27
- favos-40.txt
28
- ```
29
-
30
- Install dependencies:
31
-
32
- ```bash
33
- pip install -r requirements.txt
34
- ```
35
-
36
- Evaluate predictions:
37
-
38
- ```bash
39
- python eval_jnf_v.py \
40
- --pred-root /path/to/predictions \
41
- --output-dir results/jf_v
42
- ```
43
-
44
- Prediction masks should be indexed PNG files in one of these layouts:
45
-
46
- ```text
47
- /path/to/predictions/Annotations/<video_id>/<frame>.png
48
- /path/to/predictions/<video_id>/<frame>.png
49
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eval_jnf_v.py DELETED
@@ -1,391 +0,0 @@
1
- #!/usr/bin/env python3
2
- from __future__ import annotations
3
-
4
- import argparse
5
- import csv
6
- import json
7
- import os
8
- from concurrent.futures import ProcessPoolExecutor, as_completed
9
- from dataclasses import asdict, dataclass
10
- from pathlib import Path
11
-
12
- import numpy as np
13
- from PIL import Image
14
- from scipy.ndimage import distance_transform_edt
15
- from tqdm.auto import tqdm
16
-
17
-
18
- DATASET_ROOT = Path("data")
19
- SPLITS = ("favos-20", "favos-40")
20
- OUTPUT_DIR = Path("results/jf_v")
21
- BOUND_TH = 0.008
22
- WORKERS = min(8, os.cpu_count() or 1)
23
-
24
-
25
- @dataclass(frozen=True)
26
- class JNFVResult:
27
- j_v: float
28
- f_v: float
29
- jnf_v: float
30
- precision_v: float
31
- recall_v: float
32
- intersection_volume: int
33
- union_volume: int
34
- pred_boundary_voxels: int
35
- gt_boundary_voxels: int
36
-
37
-
38
- @dataclass(frozen=True)
39
- class ObjectResult:
40
- split: str
41
- video_id: str
42
- object_id: int
43
- num_frames: int
44
- j_v: float
45
- f_v: float
46
- jnf_v: float
47
- precision_v: float
48
- recall_v: float
49
- intersection_volume: int
50
- union_volume: int
51
- pred_boundary_voxels: int
52
- gt_boundary_voxels: int
53
-
54
-
55
- @dataclass(frozen=True)
56
- class VideoResult:
57
- split: str
58
- video_id: str
59
- num_objects: int
60
- num_frames: int
61
- j_v: float
62
- f_v: float
63
- jnf_v: float
64
-
65
-
66
- def parse_args() -> argparse.Namespace:
67
- parser = argparse.ArgumentParser(
68
- description=(
69
- "Evaluate J&F_v on FaVOS indexed-PNG predictions. "
70
- "The dataset is expected under data/."
71
- )
72
- )
73
- parser.add_argument(
74
- "--pred-root",
75
- type=Path,
76
- required=True,
77
- help="Prediction root. Accepts either <root>/Annotations/<video_id> or <root>/<video_id>.",
78
- )
79
- parser.add_argument("--output-dir", type=Path, default=OUTPUT_DIR)
80
- return parser.parse_args()
81
-
82
-
83
- def numeric_pngs(path: Path) -> list[Path]:
84
- return sorted(
85
- [p for p in path.glob("*.png") if p.is_file() and not p.name.startswith("._")],
86
- key=lambda p: int(p.stem),
87
- )
88
-
89
-
90
- def load_label(path: Path) -> np.ndarray:
91
- with Image.open(path) as image:
92
- return np.asarray(image, dtype=np.uint8)
93
-
94
-
95
- def read_split(dataset_root: Path, split: str) -> list[str]:
96
- path = dataset_root / f"{split}.txt"
97
- if not path.is_file():
98
- raise FileNotFoundError(f"Missing split file: {path}")
99
- ids = [line.strip() for line in path.read_text(encoding="utf-8").splitlines()]
100
- return list(dict.fromkeys(video_id for video_id in ids if video_id and not video_id.startswith("#")))
101
-
102
-
103
- def resolve_pred_root(pred_root: Path) -> Path:
104
- annotations = pred_root / "Annotations"
105
- return annotations if annotations.is_dir() else pred_root
106
-
107
-
108
- def load_video(gt_dir: Path, pred_dir: Path) -> tuple[np.ndarray, np.ndarray]:
109
- gt_paths = numeric_pngs(gt_dir)
110
- pred_by_name = {p.name: p for p in numeric_pngs(pred_dir)}
111
- if not gt_paths:
112
- raise FileNotFoundError(f"No GT masks found in {gt_dir}")
113
-
114
- missing = [p.name for p in gt_paths if p.name not in pred_by_name]
115
- if missing:
116
- raise FileNotFoundError(f"Missing {len(missing)} prediction masks in {pred_dir}: {missing[:5]}")
117
-
118
- gt_paths = gt_paths[1:]
119
- if not gt_paths:
120
- raise ValueError(f"No evaluation frames found in {gt_dir}")
121
-
122
- gt = np.stack([load_label(path) for path in gt_paths], axis=0)
123
- pred = np.stack([load_label(pred_by_name[path.name]) for path in gt_paths], axis=0)
124
- if gt.shape != pred.shape:
125
- raise ValueError(f"Shape mismatch for {gt_dir.name}: GT {gt.shape}, pred {pred.shape}")
126
- return gt, pred
127
-
128
-
129
- def as_bool_volume(volume: np.ndarray) -> np.ndarray:
130
- if volume.ndim != 3:
131
- raise ValueError(f"Expected (T,H,W), got {volume.shape}")
132
- return volume.astype(bool)
133
-
134
-
135
- def mean_visible_area(volume: np.ndarray) -> float:
136
- areas = np.sum(volume, axis=(1, 2), dtype=np.int64)
137
- visible = areas[areas > 0]
138
- return float(np.mean(visible)) if visible.size else 0.0
139
-
140
-
141
- def spatial_radius(shape_2d: tuple[int, int], object_area: float, bound_th: float) -> int:
142
- radius = bound_th if bound_th >= 1 else bound_th * np.linalg.norm(shape_2d)
143
- if object_area > 0:
144
- radius = min(radius, 0.1 * np.sqrt(object_area))
145
- return max(int(np.ceil(radius)), 0)
146
-
147
-
148
- def boundary_volume(volume: np.ndarray) -> np.ndarray:
149
- volume = volume.astype(bool)
150
- boundary = np.zeros_like(volume, dtype=bool)
151
- for dt in (0, 1):
152
- for dy in (0, 1):
153
- for dx in (0, 1):
154
- if dt == 0 and dy == 0 and dx == 0:
155
- continue
156
- src = (
157
- slice(0, volume.shape[0] - dt),
158
- slice(0, volume.shape[1] - dy),
159
- slice(0, volume.shape[2] - dx),
160
- )
161
- dst = (
162
- slice(dt, volume.shape[0]),
163
- slice(dy, volume.shape[1]),
164
- slice(dx, volume.shape[2]),
165
- )
166
- boundary[src] |= volume[src] ^ volume[dst]
167
- return boundary
168
-
169
-
170
- def count_matches(source_boundary: np.ndarray, target_boundaries: np.ndarray, radius: int) -> int:
171
- if not np.any(source_boundary) or not np.any(target_boundaries):
172
- return 0
173
- matched = np.zeros_like(source_boundary, dtype=bool)
174
- for target in target_boundaries:
175
- if np.any(target):
176
- matched |= distance_transform_edt(~target) <= radius
177
- return int(np.sum(source_boundary & matched))
178
-
179
-
180
- def compute_jnf_v(
181
- gt_volume: np.ndarray,
182
- pred_volume: np.ndarray,
183
- ) -> JNFVResult:
184
- gt = as_bool_volume(gt_volume)
185
- pred = as_bool_volume(pred_volume)
186
- if gt.shape != pred.shape:
187
- raise ValueError(f"Shape mismatch: GT {gt.shape}, pred {pred.shape}")
188
-
189
- intersections = np.sum(gt & pred, axis=(1, 2), dtype=np.int64)
190
- unions = np.sum(gt | pred, axis=(1, 2), dtype=np.int64)
191
- total_intersection = int(np.sum(intersections, dtype=np.int64))
192
- total_union = int(np.sum(unions, dtype=np.int64))
193
- if total_union == 0:
194
- j_v = 1.0
195
- else:
196
- nonempty = unions > 0
197
- j_v = float(np.sum((unions[nonempty] / total_union) * (intersections[nonempty] / unions[nonempty])))
198
-
199
- radius = spatial_radius(gt.shape[1:], mean_visible_area(gt), BOUND_TH)
200
- gt_boundary = boundary_volume(gt)
201
- pred_boundary = boundary_volume(pred)
202
-
203
- matched_pred = 0
204
- matched_gt = 0
205
- total_pred_boundary = 0
206
- total_gt_boundary = 0
207
- for t in range(gt.shape[0]):
208
- gt_t = gt_boundary[t]
209
- pred_t = pred_boundary[t]
210
- n_gt = int(np.sum(gt_t))
211
- n_pred = int(np.sum(pred_t))
212
- total_gt_boundary += n_gt
213
- total_pred_boundary += n_pred
214
- if n_gt:
215
- matched_gt += count_matches(gt_t, pred_boundary[t : t + 1], radius)
216
- if n_pred:
217
- matched_pred += count_matches(pred_t, gt_boundary[t : t + 1], radius)
218
-
219
- if total_pred_boundary == 0 and total_gt_boundary == 0:
220
- precision = 1.0
221
- recall = 1.0
222
- elif total_pred_boundary == 0:
223
- precision = 1.0
224
- recall = 0.0
225
- elif total_gt_boundary == 0:
226
- precision = 0.0
227
- recall = 1.0
228
- else:
229
- precision = float(matched_pred / total_pred_boundary)
230
- recall = float(matched_gt / total_gt_boundary)
231
- f_v = 0.0 if precision + recall == 0 else float(2.0 * precision * recall / (precision + recall))
232
-
233
- return JNFVResult(
234
- j_v=j_v,
235
- f_v=f_v,
236
- jnf_v=(j_v + f_v) / 2.0,
237
- precision_v=precision,
238
- recall_v=recall,
239
- intersection_volume=total_intersection,
240
- union_volume=total_union,
241
- pred_boundary_voxels=total_pred_boundary,
242
- gt_boundary_voxels=total_gt_boundary,
243
- )
244
-
245
-
246
- def evaluate_video(task: tuple[str, Path, Path]) -> dict[str, object]:
247
- video_id, gt_root, pred_root = task
248
- try:
249
- gt, pred = load_video(gt_root / video_id, pred_root / video_id)
250
- object_ids = [int(v) for v in np.unique(gt) if int(v) != 0]
251
- if not object_ids:
252
- raise ValueError(f"No foreground objects in {gt_root / video_id}")
253
-
254
- objects: list[ObjectResult] = []
255
- for object_id in object_ids:
256
- pred_obj = pred == object_id
257
- result = compute_jnf_v(
258
- gt == object_id,
259
- pred_obj,
260
- )
261
- objects.append(
262
- ObjectResult(
263
- split="all",
264
- video_id=video_id,
265
- object_id=object_id,
266
- num_frames=int(gt.shape[0]),
267
- **asdict(result),
268
- )
269
- )
270
-
271
- video = VideoResult(
272
- split="all",
273
- video_id=video_id,
274
- num_objects=len(objects),
275
- num_frames=int(gt.shape[0]),
276
- j_v=float(np.mean([row.j_v for row in objects])),
277
- f_v=float(np.mean([row.f_v for row in objects])),
278
- jnf_v=float(np.mean([row.jnf_v for row in objects])),
279
- )
280
- return {"video_id": video_id, "objects": objects, "video": video, "error": None}
281
- except Exception as exc:
282
- return {"video_id": video_id, "objects": [], "video": None, "error": {"video_id": video_id, "error": str(exc)}}
283
-
284
-
285
- def write_csv(path: Path, rows: list[dict[str, object]]) -> None:
286
- if not rows:
287
- return
288
- path.parent.mkdir(parents=True, exist_ok=True)
289
- with path.open("w", newline="", encoding="utf-8") as handle:
290
- writer = csv.DictWriter(handle, fieldnames=list(rows[0].keys()))
291
- writer.writeheader()
292
- writer.writerows(rows)
293
-
294
-
295
- def summarize(split: str, objects: list[ObjectResult], videos: list[VideoResult]) -> dict[str, object]:
296
- return {
297
- "split": split,
298
- "num_videos": len(videos),
299
- "num_objects": len(objects),
300
- "num_object_frames": int(sum(row.num_frames for row in objects)),
301
- "j_v": float(np.mean([row.j_v for row in objects])) if objects else 0.0,
302
- "f_v": float(np.mean([row.f_v for row in objects])) if objects else 0.0,
303
- "jnf_v": float(np.mean([row.jnf_v for row in objects])) if objects else 0.0,
304
- "per_video_j_v": float(np.mean([row.j_v for row in videos])) if videos else 0.0,
305
- "per_video_f_v": float(np.mean([row.f_v for row in videos])) if videos else 0.0,
306
- "per_video_jnf_v": float(np.mean([row.jnf_v for row in videos])) if videos else 0.0,
307
- }
308
-
309
-
310
- def main() -> int:
311
- args = parse_args()
312
- dataset_root = DATASET_ROOT
313
- gt_root = dataset_root / "Annotations"
314
- pred_root = resolve_pred_root(args.pred_root)
315
- if not gt_root.is_dir():
316
- raise FileNotFoundError(f"Missing GT root: {gt_root}")
317
- if not pred_root.is_dir():
318
- raise FileNotFoundError(f"Missing prediction root: {pred_root}")
319
-
320
- splits = {split: read_split(dataset_root, split) for split in SPLITS}
321
- unique_ids = sorted({video_id for ids in splits.values() for video_id in ids})
322
- if not unique_ids:
323
- raise ValueError("No videos selected for evaluation.")
324
-
325
- tasks = [
326
- (
327
- video_id,
328
- gt_root,
329
- pred_root,
330
- )
331
- for video_id in unique_ids
332
- ]
333
-
334
- objects_by_video: dict[str, list[ObjectResult]] = {}
335
- videos_by_video: dict[str, VideoResult] = {}
336
- max_workers = min(max(WORKERS, 1), len(tasks))
337
-
338
- if max_workers == 1:
339
- iterator = tqdm(tasks, desc="Evaluating", unit="video")
340
- for task in iterator:
341
- result = evaluate_video(task)
342
- if result["error"] is not None:
343
- raise RuntimeError(f"Failed evaluating {result['video_id']}: {result['error']['error']}")
344
- objects_by_video[result["video_id"]] = result["objects"]
345
- videos_by_video[result["video_id"]] = result["video"]
346
- else:
347
- with ProcessPoolExecutor(max_workers=max_workers) as executor:
348
- futures = [executor.submit(evaluate_video, task) for task in tasks]
349
- iterator = as_completed(futures)
350
- iterator = tqdm(iterator, total=len(futures), desc="Evaluating", unit="video")
351
- for future in iterator:
352
- result = future.result()
353
- if result["error"] is not None:
354
- raise RuntimeError(f"Failed evaluating {result['video_id']}: {result['error']['error']}")
355
- objects_by_video[result["video_id"]] = result["objects"]
356
- videos_by_video[result["video_id"]] = result["video"]
357
-
358
- all_objects: list[ObjectResult] = []
359
- all_videos: list[VideoResult] = []
360
- summaries: dict[str, dict[str, object]] = {}
361
- for split, ids in splits.items():
362
- split_objects: list[ObjectResult] = []
363
- split_videos: list[VideoResult] = []
364
- for video_id in ids:
365
- for row in objects_by_video.get(video_id, []):
366
- split_objects.append(ObjectResult(split=split, **{k: v for k, v in asdict(row).items() if k != "split"}))
367
- if video_id in videos_by_video:
368
- row = videos_by_video[video_id]
369
- split_videos.append(VideoResult(split=split, **{k: v for k, v in asdict(row).items() if k != "split"}))
370
- all_objects.extend(split_objects)
371
- all_videos.extend(split_videos)
372
- summaries[split] = summarize(split, split_objects, split_videos)
373
-
374
- args.output_dir.mkdir(parents=True, exist_ok=True)
375
- write_csv(args.output_dir / "per_object_jf_v.csv", [asdict(row) for row in all_objects])
376
- write_csv(args.output_dir / "per_video_jf_v.csv", [asdict(row) for row in all_videos])
377
- summary = {
378
- "splits": summaries,
379
- }
380
- (args.output_dir / "summary.json").write_text(json.dumps(summary, indent=2, sort_keys=True) + "\n", encoding="utf-8")
381
-
382
- for split, row in summaries.items():
383
- print(
384
- f"{split}: videos={row['num_videos']} objects={row['num_objects']} "
385
- f"Jv={row['j_v']:.6f} Fv={row['f_v']:.6f} J&F_v={row['jnf_v']:.6f}"
386
- )
387
- return 0
388
-
389
-
390
- if __name__ == "__main__":
391
- raise SystemExit(main())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt DELETED
@@ -1,5 +0,0 @@
1
- numpy
2
- pillow
3
- scipy
4
- tqdm
5
- huggingface_hub