PCFootprint / evaluation.py
Haoyuan-Shen's picture
Create evaluation.py
2f0cdee verified
Raw
History Blame Contribute Delete
4.58 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
Author: Kuihao Wang
Email: wangkuihao2025@mails.szu.edu.cn
Date: 2026/03/13
-------------------------------------------------
"""
"""
COCO Metrics Evaluator
This is an independent script for calculating standard COCO evaluation metrics (mAP, AP50, AR, etc.).
The script simultaneously outputs evaluation results for both Instance Segmentation and Bounding Box.
Ideal for evaluating models that output polygons (e.g., building footprint extraction,
remote sensing instance segmentation, etc.).
[Dependencies]
pip install pycocotools
[Usage]
python eval_coco.py --gt path/to/ground_truth.json --dt path/to/predictions.json
[Input File Requirements]
1. Ground Truth (--gt):
Must be a standard COCO dataset JSON dictionary containing 'images', 'annotations', and 'categories'.
For polygon annotations, the 'segmentation' field should be a nested list:
"segmentation": [[x1, y1, x2, y2, x3, y3, ...]]
2. Predictions (--dt):
Must be a JSON list containing prediction results.
⚠️ Required fields: 'image_id', 'category_id', 'bbox', 'segmentation', 'score'
Example:
[
{
"image_id": 1,
"category_id": 1,
"bbox": [100.0, 150.0, 50.0, 60.0],
"segmentation": [[100.0, 150.0, 150.0, 150.0, 150.0, 210.0, 100.0, 210.0]],
"score": 0.952 // Confidence score; COCOeval relies on this for ranking to calculate mAP
}
]
[Output Description]
The script prints two official COCO format evaluation tables to the terminal:
- AP @ IoU=0.50:0.95 (Primary metric: mAP)
- AP @ IoU=0.50 (AP50)
- AP @ IoU=0.75 (AP75)
- AP for small/medium/large objects (Accuracy across different scales)
- AR (Average Recall)
"""
import argparse
import os
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
def main():
# Initialize command-line argument parser
parser = argparse.ArgumentParser(
description="Calculate standard COCO metrics (BBox & Segmentation) for model predictions."
)
parser.add_argument(
"--gt",
type=str,
required=True,
help="Path to Ground Truth JSON file (standard COCO annotation format)."
)
parser.add_argument(
"--dt",
type=str,
required=True,
help="Path to Detection/Prediction JSON file (list of dicts with 'score')."
)
args = parser.parse_args()
# Check if files exist to prevent errors
if not os.path.exists(args.gt):
raise FileNotFoundError(f"Ground Truth file not found: {args.gt}")
if not os.path.exists(args.dt):
raise FileNotFoundError(f"Prediction file not found: {args.dt}")
# ==========================================
# 1. Load Ground Truth
# ==========================================
print(f"[*] Loading Ground Truth from: {args.gt}")
# The COCO class automatically parses the JSON and indexes images, categories, and annotations
cocoGt = COCO(args.gt)
# ==========================================
# 2. Load Predictions
# ==========================================
print(f"[*] Loading Predictions from: {args.dt}")
# loadRes creates a new COCO object for evaluation based on the prediction list and GT structure
cocoDt = cocoGt.loadRes(args.dt)
# ==========================================
# 3. Execute Evaluation: Instance Segmentation (Mask/Polygons)
# ==========================================
print("\n" + "="*50)
print("Running COCO Evaluation (Segmentation Mask/Polygons)")
print("="*50)
# Instantiate COCOeval, specifying 'segm' to perform IoU calculations on the segmentation field
cocoEval_segm = COCOeval(cocoGt, cocoDt, 'segm')
cocoEval_segm.evaluate() # Matches detections to ground truth per image/category
cocoEval_segm.accumulate() # Accumulates evaluation results across all images
cocoEval_segm.summarize() # Prints the summary metrics table (mAP, AR, etc.)
# ==========================================
# 4. Execute Evaluation: Object Detection (Bounding Box)
# ==========================================
print("\n" + "="*50)
print("Running COCO Evaluation (Bounding Box)")
print("="*50)
# Instantiate COCOeval, specifying 'bbox' to perform IoU calculations on the bbox field
cocoEval_bbox = COCOeval(cocoGt, cocoDt, 'bbox')
cocoEval_bbox.evaluate()
cocoEval_bbox.accumulate()
cocoEval_bbox.summarize()
if __name__ == "__main__":
main()