Skip to content

Commit

Permalink
Merge pull request #53 from ch-sa/ch-sa/logging
Browse files Browse the repository at this point in the history
Add logging
  • Loading branch information
ch-sa authored Jan 22, 2022
2 parents 3693407 + f99d224 commit 0be71e4
Show file tree
Hide file tree
Showing 25 changed files with 204 additions and 83 deletions.
2 changes: 1 addition & 1 deletion labelCloud/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.6.10"
__version__ = "0.7.0"
7 changes: 4 additions & 3 deletions labelCloud/__main__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import argparse
import logging

from labelCloud import __version__

Expand Down Expand Up @@ -32,7 +33,7 @@ def setup_example_project() -> None:

from labelCloud.control.config_manager import config

print(
logging.info(
"Starting labelCloud in example mode.\n"
"Setting up project with example point cloud ,label and default config."
)
Expand Down Expand Up @@ -61,7 +62,7 @@ def setup_example_project() -> None:
),
str(label_folder.joinpath("exemplary.json")),
)
print(
logging.info(
f"Setup example project in {cwdir}:"
"\n - config.ini"
"\n - pointclouds/exemplary.ply"
Expand Down Expand Up @@ -95,7 +96,7 @@ def start_gui():
height = (desktop.height() - view.height()) / 2
view.move(width, height)

print("Showing GUI...")
logging.info("Showing GUI...")
sys.exit(app.exec_())


Expand Down
7 changes: 4 additions & 3 deletions labelCloud/control/alignmode.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
three points on the plane that serves as the ground. Then the old point cloud will be
saved up and the aligned current will overwrite the old.
"""
import logging
from typing import TYPE_CHECKING, Union

import numpy as np
Expand Down Expand Up @@ -50,7 +51,7 @@ def change_activation(self, force=None) -> None:
self.view.activate_draw_modes(
not self.is_active
) # Prevent bbox drawing while aligning
print(f"Alignmode was changed to {self.is_active}!")
logging.info(f"Alignmode was changed to {self.is_active}!")

def reset(self, points_only: bool = False) -> None:
self.plane1, self.plane2, self.plane3 = (None, None, None)
Expand All @@ -70,7 +71,7 @@ def register_point(self, new_point) -> None:
self.plane3 = new_point
self.calculate_angles()
else:
print("Cannot register point.")
logging.warning("Cannot register point.")

def register_tmp_point(self, new_tmp_point) -> None:
if self.plane1 and (not self.plane2):
Expand Down Expand Up @@ -121,7 +122,7 @@ def calculate_angles(self) -> None:
rotation_axis = np.cross(pn_normalized, z_axis) / np.linalg.norm(
np.cross(pn_normalized, z_axis)
)
print(
logging.info(
f"Alignment rotation: {round(rotation_angle, 2)} "
f"around {np.round(rotation_axis, 2)}"
)
Expand Down
9 changes: 6 additions & 3 deletions labelCloud/control/bbox_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
Bounding Box Management: adding, selecting updating, deleting bboxes;
Possible Active Bounding Box Manipulations: rotation, translation, scaling
"""
import logging
from typing import TYPE_CHECKING, List, Optional

import numpy as np
Expand All @@ -26,7 +27,7 @@ def wrapper(*args, **kwargs):
if args[0].has_active_bbox():
return func(*args, **kwargs)
else:
print("There is currently no active bounding box to manipulate.")
logging.warning("There is currently no active bounding box to manipulate.")

return wrapper

Expand All @@ -40,7 +41,9 @@ def wrapper(*args, **kwargs):
if not config.getboolean("USER_INTERFACE", "z_rotation_only"):
return func(*args, **kwargs)
else:
print("Rotations around the x- or y-axis are not supported in this mode.")
logging.warning(
"Rotations around the x- or y-axis are not supported in this mode."
)

return wrapper

Expand Down Expand Up @@ -282,7 +285,7 @@ def select_bbox_by_ray(self, x: int, y: int) -> None:
)
if intersected_bbox_id is not None:
self.set_active_bbox(intersected_bbox_id)
print("Selected bounding box %s." % intersected_bbox_id)
logging.info("Selected bounding box %s." % intersected_bbox_id)

# HELPER

Expand Down
7 changes: 4 additions & 3 deletions labelCloud/control/controller.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
from typing import Union

from PyQt5 import QtCore, QtGui
Expand Down Expand Up @@ -219,7 +220,7 @@ def key_press_event(self, a0: QtGui.QKeyEvent) -> None:
# Reset point cloud pose to intial rotation and translation
elif (a0.key() == QtCore.Qt.Key_R) or (a0.key() == QtCore.Qt.Key_Home):
self.pcd_manager.reset_transformations()
print("Reseted position to default.")
logging.info("Reseted position to default.")

elif a0.key() == QtCore.Qt.Key_Delete: # Delete active bbox
self.bbox_controller.delete_current_bbox()
Expand All @@ -231,10 +232,10 @@ def key_press_event(self, a0: QtGui.QKeyEvent) -> None:
elif a0.key() == QtCore.Qt.Key_Escape:
if self.drawing_mode.is_active():
self.drawing_mode.reset()
print("Resetted drawn points!")
logging.info("Resetted drawn points!")
elif self.align_mode.is_active:
self.align_mode.reset()
print("Resetted selected points!")
logging.info("Resetted selected points!")

# BBOX MANIPULATION
elif (a0.key() == QtCore.Qt.Key_Y) or (a0.key() == QtCore.Qt.Key_Comma):
Expand Down
5 changes: 3 additions & 2 deletions labelCloud/control/drawing_manager.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
from typing import TYPE_CHECKING, Union

from ..labeling_strategies import BaseLabelingStrategy
Expand Down Expand Up @@ -27,11 +28,11 @@ def has_preview(self) -> bool:
def set_drawing_strategy(self, strategy: BaseLabelingStrategy) -> None:
if self.is_active() and self.drawing_strategy == strategy:
self.reset()
print("Deactivated drawing!")
logging.info("Deactivated drawing!")
else:
if self.is_active():
self.reset()
print("Resetted previous active drawing mode!")
logging.info("Resetted previous active drawing mode!")

self.drawing_strategy = strategy

Expand Down
13 changes: 8 additions & 5 deletions labelCloud/control/label_manager.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
from pathlib import Path
from typing import List

Expand Down Expand Up @@ -25,7 +26,7 @@ def get_label_strategy(export_format: str, label_folder: Path) -> "BaseLabelForm
transformed=False,
)
elif export_format != "centroid_abs":
print(
logging.warning(
f"Unknown export strategy '{export_format}'. Proceeding with default (centroid_abs)!"
)
return CentroidFormat(
Expand Down Expand Up @@ -58,14 +59,16 @@ def import_labels(self, pcd_path: Path) -> List[BBox]:
try:
return self.label_strategy.import_labels(pcd_path)
except KeyError as key_error:
print("Found a key error with %s in the dictionary." % key_error)
print(
logging.warning("Found a key error with %s in the dictionary." % key_error)
logging.warning(
"Could not import labels, please check the consistency of the label format."
)
return []
except AttributeError as attribute_error:
print("Attribute Error: %s. Expected a dictionary." % attribute_error)
print(
logging.warning(
"Attribute Error: %s. Expected a dictionary." % attribute_error
)
logging.warning(
"Could not import labels, please check the consistency of the label format."
)
return []
Expand Down
38 changes: 22 additions & 16 deletions labelCloud/control/pcd_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
Module to manage the point clouds (loading, navigation, floor alignment).
Sets the point cloud and original point cloud path. Initiate the writing to the virtual object buffer.
"""
import logging
from dataclasses import dataclass
from pathlib import Path
from shutil import copyfile
Expand All @@ -11,6 +12,7 @@
import open3d as o3d

from ..model import BBox, PointCloud
from ..utils.logger import end_section, green, print_column, start_section
from .config_manager import config
from .label_manager import LabelManager

Expand Down Expand Up @@ -77,7 +79,9 @@ def read_pointcloud_folder(self) -> None:
if file.suffix in PointCloudManger.PCD_EXTENSIONS:
self.pcds.append(file)
else:
print(f"Point cloud path {self.pcd_folder} is not a valid directory.")
logging.warning(
f"Point cloud path {self.pcd_folder} is not a valid directory."
)

if self.pcds:
self.view.update_status(
Expand Down Expand Up @@ -106,16 +110,16 @@ def pcds_left(self) -> bool:
return self.current_id + 1 < len(self.pcds)

def get_next_pcd(self) -> None:
print("Loading next point cloud...")
logging.info("Loading next point cloud...")
if self.pcds_left():
self.current_id += 1
self.pointcloud = self.load_pointcloud(self.pcd_path)
self.update_pcd_infos()
else:
print("No point clouds left!")
logging.warning("No point clouds left!")

def get_prev_pcd(self) -> None:
print("Loading previous point cloud...")
logging.info("Loading previous point cloud...")
if self.current_id > 0:
self.current_id -= 1
self.pointcloud = self.load_pointcloud(self.pcd_path)
Expand All @@ -125,7 +129,7 @@ def get_prev_pcd(self) -> None:

def get_labels_from_file(self) -> List[BBox]:
bboxes = self.label_manager.import_labels(self.pcd_path)
print("Loaded %s bboxes!" % len(bboxes))
logging.info(green("Loaded %s bboxes!" % len(bboxes)))
return bboxes

# SETTER
Expand All @@ -142,22 +146,22 @@ def save_labels_into_file(self, bboxes: List[BBox]) -> None:
self.view.update_label_completer(self.collected_object_classes)
self.view.update_default_object_class_menu(self.collected_object_classes)
else:
print("No point clouds to save labels for!")
logging.warning("No point clouds to save labels for!")

def save_current_perspective(self, active: bool = True) -> None:
if active and self.pointcloud:
self.saved_perspective = Perspective(
zoom=self.pointcloud.trans_z,
rotation=tuple(self.pointcloud.get_rotations()),
)
print(f"Saved current perspective ({self.saved_perspective}).")
logging.info(f"Saved current perspective ({self.saved_perspective}).")
else:
self.saved_perspective = None
print("Reset saved perspective.")
logging.info("Reset saved perspective.")

# MANIPULATOR
def load_pointcloud(self, path_to_pointcloud: Path) -> PointCloud:
print("=" * 20, "Loading", path_to_pointcloud.name, "=" * 20)
def load_pointcloud(self, path_to_pointcloud: str) -> PointCloud:
start_section(f"Loading {path_to_pointcloud.name}")

if config.getboolean("USER_INTERFACE", "keep_perspective"):
self.save_current_perspective()
Expand All @@ -181,13 +185,13 @@ def load_pointcloud(self, path_to_pointcloud: Path) -> PointCloud:

tmp_pcd.colorless = len(tmp_pcd.colors) == 0

print("Number of Points: %s" % len(tmp_pcd.points))
print_column(["Number of Points:", f"{len(tmp_pcd.points):n}"])
# Calculate and set initial translation to view full pointcloud
tmp_pcd.center = self.current_o3d_pcd.get_center()
tmp_pcd.set_mins_maxs()

if PointCloudManger.COLORIZE and tmp_pcd.colorless:
print("Generating colors for colorless point cloud!")
logging.info("Generating colors for colorless point cloud!")
min_height, max_height = tmp_pcd.get_min_max_height()
tmp_pcd.colors = color_pointcloud(tmp_pcd.points, min_height, max_height)
tmp_pcd.colorless = False
Expand All @@ -211,12 +215,14 @@ def load_pointcloud(self, path_to_pointcloud: Path) -> PointCloud:
if self.pointcloud is not None: # Skip first pcd to intialize OpenGL first
tmp_pcd.write_vbo()

print("Successfully loaded point cloud from %s!" % path_to_pointcloud)
logging.info(
green(f"Successfully loaded point cloud from {path_to_pointcloud}!")
)
if tmp_pcd.colorless:
print(
logging.warning(
"Did not find colors for the loaded point cloud, drawing in colorless mode!"
)
print("=" * 65)
end_section()
return tmp_pcd

def rotate_around_x(self, dangle) -> None:
Expand Down Expand Up @@ -280,7 +286,7 @@ def rotate_pointcloud(
pcd_maxs = np.amax(self.current_o3d_pcd.points, axis=0)

if abs(pcd_mins[2]) > pcd_maxs[2]:
print("Point cloud is upside down, rotating ...")
logging.warning("Point cloud is upside down, rotating ...")
self.current_o3d_pcd.rotate(
o3d.geometry.get_rotation_matrix_from_xyz([np.pi, 0, 0]),
center=(0, 0, 0),
Expand Down
15 changes: 9 additions & 6 deletions labelCloud/label_formats/base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import json
from abc import ABC, abstractmethod
import logging
from pathlib import Path
from typing import List, Optional, Union

Expand All @@ -15,22 +16,24 @@ def __init__(
self, label_folder: Path, export_precision: int, relative_rotation: bool = False
) -> None:
self.label_folder = label_folder
print("Set export strategy to %s." % self.__class__.__name__)
logging.info("Set export strategy to %s." % self.__class__.__name__)
self.export_precision = export_precision
self.relative_rotation = relative_rotation
self.file_ending = ".json"
if relative_rotation:
print(
logging.info(
"Saving rotations relatively to positve x-axis in radians (-pi..+pi)."
)
elif self.__class__.__name__ == "VerticesFormat":
print("Saving rotations implicitly in the vertices coordinates.")
logging.info("Saving rotations implicitly in the vertices coordinates.")
else:
print("Saving rotations absolutely to positve x-axis in degrees (0..360°).")
logging.info(
"Saving rotations absolutely to positve x-axis in degrees (0..360°)."
)

def update_label_folder(self, new_label_folder: Path) -> None:
self.label_folder = new_label_folder
print(f"Updated label folder to {new_label_folder}.")
logging.info(f"Updated label folder to {new_label_folder}.")

def round_dec(self, x, decimal_places: Optional[int] = None) -> List[float]:
if not decimal_places:
Expand All @@ -41,7 +44,7 @@ def save_label_to_file(self, pcd_path: Path, data: Union[dict, str]) -> Path:
label_path = self.label_folder.joinpath(pcd_path.stem + self.FILE_ENDING)

if label_path.is_file():
print("File %s already exists, replacing file ..." % label_path)
logging.info("File %s already exists, replacing file ..." % label_path)
if label_path.suffix == ".json":
with open(label_path, "w") as write_file:
json.dump(data, write_file, indent="\t")
Expand Down
7 changes: 5 additions & 2 deletions labelCloud/label_formats/centroid_format.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
import logging
from pathlib import Path
from typing import List

Expand All @@ -25,7 +26,9 @@ def import_labels(self, pcd_path: Path) -> List[BBox]:
bbox.set_rotations(*rotations)
bbox.set_classname(label["name"])
labels.append(bbox)
print("Imported %s labels from %s." % (len(data["objects"]), label_path))
logging.info(
"Imported %s labels from %s." % (len(data["objects"]), label_path)
)
return labels

def export_labels(self, bboxes: List[BBox], pcd_path: Path) -> None:
Expand Down Expand Up @@ -62,7 +65,7 @@ def export_labels(self, bboxes: List[BBox], pcd_path: Path) -> None:

# Save to JSON
label_path = self.save_label_to_file(pcd_path, data)
print(
logging.info(
f"Exported {len(bboxes)} labels to {label_path} "
f"in {self.__class__.__name__} formatting!"
)
Loading

0 comments on commit 0be71e4

Please sign in to comment.