cghd / consistency.py
lowercaseonly's picture
Added Loading/Statistics/Preprocessing Scripts and Class Info Files
62030e0
raw history blame
No virus
10.4 kB
"""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)