Skip to content

Commit

Permalink
Clean comments, strings, imports
Browse files Browse the repository at this point in the history
  • Loading branch information
ch-sa committed Jun 27, 2021
1 parent e520aa5 commit 438bf8e
Show file tree
Hide file tree
Showing 10 changed files with 104 additions and 99 deletions.
13 changes: 8 additions & 5 deletions labelCloud/control/alignmode.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
"""A module for aligning point clouds with the floor. The user has to span a triangle with 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."""
"""
A module for aligning point clouds with the floor. The user has to span a triangle with
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.
"""
from typing import Union, TYPE_CHECKING

import numpy as np

import utils.oglhelper as ogl
from control.pcd_manager import PointCloudManger
from .pcd_manager import PointCloudManger

if TYPE_CHECKING:
from view.gui import GUI
Expand Down Expand Up @@ -123,8 +126,8 @@ def calculate_angles(self):
np.cross(pn_normalized, z_axis)
)
print(
"Alignment rotation: %s around %s"
% (round(rotation_angle, 2), np.round(rotation_axis, 2))
f"Alignment rotation: {round(rotation_angle, 2)} "
f"around {np.round(rotation_axis, 2)}"
)

# Initiate point cloud rotation
Expand Down
48 changes: 32 additions & 16 deletions labelCloud/control/bbox_controller.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,29 @@
"""
A class to handle all user manipulations of the bounding boxes and collect all labeling settings in one place.
Bounding Box Management: adding, updating, deleting bboxes; changing the active bounding box
A class to handle all user manipulations of the bounding boxes and collect all labeling
settings in one place.
Bounding Box Management: adding, selecting updating, deleting bboxes;
Possible Active Bounding Box Manipulations: rotation, translation, scaling
"""
from typing import TYPE_CHECKING, Union, List

import numpy as np


from utils import oglhelper
from control.config_manager import config
from model.bbox import BBox
from .config_manager import config

if TYPE_CHECKING:
from view.gui import GUI


# DECORATORS
def has_active_bbox_decorator(func):
def wrapper(*args, **kwargs): # plays function if active bbox exists
"""
Only execute bounding box manipulation if there is an active bounding box.
"""

def wrapper(*args, **kwargs):
if args[0].has_active_bbox():
return func(*args, **kwargs)
else:
Expand All @@ -27,7 +33,11 @@ def wrapper(*args, **kwargs): # plays function if active bbox exists


def only_zrotation_decorator(func):
def wrapper(*args, **kwargs): # plays function if active bbox exists
"""
Only execute x- and y-rotation if z_rotation_only mode is not activated.
"""

def wrapper(*args, **kwargs):
if not config.getboolean("USER_INTERFACE", "z_rotation_only"):
return func(*args, **kwargs)
else:
Expand Down Expand Up @@ -209,9 +219,6 @@ def rotate_with_mouse(
bbox_cosz = round(np.cos(np.deg2rad(total_z_rotation)), 0)
bbox_sinz = -round(np.sin(np.deg2rad(total_z_rotation)), 0)

# self.rotate_around_x(y_angle * bbox_cosz + x_angle * bbox_sinz)
# self.rotate_around_y(y_angle * bbox_sinz + x_angle * bbox_cosz)

self.rotate_around_x(y_angle * bbox_cosz)
self.rotate_around_y(y_angle * bbox_sinz)
self.rotate_around_z(x_angle)
Expand Down Expand Up @@ -251,9 +258,14 @@ def translate_along_z(self, distance: float = None, down: bool = False):
self.get_active_bbox().center[2] + distance
)

# Scale bbox while keeping ratios
@has_active_bbox_decorator
def scale(self, length_increase: float = None, decrease: bool = False):
def scale(self, length_increase: float = None, decrease: bool = False) -> None:
"""Scales a bounding box while keeping the previous aspect ratio.
:param length_increase: factor by which the length should be increased
:param decrease: if True, reverses the length_increasee (* -1)
:return: None
"""
length_increase = length_increase or config.getfloat("LABEL", "std_scaling")
if decrease:
length_increase *= -1
Expand All @@ -267,7 +279,7 @@ def scale(self, length_increase: float = None, decrease: bool = False):

self.get_active_bbox().set_dimensions(new_length, new_width, new_height)

def select_bbox_by_ray(self, x: int, y: int):
def select_bbox_by_ray(self, x: int, y: int) -> None:
intersected_bbox_id = oglhelper.get_intersected_bboxes(
x,
y,
Expand All @@ -281,26 +293,30 @@ def select_bbox_by_ray(self, x: int, y: int):

# HELPER

def update_all(self):
def update_all(self) -> None:
self.update_z_dial()
self.update_curr_class()
self.update_label_list()
self.view.update_bbox_stats(self.get_active_bbox())

@has_active_bbox_decorator
def update_z_dial(self):
def update_z_dial(self) -> None:
self.view.dial_zrotation.blockSignals(True) # To brake signal loop
self.view.dial_zrotation.setValue(int(self.get_active_bbox().get_z_rotation()))
self.view.dial_zrotation.blockSignals(False)

def update_curr_class(self):
def update_curr_class(self) -> None:
if self.has_active_bbox():
self.view.update_curr_class_edit()
else:
self.view.update_curr_class_edit(force="")

# Updating the list of existing labels if bboxes changed
def update_label_list(self):
def update_label_list(self) -> None:
"""Updates the list of drawn labels and highlights the active label.
Should be always called if the bounding boxes changed.
:return: None
"""
self.view.label_list.blockSignals(True) # To brake signal loop
self.view.label_list.clear()
for bbox in self.bboxes:
Expand Down
9 changes: 7 additions & 2 deletions labelCloud/control/config_manager.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
"""Load configuration from .ini file."""
import configparser

# Read local file `config.ini`.

import os
from typing import List, Union, Optional
from typing import List


class ExtendedConfigParser(configparser.ConfigParser):
"""Extends the ConfigParser with the ability to read and parse lists.
Can automatically parse float values besides plain strings.
"""

def getlist(self, section, option, raw=False, vars=None, fallback=None) -> List:
raw_value = self.get(section, option, raw=raw, vars=vars, fallback=fallback)
if "," in raw_value:
Expand Down
75 changes: 34 additions & 41 deletions labelCloud/control/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,19 @@

from PyQt5 import QtGui, QtCore

from control.alignmode import AlignMode
from control.drawing_manager import DrawingManager
from control.pcd_manager import PointCloudManger
from model.bbox import BBox
from control.bbox_controller import BoundingBoxController

from view.gui import GUI
from utils import oglhelper
from model.bbox import BBox
from view.gui import GUI
from .alignmode import AlignMode
from .bbox_controller import BoundingBoxController
from .drawing_manager import DrawingManager
from .pcd_manager import PointCloudManger


class Controller:
MOVEMENT_THRESHOLD = 0.1

def __init__(self):
"""Initializes all controllers and managers."""
self.view: Union["GUI", None] = None
Expand Down Expand Up @@ -172,12 +174,8 @@ def mouse_move_event(self, a0: QtGui.QMouseEvent):
and (not self.align_mode.is_active())
):
if a0.buttons() & QtCore.Qt.LeftButton: # bbox rotation
# self.bbox_controller.rotate_around_x(-dy)
# self.bbox_controller.rotate_around_y(-dx)
self.bbox_controller.rotate_with_mouse(-dx, -dy)
elif a0.buttons() & QtCore.Qt.RightButton: # bbox translation
# self.bbox_controller.translate_along_x(-dx / 30)
# self.bbox_controller.translate_along_y(dy / 30)
new_center = self.view.glWidget.get_world_coords(
a0.x(), a0.y(), correction=True
)
Expand All @@ -190,9 +188,8 @@ def mouse_move_event(self, a0: QtGui.QMouseEvent):
self.pcd_manager.translate_along_x(dx)
self.pcd_manager.translate_along_y(dy)

if (
dx > 0.1 or dy > 0.1
): # Reset scroll locks if significant cursor movements
# Reset scroll locks of "side scrolling" for significant cursor movements
if dx > Controller.MOVEMENT_THRESHOLD or dy > Controller.MOVEMENT_THRESHOLD:
if self.side_mode:
self.side_mode = False
else:
Expand Down Expand Up @@ -243,45 +240,41 @@ def key_press_event(self, a0: QtGui.QKeyEvent):
print("Resetted selected points!")

# BBOX MANIPULATION
elif (a0.key() == QtCore.Qt.Key_Y) or (
a0.key() == QtCore.Qt.Key_Comma
): # z rotate counterclockwise
elif (a0.key() == QtCore.Qt.Key_Y) or (a0.key() == QtCore.Qt.Key_Comma):
# z rotate counterclockwise
self.bbox_controller.rotate_around_z()
elif (a0.key() == QtCore.Qt.Key_X) or (
a0.key() == QtCore.Qt.Key_Period
): # z rotate clockwise
elif (a0.key() == QtCore.Qt.Key_X) or (a0.key() == QtCore.Qt.Key_Period):
# z rotate clockwise
self.bbox_controller.rotate_around_z(clockwise=True)
elif a0.key() == QtCore.Qt.Key_C: # y rotate counterclockwise
elif a0.key() == QtCore.Qt.Key_C:
# y rotate counterclockwise
self.bbox_controller.rotate_around_y()
elif a0.key() == QtCore.Qt.Key_V: # y rotate clockwise
elif a0.key() == QtCore.Qt.Key_V:
# y rotate clockwise
self.bbox_controller.rotate_around_y(clockwise=True)
elif a0.key() == QtCore.Qt.Key_B: # x rotate counterclockwise
elif a0.key() == QtCore.Qt.Key_B:
# x rotate counterclockwise
self.bbox_controller.rotate_around_x()
elif a0.key() == QtCore.Qt.Key_N: # x rotate clockwise
elif a0.key() == QtCore.Qt.Key_N:
# x rotate clockwise
self.bbox_controller.rotate_around_x(clockwise=True)
elif (a0.key() == QtCore.Qt.Key_W) or (
a0.key() == QtCore.Qt.Key_Up
): # move backward
elif (a0.key() == QtCore.Qt.Key_W) or (a0.key() == QtCore.Qt.Key_Up):
# move backward
self.bbox_controller.translate_along_y()
elif (a0.key() == QtCore.Qt.Key_S) or (
a0.key() == QtCore.Qt.Key_Down
): # move forward
elif (a0.key() == QtCore.Qt.Key_S) or (a0.key() == QtCore.Qt.Key_Down):
# move forward
self.bbox_controller.translate_along_y(forward=True)
elif (a0.key() == QtCore.Qt.Key_A) or (
a0.key() == QtCore.Qt.Key_Left
): # move left
elif (a0.key() == QtCore.Qt.Key_A) or (a0.key() == QtCore.Qt.Key_Left):
# move left
self.bbox_controller.translate_along_x(left=True)
elif (a0.key() == QtCore.Qt.Key_D) or (
a0.key() == QtCore.Qt.Key_Right
): # move right
elif (a0.key() == QtCore.Qt.Key_D) or (a0.key() == QtCore.Qt.Key_Right):
# move right
self.bbox_controller.translate_along_x()
elif (a0.key() == QtCore.Qt.Key_Q) or (
a0.key() == QtCore.Qt.Key_PageUp
): # move up
elif (a0.key() == QtCore.Qt.Key_Q) or (a0.key() == QtCore.Qt.Key_PageUp):
# move up
self.bbox_controller.translate_along_z()
elif (a0.key() == QtCore.Qt.Key_E) or (
a0.key() == QtCore.Qt.Key_PageDown
): # move down
elif (a0.key() == QtCore.Qt.Key_E) or (a0.key() == QtCore.Qt.Key_PageDown):
# move down
self.bbox_controller.translate_along_z(down=True)

def key_release_event(self, a0: QtGui.QKeyEvent):
Expand Down
4 changes: 2 additions & 2 deletions labelCloud/control/drawing_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@

import utils.math3d as math3d
import utils.oglhelper as ogl
from control.bbox_controller import BoundingBoxController
from control.config_manager import config
from model.bbox import BBox
from .bbox_controller import BoundingBoxController
from .config_manager import config

if TYPE_CHECKING:
from view.gui import GUI
Expand Down
10 changes: 4 additions & 6 deletions labelCloud/control/label_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@

import numpy as np

from utils import math3d
from control.config_manager import config
from model.bbox import BBox
from utils import math3d
from .config_manager import config


def get_label_strategy(export_format: str, label_folder: str) -> "IFormattingInterface":
Expand All @@ -31,11 +31,9 @@ class LabelManager:
"centroid_rel",
"centroid_abs",
"kitti",
] # supported export formats
]
STD_LABEL_FORMAT = config.get("LABEL", "label_format")
EXPORT_PRECISION = config.getint(
"LABEL", "export_precision"
) # Number of decimal places
EXPORT_PRECISION = config.getint("LABEL", "export_precision")

def __init__(
self, strategy: str = STD_LABEL_FORMAT, path_to_label_folder: str = None
Expand Down
16 changes: 3 additions & 13 deletions labelCloud/control/pcd_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,16 @@
"""
import ntpath
import os
from shutil import copyfile
from typing import List, Tuple, TYPE_CHECKING, Optional

import numpy as np
import open3d as o3d
from shutil import copyfile

from control.config_manager import config
from control.label_manager import LabelManager
from model.bbox import BBox
from model.point_cloud import PointCloud
from .config_manager import config
from .label_manager import LabelManager

if TYPE_CHECKING:
from view.gui import GUI
Expand Down Expand Up @@ -247,8 +247,6 @@ def rotate_pointcloud(
self.get_current_path(),
os.path.join(originals_path, self.get_current_name()),
)
# o3d.io.write_point_cloud(os.path.join(originals_path, self.get_current_name()), self.current_o3d_pcd)

# Rotate and translate point cloud
rotation_matrix = o3d.geometry.get_rotation_matrix_from_axis_angle(
np.multiply(axis, angle)
Expand All @@ -267,12 +265,6 @@ def rotate_pointcloud(
center=(0, 0, 0),
)

# Overwrite current point cloud and reload
# if os.path.splitext(self.get_current_path())[1] == ".bin":
# points = np.asarray(self.current_o3d_pcd.points)
# flattened_points = np.append(points, np.zeros((len(points), 1)), axis=1).flatten() # add dummy reflection
# flattened_points.tofile(self.get_current_path())
# else:
save_path = self.get_current_path()
if os.path.splitext(save_path)[1] == ".bin":
save_path = save_path[:-4] + ".pcd"
Expand All @@ -284,9 +276,7 @@ def rotate_pointcloud(

def get_perspective(self):
x_rotation = self.pointcloud.rot_x
# y_rotation = self.pcdc.get_pointcloud().rot_y
z_rotation = self.pointcloud.rot_z
# print("PCD-ROTX/y/z: %s, %s, %s" % (x_rotation, y_rotation, z_rotation))

cosz = round(np.cos(np.deg2rad(z_rotation)), 1)
sinz = -round(np.sin(np.deg2rad(z_rotation)), 1)
Expand Down
Loading

0 comments on commit 438bf8e

Please sign in to comment.