From 3e5f5fce72d746bf2a70dd62f80724bc642734c1 Mon Sep 17 00:00:00 2001 From: Jens Ahrensfeld Date: Thu, 11 Dec 2025 08:39:55 +0100 Subject: [PATCH] refactored initialization --- ar_tag_pose/detector_board_main.py | 46 ++++++++++++++++++++++-------- 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/ar_tag_pose/detector_board_main.py b/ar_tag_pose/detector_board_main.py index cab1a03..6b4da8e 100644 --- a/ar_tag_pose/detector_board_main.py +++ b/ar_tag_pose/detector_board_main.py @@ -17,15 +17,27 @@ RESULTS_FOLDER = "results" class Detector(abc.ABC): def __init__(self, name: str, params: dict, source: str, detector: list[BoardDetector], out_file: str|None = None, rotation_order: str=''): + Path.mkdir(Path(RESULTS_FOLDER), exist_ok=True) self.name = name self.params = params self.detector = detector self.out_file = out_file self.rotation_order = rotation_order - self.camera_name = "default" self.device_id = None self.src_video = None self.src_images = None + self.camera_name = None + try: + self.params_load() + except Exception: + self.params_save() + + self._source_init(source) + self.calibration = Calibration() + self.calibration.load(self._get_calibration_filename()) + + def _source_init(self, source: str): + self.cap = None if source.isnumeric(): self.device_id = int(source) else: @@ -40,13 +52,6 @@ class Detector(abc.ABC): suffix = basename.split('_')[-1].split('.')[1] self.src_images = f"{os.path.dirname(source)}/{name}_%0{len(numeric_part)}d.{suffix}" - Path.mkdir(Path(RESULTS_FOLDER), exist_ok=True) - try: - self.params_load() - except Exception: - self.params_save() - - self.cap = None if self.device_id is not None: # Open camera self.cap = cv.VideoCapture(self.device_id) @@ -59,15 +64,32 @@ class Detector(abc.ABC): self.cap = cv.VideoCapture(self.src_images, cv.CAP_IMAGES) self.camera_name = self.name - self.calibration = Calibration() - self.calibration.load(f"{RESULTS_FOLDER}/{self.camera_name}_cal.npz") + self.camera_name = self._get_camera_name() + + def _get_calibration_filename(self): + return f"{RESULTS_FOLDER}/{self.camera_name}_cal.npz" + + def _get_params_filename(self): + return f"{RESULTS_FOLDER}/{self.params["name"]}.json" + + def _get_camera_name(self): + camera_name = "default" + if self.cap is not None: + backends = {'V4L2': cv.CAP_V4L} + cameras = enumerate_cameras(backends[self.cap.getBackendName()]) + + for cam in cameras: + if cam.index == self.device_id: + camera_name = cam.name.split(':')[0] + + return camera_name def params_save(self): - with open(f"{RESULTS_FOLDER}/{self.params["name"]}.json", 'w') as fp: + with open(self._get_params_filename(), 'w') as fp: json.dump(self.params, fp, indent=4) def params_load(self): - with open(f"{RESULTS_FOLDER}/{self.params["name"]}.json", 'r') as fp: + with open(self._get_params_filename(), 'r') as fp: self.params = json.load(fp) def cap_init(self):