Datasets:

Modalities:
Image
Size:
< 1K
ArXiv:
Libraries:
Datasets
File size: 4,759 Bytes
ada18d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import os

import matplotlib.pyplot as plt
from matplotlib.patches import Patch
from matplotlib.patches import Polygon
import numpy as np
from PIL import Image
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval

xp_images = ["Exp6_Cam1_Stage01.jpg", "Exp6_Cam1_Stage03.jpg", "Exp6_Cam1_Stage05.jpg",
        "Exp17_Cam1_Stage01.jpg", "Exp17_Cam1_Stage04.jpg", "Exp17_Cam1_Stage05.jpg",
        "Exp30_Cam1_Stage01.jpg", "Exp30_Cam1_Stage05.jpg", "Exp30_Cam1_Stage07.jpg",
        "Exp21_Cam2_Stage01.jpg", "Exp21_Cam2_Stage03.jpg", "Exp21_Cam2_Stage05.jpg",
        "Exp18_Cam3_Stage01.jpg", "Exp18_Cam3_Stage04.jpg", "Exp18_Cam3_Stage06.jpg"]

coco_gt_path = "instance_segmentation/ground_truth_15imgs_coco.json"
multiannotation_path = "instance_segmentation/multiannotator_15imgs.json"
img_folder = "images"
binary_folder = "binary_segmentation"

if __name__ == "__main__":
    coco = COCO(coco_gt_path)

    # Sanity check: display the ground truth of one image
    img_info = coco.imgs[1]
    anns = coco.loadAnns(coco.getAnnIds(imgIds=img_info["id"]))
    print(f"{img_info['file_name']}: {len(anns)} annotations")

    plt.figure(figsize=(12, 8))
    plt.imshow(Image.open(os.path.join(img_folder, img_info["file_name"])))
    coco.showAnns(anns, draw_bbox=True)
    plt.title(img_info["file_name"])
    plt.axis("off")
    plt.tight_layout()
    plt.savefig("example_gt.png", dpi=100)
    plt.show()

    # Same image, annotated by one of the annotators
    with open(multiannotation_path) as f:
        multiannotations = json.load(f)

    annotation = multiannotations[img_info["file_name"]][1] # index 1 is the second annotator, index 0 is the first annotator, etc
    print(f"{img_info['file_name']}: annotator {annotation['user_id']}, "
          f"{len(annotation['polygons'])} polygons")

    fig, ax = plt.subplots(figsize=(12, 8))
    ax.imshow(Image.open(os.path.join(img_folder, img_info["file_name"])))
    for poly in annotation["polygons"]:
        pts = [(p["x"], p["y"]) for p in poly["polygon_pts"]]
        ax.add_patch(Polygon(pts, closed=True, fill=True, alpha=0.4,
                             facecolor="tab:orange", edgecolor="tab:orange", linewidth=2))
    ax.set_title(f"{img_info['file_name']} - annotator {annotation['user_id']}")
    ax.axis("off")
    fig.tight_layout()
    fig.savefig("example_annotator.png", dpi=100)
    plt.show()

    # Evaluate the annotator against the ground truth with COCO metrics (this image only).
    # User-reported confidence is used as the bbox/segmentation score.
    detections = []
    for poly in annotation["polygons"]:
        flat = [c for p in poly["polygon_pts"] for c in (p["x"], p["y"])]
        xs, ys = flat[0::2], flat[1::2]
        detections.append({
            "image_id": img_info["id"], "category_id": 1, "segmentation": [flat],
            "bbox": [min(xs), min(ys), max(xs) - min(xs), max(ys) - min(ys)],
            "score": poly.get("polygon_confidence") or 1.0,
        })

    coco_dt = coco.loadRes(detections)
    for iou_type in ("segm", "bbox"):
        print(f"\n=== {iou_type} ===")
        coco_eval = COCOeval(coco, coco_dt, iou_type)
        coco_eval.params.imgIds = [img_info["id"]]
        coco_eval.evaluate()
        coco_eval.accumulate()
        coco_eval.summarize()

    # Binary (foreground/background) IoU between the annotator and ground truth masks
    name = img_info["file_name"]
    gt_mask = np.array(Image.open(os.path.join(binary_folder, f"{name}_GT.png"))).astype(bool)
    annotator_mask = np.array(
        Image.open(os.path.join(binary_folder, f"{name}_{annotation['user_id']}.png"))).astype(bool)

    intersection = np.logical_and(gt_mask, annotator_mask).sum()
    union = np.logical_or(gt_mask, annotator_mask).sum()
    print(f"\nBinary IoU ({name}, annotator {annotation['user_id']}): {intersection / union:.3f}")

    # Overlay both masks on the image: agreement in green, GT only in red, annotator only in blue
    overlay = np.zeros((*gt_mask.shape, 4))
    overlay[gt_mask & annotator_mask] = (0, 0.8, 0, 0.5)
    overlay[gt_mask & ~annotator_mask] = (1, 0, 0, 0.5)
    overlay[~gt_mask & annotator_mask] = (0, 0.3, 1, 0.5)

    fig, ax = plt.subplots(figsize=(12, 8))
    ax.imshow(Image.open(os.path.join(img_folder, name)))
    ax.imshow(overlay)
    ax.legend(handles=[Patch(color=(0, 0.8, 0), label="both"),
                       Patch(color=(1, 0, 0), label="GT only"),
                       Patch(color=(0, 0.3, 1), label="annotator only")], loc="lower right")
    ax.set_title(f"{name} - GT vs annotator {annotation['user_id']} (IoU {intersection / union:.3f})")
    ax.axis("off")
    fig.tight_layout()
    fig.savefig("example_binary_masks.png", dpi=100)
    plt.show()