File size: 10,430 Bytes
62030e0 |
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 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 |
"""consistency.py: Integrity Check, Correction by Mapping for Annotation Class, Metadata Cleaning, Statistics"""
# System Imports
import os
import sys
import re
# Project Imports
from loader import load_classes, load_properties, read_dataset, write_dataset, file_name
# Third-Party Imports
import matplotlib.pyplot as plt
import numpy as np
__author__ = "Johannes Bayer, Shabi Haider"
__copyright__ = "Copyright 2021-2023, DFKI"
__license__ = "CC"
__version__ = "0.0.2"
__email__ = "johannes.bayer@dfki.de"
__status__ = "Prototype"
# Edit this lookup table for relabeling purposes
MAPPING_LOOKUP = {
"integrated_cricuit": "integrated_circuit",
"zener": "diode.zener"
}
def consistency(db: list, classes: dict, recover: dict = {}) -> tuple:
"""Checks Whether Annotation Classes are in provided Classes Dict and Attempts Recovery"""
total, ok, mapped, faulty, rotation, text = 0, 0, 0, 0, 0, 0
for sample in db:
for bbox in sample["bboxes"] + sample["polygons"] + sample["points"]:
total += 1
if bbox["class"] in classes:
ok += 1
if bbox["class"] in recover:
bbox["class"] = recover[bbox["class"]]
mapped += 1
if bbox["class"] not in classes and bbox["class"] not in recover:
print(f"Can't recover faulty label in {file_name(sample)}: {bbox['class']}")
faulty += 1
if bbox["rotation"] is not None:
rotation += 1
if bbox["class"] == "text" and bbox["text"] is None:
print(f"Missing Text in {file_name(sample)} -> {bbox['xmin']}, {bbox['ymin']}")
if bbox["text"] is not None:
if bbox["text"].strip() != bbox["text"]:
print(f"Removing leading of trailing spaces from: {bbox['text']}")
bbox["text"] = bbox["text"].strip()
if bbox["class"] != "text":
print(f"Text string outside Text BB in {file_name(sample)}: {bbox['class']}: {bbox['text']}")
text += 1
return total, ok, mapped, faulty, rotation, text
def consistency_circuit(db: list, classes: dict) -> None:
"""Checks whether the Amount of Annotation per Class is Consistent Among the Samples of a Circuits"""
print("BBox Inconsistency Report:")
sample_cls_bb_count = {(sample["circuit"], sample["drawing"], sample["picture"]):
{cls: len([bbox for bbox in sample["bboxes"] if bbox["class"] == cls])
for cls in classes} for sample in db}
for circuit in set(sample["circuit"] for sample in db):
circuit_samples = [sample for sample in sample_cls_bb_count if sample[0] == circuit]
for cls in classes:
check = [sample_cls_bb_count[sample][cls] for sample in circuit_samples]
if not all(c == check[0] for c in check):
print(f" Circuit {circuit}: {cls}: {check}")
def circuit_annotations(db: list, classes: dict) -> None:
"""Plots the Annotations per Sample and Class"""
fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(8, 6))
axes.plot([len(sample["bboxes"]) for sample in db], label="all")
for cls in classes:
axes.plot([len([annotation for annotation in sample["bboxes"]
if annotation["class"] == cls]) for sample in db], label=cls)
plt.minorticks_on()
axes.set_xticks(np.arange(0, len(db)+1, step=8))
axes.set_xticks(np.arange(0, len(db), step=8)+4, minor=True)
axes.grid(axis='x', linestyle='solid')
axes.grid(axis='x', linestyle='dotted', alpha=0.7, which="minor")
plt.title("Class Distribution in Samples")
plt.xlabel("Image Sample")
plt.ylabel("BB Annotation Count")
plt.yscale('log')
plt.legend(ncol=2, loc='center left', bbox_to_anchor=(1.0, 0.5))
plt.show()
def class_distribution(db: list, classes: dict) -> None:
"""Plots the Class Distribution over the Dataset"""
class_nbrs = np.arange(len(classes))
class_counts = [sum([len([bbox for bbox in sample["bboxes"] + sample["polygons"] + sample["points"]
if bbox["class"] == cls])
for sample in db]) for cls in classes]
bars = plt.bar(class_nbrs, class_counts)
plt.xticks(class_nbrs, labels=classes, rotation=90)
plt.yscale('log')
plt.title("Class Distribution")
plt.xlabel("Class")
plt.ylabel("BB Annotation Count")
for rect in bars:
height = rect.get_height()
plt.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, -3), textcoords="offset points", ha='center', va='top', rotation=90)
plt.show()
def class_sizes(db: list, classes: dict) -> None:
""""""
plt.title('BB Sizes')
plt.boxplot([[max(bbox["xmax"]-bbox["xmin"], bbox["ymax"]-bbox["ymin"])
for sample in db for bbox in sample["bboxes"] if bbox["class"] == cls]
for cls in classes])
class_nbrs = np.arange(len(classes))+1
plt.xticks(class_nbrs, labels=classes, rotation=90)
plt.show()
def image_count(drafter: int = None, segmentation: bool = False) -> int:
"""Counts the Raw Images or Segmentation Maps in the Dataset"""
return len([file_name for root, _, files in os.walk(".")
for file_name in files
if ("segmentation" if segmentation else "annotation") in root and
(not drafter or f"drafter_{drafter}{os.sep}" in root)])
def read_check_write(classes: dict, drafter: int = None, segmentation: bool = False):
"""Reads Annotations, Checks Consistency with Provided Classes
Writes Corrected Annotations Back and Returns the Annotations"""
db = read_dataset(drafter=drafter, segmentation=segmentation)
ann_total, ann_ok, ann_mapped, ann_faulty, ann_rot, ann_text = consistency(db, classes)
write_dataset(db, segmentation=segmentation)
print("")
print(" Class and File Consistency Report")
print(" -------------------------------------")
print(f"Annotation Type: {'Polygon' if segmentation else 'Bounding Box'}")
print(f"Class Label Count: {len(classes)}")
print(f"Raw Image Files: {image_count(drafter=drafter, segmentation=segmentation)}")
print(f"Processed Annotation Files: {len(db)}")
print(f"Total Annotation Count: {ann_total}")
print(f"Consistent Annotations: {ann_ok}")
print(f"Faulty Annotations (no recovery): {ann_faulty}")
print(f"Corrected Annotations by Mapping: {ann_mapped}")
print(f"Annotations with Rotation: {ann_rot}")
print(f"Annotations with Text: {ann_text}")
return db
def text_statistics(db: list, plot_unique_labels: bool = False):
"""Generates and Plots Statistics on Text Classes"""
print("")
print(" Text Statistics")
print("---------------------")
text_bbs = len([bbox for sample in db for bbox in sample["bboxes"] if bbox["class"] == "text"])
print(f"Text BB Annotations: {text_bbs}")
text_labels = [bbox["text"] for sample in db for bbox in sample["bboxes"] if bbox["text"] is not None]
print(f"Overall Text Label Count: {len(text_labels)}")
text_labels_unique = set(text_labels)
print(f"Unique Text Label Count: {len(text_labels_unique)}")
print(f"Total Character Count: {sum([len(text_label) for text_label in text_labels])}")
print("\nSet of all characters occurring in all text labels:")
char_set = set([char_set for label in text_labels_unique for char_set in label])
chars = sorted(list(char_set))
print(chars)
char_nbrs = np.arange(len(chars))
char_counts = [sum([len([None for text_char in text_label if text_char == char])
for text_label in text_labels])
for char in chars]
plt.bar(char_nbrs, char_counts)
plt.xticks(char_nbrs, chars)
plt.title("Character Frequencies")
plt.xlabel("Character")
plt.ylabel("Overall Count")
plt.show()
print("\nCharacter Frequencies:")
print({char: 1/char_count for char, char_count in zip(chars, char_counts)})
max_text_len = max([len(text_label) for text_label in text_labels])
text_lengths = np.arange(max_text_len)+1
text_count_by_length = [len([None for text_label in text_labels if len(text_label) == text_length])
for text_length in text_lengths]
plt.bar(text_lengths, text_count_by_length)
plt.xticks(text_lengths, rotation=90)
plt.title("Text Length Distribution")
plt.xlabel("Character Count")
plt.ylabel("Annotation Count")
plt.show()
text_instances = text_labels_unique if plot_unique_labels else text_labels
text_classes_names = []
text_classes_instances = []
for text_class in load_properties():
text_classes_names.append(text_class["name"])
text_classes_instances.append([text_instance for text_instance in text_instances
if re.match(text_class["regex"], text_instance)])
text_classified = [text for text_class_instances in text_classes_instances for text in text_class_instances]
text_classes_names.append("Unclassified")
text_classes_instances.append([text_instance for text_instance in text_instances
if text_instance not in text_classified])
for text_class_name, text_class_instances in zip(text_classes_names, text_classes_instances):
print(f"\n{text_class_name}:")
print(sorted(list(set(text_class_instances))))
plt.bar(text_classes_names, [len(text_class_instances) for text_class_instances in text_classes_instances])
plt.title('Count of matching pattern')
plt.xlabel('Regex')
plt.ylabel('No. of text matched')
plt.xticks(rotation=90)
plt.tight_layout()
plt.show()
if __name__ == "__main__":
drafter_selected = int(sys.argv[1]) if len(sys.argv) == 2 else None
classes = load_classes()
#db_poly = read_check_write(classes, drafter_selected, segmentation=True)
db_bb = read_check_write(classes, drafter_selected)
class_sizes(db_bb, classes)
circuit_annotations(db_bb, classes)
class_distribution(db_bb, classes)
#class_distribution(db_poly, classes)
consistency_circuit(db_bb, classes)
text_statistics(db_bb)
|