| """ |
| Evaluate detection results from inference_k2.py output. |
| No GPU needed — pure CPU computation. |
| """ |
| import json |
| import re |
| import argparse |
| from pathlib import Path |
| from collections import defaultdict |
|
|
| GRID_SIZE = 1000 |
|
|
|
|
| def extract_bboxes_from_response(response_text): |
| """Extract bboxes from model response, handles both GT and model output formats.""" |
| try: |
| response_clean = response_text.strip() |
| if response_clean.startswith('"') and response_clean.endswith('"'): |
| try: |
| response_clean = json.loads(response_clean) |
| except Exception: |
| pass |
|
|
| if isinstance(response_clean, str): |
| if not (response_clean.startswith('{') or response_clean.startswith('[')): |
| match = re.search(r'[\{\[].*[\}\]]', response_clean, re.DOTALL) |
| if match: |
| response_clean = match.group() |
| data = json.loads(response_clean) |
| else: |
| data = response_clean |
|
|
| pattern = r'<x(\d+)><y(\d+)><x(\d+)><y(\d+)>' |
|
|
| |
| if isinstance(data, list): |
| all_bbox_strs = [] |
| for item in data: |
| all_bbox_strs.extend(item.get("bbox", [])) |
| |
| elif isinstance(data, dict): |
| all_bbox_strs = data.get("bboxes", []) |
| else: |
| return [] |
|
|
| bboxes = [] |
| for bbox_str in all_bbox_strs: |
| match = re.search(pattern, bbox_str) |
| if match: |
| x1, y1, x2, y2 = map(int, match.groups()) |
| bboxes.append([x1, y1, x2, y2]) |
| return bboxes |
| except Exception: |
| return [] |
|
|
|
|
| def grid_to_pixel(boxes, img_w, img_h): |
| """Convert 1000-grid coords to pixel coords.""" |
| return [[ |
| x1 * img_w / GRID_SIZE, |
| y1 * img_h / GRID_SIZE, |
| x2 * img_w / GRID_SIZE, |
| y2 * img_h / GRID_SIZE, |
| ] for x1, y1, x2, y2 in boxes] |
|
|
|
|
| def compute_iou(box_a, box_b): |
| """Compute IoU between two boxes [x1, y1, x2, y2].""" |
| x1 = max(box_a[0], box_b[0]) |
| y1 = max(box_a[1], box_b[1]) |
| x2 = min(box_a[2], box_b[2]) |
| y2 = min(box_a[3], box_b[3]) |
| inter_w = max(0, x2 - x1) |
| inter_h = max(0, y2 - y1) |
| inter = inter_w * inter_h |
| if inter == 0: |
| return 0.0 |
| area_a = (box_a[2] - box_a[0]) * (box_a[3] - box_a[1]) |
| area_b = (box_b[2] - box_b[0]) * (box_b[3] - box_b[1]) |
| return inter / (area_a + area_b - inter + 1e-9) |
|
|
|
|
| def match_boxes(gt_boxes, pred_boxes, iou_thr=0.5): |
| """Greedy matching of pred to GT boxes. Returns tp, fp, fn counts and per-match details.""" |
| gt_matched = [False] * len(gt_boxes) |
| tp = 0 |
| matches = [] |
|
|
| for pred_idx, pred_box in enumerate(pred_boxes): |
| best_iou = 0.0 |
| best_gt_idx = -1 |
| for gt_idx, gt_box in enumerate(gt_boxes): |
| if gt_matched[gt_idx]: |
| continue |
| iou = compute_iou(pred_box, gt_box) |
| if iou > best_iou: |
| best_iou = iou |
| best_gt_idx = gt_idx |
| if best_gt_idx >= 0 and best_iou >= iou_thr: |
| gt_matched[best_gt_idx] = True |
| tp += 1 |
| matches.append({'pred_idx': pred_idx, 'gt_idx': best_gt_idx, 'iou': best_iou, 'matched': True}) |
| else: |
| matches.append({'pred_idx': pred_idx, 'gt_idx': -1, 'iou': best_iou, 'matched': False}) |
|
|
| fp = len(pred_boxes) - tp |
| fn = len(gt_boxes) - tp |
| return tp, fp, fn, matches |
|
|
|
|
| def eval_results(input_path, output_dir, iou_thr=0.5): |
| """Main evaluation: re-extract bboxes, compute metrics, save outputs.""" |
| with open(input_path, 'r', encoding='utf-8') as f: |
| raw_data = json.load(f) |
|
|
| output_dir = Path(output_dir) |
| output_dir.mkdir(parents=True, exist_ok=True) |
|
|
| |
| per_sample = [] |
| for item in raw_data: |
| pred_boxes = extract_bboxes_from_response(item['model_response']) |
| gt_boxes = extract_bboxes_from_response(item['ground_truth']) |
| per_sample.append({ |
| 'index': item['index'], |
| 'image': item['image'], |
| 'pred_boxes_grid': pred_boxes, |
| 'gt_boxes_grid': gt_boxes, |
| }) |
|
|
| |
| total_gt = 0 |
| total_pred = 0 |
| total_tp = 0 |
| sample_metrics = [] |
|
|
| for s in per_sample: |
| gt = s['gt_boxes_grid'] |
| pred = s['pred_boxes_grid'] |
| tp, fp, fn, matches = match_boxes(gt, pred, iou_thr) |
|
|
| precision = tp / max(1, tp + fp) |
| recall = tp / max(1, len(gt)) if len(gt) > 0 else 0.0 |
| f1 = 2 * precision * recall / (precision + recall + 1e-9) |
|
|
| total_gt += len(gt) |
| total_pred += len(pred) |
| total_tp += tp |
|
|
| sample_metrics.append({ |
| 'index': s['index'], |
| 'image': s['image'], |
| 'num_gt': len(gt), |
| 'num_pred': len(pred), |
| 'tp': tp, |
| 'fp': fp, |
| 'fn': fn, |
| 'precision': round(precision, 4), |
| 'recall': round(recall, 4), |
| 'f1': round(f1, 4), |
| }) |
|
|
| |
| overall_precision = total_tp / max(1, total_tp + (total_pred - total_tp)) |
| overall_recall = total_tp / max(1, total_gt) |
| overall_f1 = 2 * overall_precision * overall_recall / (overall_precision + overall_recall + 1e-9) |
|
|
| |
| corrected = [] |
| for item, s in zip(raw_data, per_sample): |
| corrected.append({ |
| **item, |
| 'pred_bboxes': s['pred_boxes_grid'], |
| 'gt_bboxes': s['gt_boxes_grid'], |
| 'num_pred': len(s['pred_boxes_grid']), |
| 'num_gt': len(s['gt_boxes_grid']), |
| }) |
|
|
| corrected_path = output_dir / Path(input_path).name |
| with open(corrected_path, 'w', encoding='utf-8') as f: |
| json.dump(corrected, f, ensure_ascii=False, indent=2) |
|
|
| |
| simplified = [{'image': r['image'], 'gt_bboxes': r['gt_bboxes'], 'pred_bboxes': r['pred_bboxes']} |
| for r in corrected] |
| simplified_path = str(corrected_path).replace('.json', '_simplified.json') |
| with open(simplified_path, 'w', encoding='utf-8') as f: |
| json.dump(simplified, f, ensure_ascii=False, indent=2) |
|
|
| |
| metrics_path = output_dir / Path(input_path).name.replace('.json', '_metrics.json') |
| metrics_summary = { |
| 'input': str(input_path), |
| 'iou_threshold': iou_thr, |
| 'num_samples': len(sample_metrics), |
| 'total_gt': total_gt, |
| 'total_pred': total_pred, |
| 'total_tp': total_tp, |
| 'total_fp': total_pred - total_tp, |
| 'total_fn': total_gt - total_tp, |
| 'precision': round(overall_precision, 4), |
| 'recall': round(overall_recall, 4), |
| 'f1': round(overall_f1, 4), |
| 'per_sample': sample_metrics, |
| } |
| with open(metrics_path, 'w', encoding='utf-8') as f: |
| json.dump(metrics_summary, f, ensure_ascii=False, indent=2) |
|
|
| |
| print(f"\n{'='*60}") |
| print(f" Evaluation @ IoU={iou_thr}") |
| print(f"{'='*60}") |
| print(f" Samples : {len(sample_metrics)}") |
| print(f" GT boxes : {total_gt}") |
| print(f" Pred boxes : {total_pred}") |
| print(f" TP / FP / FN: {total_tp} / {total_pred - total_tp} / {total_gt - total_tp}") |
| print(f" Precision : {overall_precision:.4f}") |
| print(f" Recall : {overall_recall:.4f}") |
| print(f" F1 : {overall_f1:.4f}") |
| print(f"{'='*60}") |
| print(f"\nPer-sample details:") |
| for sm in sample_metrics: |
| print(f" [{sm['index']:3d}] GT={sm['num_gt']} Pred={sm['num_pred']} " |
| f"P={sm['precision']:.3f} R={sm['recall']:.3f} F1={sm['f1']:.3f} " |
| f"{Path(sm['image']).name}") |
|
|
| print(f"\nCorrected results : {corrected_path}") |
| print(f"Simplified results: {simplified_path}") |
| print(f"Metrics summary : {metrics_path}") |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="Evaluate detection results") |
| parser.add_argument('--input', '-i', required=True, help='Full results JSON from inference_k2.py') |
| parser.add_argument('--output-dir', '-o', default='.', help='Output directory') |
| parser.add_argument('--iou', type=float, default=0.5, help='IoU threshold') |
| args = parser.parse_args() |
| eval_results(args.input, args.output_dir, args.iou) |
|
|
|
|
| if __name__ == '__main__': |
| main() |
|
|