Datasets:
Download visualize_gt_vs_annotator.py from vapaau/TUBcertainty: direct link, hf CLI and curl.
- Browser
- Download file 4.76 kB
-
https://huggingface.co/datasets/vapaau/TUBcertainty/resolve/main/visualize_gt_vs_annotator.py
- Command line
-
hf download hf://datasets/vapaau/TUBcertainty/visualize_gt_vs_annotator.py
-
curl -L -o visualize_gt_vs_annotator.py https://huggingface.co/datasets/vapaau/TUBcertainty/resolve/main/visualize_gt_vs_annotator.py
4.76 kB
| 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() | |