Skip to content

Commit

Permalink
ci(pre-commit): autofix
Browse files Browse the repository at this point in the history
  • Loading branch information
pre-commit-ci[bot] committed Jan 10, 2025
1 parent c1e02c5 commit 1760894
Show file tree
Hide file tree
Showing 6 changed files with 59 additions and 28 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,6 @@ def detect(self, img: np.array, stamp):

def single_shot_calibration_error(self, object_points, image_points) -> Tuple[float, float]:
raise NotImplementedError

def restart_lost_frames_counter(self):
raise NotImplementedError
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,14 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import logging

import cv2
from intrinsic_camera_calibrator.board_detections.chess_board_detection import ChessBoardDetection
from intrinsic_camera_calibrator.board_detectors.board_detector import BoardDetector
from intrinsic_camera_calibrator.parameter import Parameter
from intrinsic_camera_calibrator.utils import to_grayscale
import numpy as np
import logging


class ChessBoardDetector(BoardDetector):
Expand All @@ -38,7 +39,7 @@ def __init__(self, **kwargs):
self.roi = None
self.lost_frames = 0
self.max_lost_frames = 3

def restart_lost_frames_counter(self):
self.lost_frames = self.max_lost_frames

Expand All @@ -61,7 +62,7 @@ def detect(self, img: np.array, stamp: float):
resized_detection = self.resized_detection.value
resized_max_resolution = self.resized_max_resolution.value

def get_roi(corners, frame_shape, padding = 120):
def get_roi(corners, frame_shape, padding=120):
"""Region to keep track of the chessboard in the next frame"""
x_min, y_min = np.min(corners, axis=0).ravel().astype(int) - padding
x_max, y_max = np.max(corners, axis=0).ravel().astype(int) + padding
Expand All @@ -73,7 +74,9 @@ def get_roi(corners, frame_shape, padding = 120):
grayscale = to_grayscale(img)
if not resized_detection or max(h, w) <= resized_max_resolution:
if self.roi is None or self.lost_frames >= self.max_lost_frames:
(detected, corners) = cv2.findChessboardCorners(grayscale, (cols, rows), flags=flags)
(detected, corners) = cv2.findChessboardCorners(
grayscale, (cols, rows), flags=flags
)
# if chessboard was found, keep track of the region to try to detect easily in the next frame
if detected:
self.roi = get_roi(corners, img.shape[:2])
Expand All @@ -83,8 +86,10 @@ def get_roi(corners, frame_shape, padding = 120):
self.detection_results_signal.emit(img, None, stamp)
return
else:
roi_frame = grayscale[self.roi[1]:self.roi[3], self.roi[0]:self.roi[2]]
(detected, corners) = cv2.findChessboardCorners(roi_frame, (cols, rows), flags=flags)
roi_frame = grayscale[self.roi[1] : self.roi[3], self.roi[0] : self.roi[2]]
(detected, corners) = cv2.findChessboardCorners(
roi_frame, (cols, rows), flags=flags
)
if detected:
corners += (self.roi[0], self.roi[1])
self.roi = get_roi(corners, img.shape[:2])
Expand Down Expand Up @@ -144,7 +149,9 @@ def get_roi(corners, frame_shape, padding = 120):
)
np.fill_diagonal(dist_matrix, np.inf)
min_distance = dist_matrix.min()
radius = max(1, int(np.ceil(min_distance * 0.5))) # ensuring radius has a value of at least 1
radius = max(
1, int(np.ceil(min_distance * 0.5))
) # ensuring radius has a value of at least 1

criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -928,7 +928,7 @@ def on_save_clicked(self):
self.undistortion_alpha_spinbox.value(),
self.data_source.get_camera_name(),
os.path.join(output_folder, f"{self.data_source.get_camera_name()}_info.yaml"),
self.rectify_type_combobox.currentData()
self.rectify_type_combobox.currentData(),
)

self.save_parameters(os.path.join(output_folder, "parameters.yaml"))
Expand Down Expand Up @@ -1012,7 +1012,7 @@ def process_detection_results(self, img: np.array, detection: BoardDetection, im
alpha_indicators=self.indicators_alpha_spinbox.value(),
value=False,
)
self.skip_next_img = 5 # skips the next images if there are no detections
self.skip_next_img = 5 # skips the next images if there are no detections

else:
camera_model_cfg, camera_model_type = self.calibrator_dict[
Expand Down Expand Up @@ -1259,8 +1259,9 @@ def process_data(self):
elif self.image_view_type_combobox.currentData() == ImageViewMode.SOURCE_RECTIFIED:
assert self.calibrated_camera_model is not None
img = self.calibrated_camera_model.rectify(
self.unprocessed_image, self.undistortion_alpha_spinbox.value(),
self.rectify_type_combobox.currentData()
self.unprocessed_image,
self.undistortion_alpha_spinbox.value(),
self.rectify_type_combobox.currentData(),
)
else:
raise NotImplementedError
Expand All @@ -1286,14 +1287,18 @@ def process_db_data(self, img):
def process_new_data(self):
"""Attempt to request the detector to process an image. However, if it there is an image being processed, does not enqueue them indefinitely. Instead, only leave the last one."""
# if was not found the pattern skip some frames
if self.data_collector.skip_frames_when_not_detection.value and self.skip_next_img > 1 and self.data_source_type != DataSourceEnum.FILES:
self.detector.restart_lost_frames_counter() # to force next frame detection
if (
self.data_collector.skip_frames_when_not_detection.value
and self.skip_next_img > 1
and self.data_source_type != DataSourceEnum.FILES
):
self.detector.restart_lost_frames_counter() # to force next frame detection
self.skip_next_img -= 1
self.consumed_data_signal.emit()
return

if self.data_source_type == DataSourceEnum.FILES:
self.detector.restart_lost_frames_counter() # to force next frame detection
self.detector.restart_lost_frames_counter() # to force next frame detection

if self.paused:
return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,8 @@ def get_reprojection_errors(
projected_points = projected_points.reshape((num_points, 2))
return projected_points - image_points

def as_dict(self, alpha: float = 0.0, rectify_option = 0) -> Dict:
undistorted = self.get_undistorted_camera_model(alpha,rectify_option=rectify_option)
def as_dict(self, alpha: float = 0.0, rectify_option=0) -> Dict:
undistorted = self.get_undistorted_camera_model(alpha, rectify_option=rectify_option)
p = np.zeros((3, 4))
p[0:3, 0:3] = undistorted.k

Expand All @@ -171,7 +171,7 @@ def as_dict(self, alpha: float = 0.0, rectify_option = 0) -> Dict:
}
distortion_model_used = "plumb_bob"
if self.d.size > 5:
distortion_model_used = "rational_polynomial"
distortion_model_used = "rational_polynomial"
d["distortion_model"] = distortion_model_used
d["distortion_coefficients"] = {
"rows": 1,
Expand Down Expand Up @@ -212,18 +212,24 @@ def update_config(self, **kwargs):
def get_undistorted_camera_model(self, alpha: float, rectify_option):
"""Compute the undistorted version of the camera model."""
if rectify_option == 1:

def get_rectangles(camera_matrix, dist_coeffs, img_size, new_camera_matrix=None):
N = 101
# Generate grid points
pts = np.zeros((1, N * N, 2), dtype=np.float64)
k = 0
for y in range(N):
for x in range(N):
pts[0, k] = [(x * (img_size[0] - 1)) / (N - 1), (y * (img_size[1] - 1)) / (N - 1)]
pts[0, k] = [
(x * (img_size[0] - 1)) / (N - 1),
(y * (img_size[1] - 1)) / (N - 1),
]
k += 1

# Undistort points
undistorted_pts = cv2.undistortPoints(pts, camera_matrix, dist_coeffs, P=new_camera_matrix)
undistorted_pts = cv2.undistortPoints(
pts, camera_matrix, dist_coeffs, P=new_camera_matrix
)
undistorted_pts = undistorted_pts.reshape(-1, 2)

# Initialize variables for inscribed and outer rectangle
Expand Down Expand Up @@ -258,6 +264,7 @@ def get_rectangles(camera_matrix, dist_coeffs, img_size, new_camera_matrix=None)
outer = (oX0, oY0, oX1 - oX0, oY1 - oY0)

return inner, outer

size = (self.width, self.height)
(image_width, image_height) = size
camera_matrix = self.k
Expand All @@ -273,7 +280,7 @@ def roi_to_intrinsics(roi):

new_image_width = image_width
new_image_height = image_height

if force_aspect_ratio:
# we want to make sure that fx = fy while also making sure all the roi is valid
if fx * roi[3] < image_height - 1:
Expand All @@ -295,13 +302,18 @@ def roi_to_intrinsics(roi):
outer_intrinsics, new_image_size = roi_to_intrinsics(outer)
new_intrinsics = inner_intrinsics * (1.0 - alpha) + outer_intrinsics * alpha

roi, _ = get_rectangles(camera_matrix, distortion_coefficients, size, new_camera_matrix=new_intrinsics)
roi, _ = get_rectangles(
camera_matrix, distortion_coefficients, size, new_camera_matrix=new_intrinsics
)
roi = list(roi)

new_image_width, new_image_height = new_image_size

return type(self)(
k=new_intrinsics, d=np.zeros_like(self.d), height=new_image_height, width=new_image_width
k=new_intrinsics,
d=np.zeros_like(self.d),
height=new_image_height,
width=new_image_width,
)
elif rectify_option == 0:
undistorted_k, _ = cv2.getOptimalNewCameraMatrix(
Expand All @@ -319,7 +331,9 @@ def rectify(self, img: np.array, alpha=0.0, rectify_option=0) -> np.array:

if self._cached_undistorted_model is None or alpha != self._cached_undistortion_alpha:
self._cached_undistortion_alpha = alpha
self._cached_undistorted_model = self.get_undistorted_camera_model(alpha=alpha, rectify_option=rectify_option)
self._cached_undistorted_model = self.get_undistorted_camera_model(
alpha=alpha, rectify_option=rectify_option
)
(
self._cached_undistortion_map_x,
self._cached_undistortion_map_y,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@
from PySide2.QtCore import Signal
from intrinsic_camera_calibrator.board_detections.board_detection import BoardDetection
from intrinsic_camera_calibrator.camera_models.camera_model import CameraModel
from intrinsic_camera_calibrator.data_sources.data_source import DataSourceEnum
from intrinsic_camera_calibrator.parameter import Parameter
from intrinsic_camera_calibrator.parameter import ParameterizedClass
from intrinsic_camera_calibrator.types import CollectionStatus
from intrinsic_camera_calibrator.types import OperationMode
from intrinsic_camera_calibrator.data_sources.data_source import DataSourceEnum
import numpy as np


Expand Down Expand Up @@ -258,7 +258,9 @@ def __init__(self, cfg: dict = dict(), **kwargs): # noqa C408
self.point_2d_hist_bins = Parameter(int, value=20, min_value=2, max_value=100)
self.point_3d_hist_bins = Parameter(int, value=20, min_value=2, max_value=100)

self.skip_frames_when_not_detection = Parameter(bool, value=True, min_value=False, max_value=True)
self.skip_frames_when_not_detection = Parameter(
bool, value=True, min_value=False, max_value=True
)

self.set_parameters(**cfg)

Expand Down Expand Up @@ -527,7 +529,9 @@ def process_detection(
# process detections without filtering, only to get linearity heatmap
self.update_linearity_heatmap(self.linearity_heatmap, detection)

if self.filter_by_speed.value and source_type != DataSourceEnum.FILES: # remove speed filter if we ar using images
if (
self.filter_by_speed.value and source_type != DataSourceEnum.FILES
): # remove speed filter if we ar using images
speed = 0 if self.last_detection is None else detection.get_speed(self.last_detection)
self.last_detection = detection

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ def on_start(self):
"""Start the calibration process after receiving the user settings."""

source_type = self.data_source_combobox.currentData()

def on_success():
"""Handle the successful initialization of the data source."""
mode = (
Expand Down

0 comments on commit 1760894

Please sign in to comment.