Free Motion Capture for Everyone πβ¨
TypeScript
building shared view accumulator
jonmatthis556adf363c1a
diff --git a/freemocap/api/websocket/websocket_server.py b/freemocap/api/websocket/websocket_server.pyindex 39e8fc29..e1e9e250 100644--- a/freemocap/api/websocket/websocket_server.py+++ b/freemocap/api/websocket/websocket_server.py@@ -99,7 +99,7 @@ class FreemocapWebsocketServer:try:while True:await async_wait_1ms()- # TODO - clean this up once the architecture firms up, names too long+ # TODO - clean this up once the architecture firms up, names are too long for my taste atmif not self._freemocap_app_state.skellycam_app_state.camera_group:latest_mf_number = -1continue@@ -115,7 +115,7 @@ class FreemocapWebsocketServer:camera_group_uuid = self._freemocap_app_state.skellycam_app_state.camera_group.uuidif processing_pipeline:processing_pipeline.shutdown()- processing_pipeline: BaseProcessingPipeline = self._freemocap_app_state.create_processing_pipeline(pipeline_type=PipelineTypes.MOCAP)+ processing_pipeline: BaseProcessingPipeline = self._freemocap_app_state.create_processing_pipeline(pipeline_type=PipelineTypes.CALIBRATION)processing_pipeline.start()continuediff --git a/freemocap/pipelines/calibration_pipeline/calibration_aggregation_node.py b/freemocap/pipelines/calibration_pipeline/calibration_aggregation_node.pyindex fc9dc992..867b4f7a 100644--- a/freemocap/pipelines/calibration_pipeline/calibration_aggregation_node.py+++ b/freemocap/pipelines/calibration_pipeline/calibration_aggregation_node.py@@ -5,7 +5,9 @@ from dataclasses import dataclassfrom multiprocessing import Queue, Processfrom typing import Dict+from pydantic import BaseModelfrom skellycam import CameraId+from tabulate import tabulatefrom freemocap.pipelines.calibration_pipeline.calibration_camera_node import CalibrationCameraNodeOutputDatafrom freemocap.pipelines.pipeline_abcs import BaseAggregationLayerOutputData, BasePipelineStageConfig, \@@ -17,13 +19,10 @@ logger = logging.getLogger(__name__)@dataclassclass CalibrationAggregationLayerOutputData(BaseAggregationLayerOutputData):data: object = None+def to_serializable_dict(self):return {"data": self.data}-@dataclass-class CalibrationAggregationNodeConfig(BasePipelineStageConfig):- param2: int = 2-@dataclassclass CalibrationPipelineOutputData(BasePipelineOutputData):@@ -32,12 +31,81 @@ class CalibrationPipelineOutputData(BasePipelineOutputData):def to_serializable_dict(self):return {- "camera_node_output": {camera_id: camera_node_output.to_serializable_dict() for camera_id, camera_node_output in+ "camera_node_output": {camera_id: camera_node_output.to_serializable_dict() for+ camera_id, camera_node_output inself.camera_node_output.items()},"aggregation_layer_output": self.aggregation_layer_output.to_serializable_dict()}+@dataclass+class CalibrationAggregationNodeConfig(BasePipelineStageConfig):+ param2: int = 2+++class CameraViewRecord(BaseModel):+ camera_id: CameraId+ can_see_target: bool+++class SharedViewAccumulator(BaseModel):+ """+ Keeps track of the data feeds from each camera, and keeps track of the frames where each can see the calibration target,+ and counts the number of shared views each camera has with each other camera (i.e. frames where both cameras can see the target)+ """+ camera_ids: list[CameraId]+ camera_view_records_by_frame: dict[int, Dict[CameraId, CameraViewRecord]]++ @classmethod+ def create(cls, camera_ids: list[CameraId]):+ return cls(camera_ids=camera_ids, camera_view_records_by_frame={})++ @property+ def shared_views_per_camera_by_camera(self) -> dict[CameraId, dict[CameraId, int]]:+ shared_views_by_camera = {+ camera_id: {other_camera_id: 0 for other_camera_id in self.camera_ids if other_camera_id != camera_id}+ for camera_id in self.camera_ids}+ for frame_number, camera_view_records in self.camera_view_records_by_frame.items():+ for camera_id, camera_view_record in camera_view_records.items():+ for other_camera_view_record in camera_view_records.values():+ if other_camera_view_record.camera_id != camera_id:+ if camera_view_records[camera_id].can_see_target and other_camera_view_record.can_see_target:+ shared_views_by_camera[camera_id][other_camera_view_record.camera_id] += 1+ return shared_views_by_camera++ @property+ def shared_views_total_per_camera(self) -> dict[CameraId, int]:+ return {camera_id: sum(shared_views.values()) for camera_id, shared_views in+ self.shared_views_per_camera_by_camera.items()}++ def receive_camera_node_output(self, multi_frame_number: int,+ camera_node_output: dict[CameraId, CalibrationCameraNodeOutputData]):+ self.camera_view_records_by_frame[multi_frame_number] = {camera_id: CameraViewRecord(camera_id=camera_id,+ can_see_target=camera_node_output.can_see_target)+ for camera_id, camera_node_output in+ camera_node_output.items()}++ def as_pretty_table(self) -> str:+ """+ Print the shared views per camera in rows with totals beneath, using 'tabulate' to format the table+ """+ shared_views_per_camera_by_camera = self.shared_views_per_camera_by_camera+ shared_views_total_per_camera = self.shared_views_total_per_camera+ camera_ids = [str(camera_id) for camera_id in self.camera_ids]++ headers = [''] + camera_ids+ table_data = []+ for camera_id, shared_views in shared_views_per_camera_by_camera.items():+ camera_row = [str(camera_id)]+ camera_row.extend(str(shared_views.get(other_camera_id, 0)) for other_camera_id in camera_ids)+ table_data.append(camera_row)++ shared_totals_row = ['Total'] + [shared_views_total_per_camera.get(camera_id, 0) for camera_id in camera_ids]+ table_data.append(shared_totals_row)++ return tabulate(table_data, headers=headers)++@dataclassclass CalibrationAggregationProcessNode(BaseAggregationNode):@classmethod@@ -70,12 +138,14 @@ class CalibrationAggregationProcessNode(BaseAggregationNode):while not all([value.is_set() for value in all_ready_events.values()]):time.sleep(0.001)logger.trace(f"All processing nodes ready!")- try:- camera_node_incoming_data: dict[CameraId, CalibrationCameraNodeOutputData | None] = {camera_id: None for- camera_id in- input_queues.keys()}-+ camera_node_incoming_data: dict[CameraId, CalibrationCameraNodeOutputData | None] = {camera_id: None for+ camera_id in+ input_queues.keys()}+ shared_view_accumulator: SharedViewAccumulator = SharedViewAccumulator.create(+ camera_ids=list(input_queues.keys()))+ incoming_data: list[dict[CameraId, CalibrationCameraNodeOutputData | None]] = []+ try:while not shutdown_event.is_set():@@ -88,7 +158,12 @@ class CalibrationAggregationProcessNode(BaseAggregationNode):if not isinstance(camera_node_output, CalibrationCameraNodeOutputData):raise ValueError(f"Unexpected data type received from camera {camera_id}: {type(camera_node_output)}")- camera_node_incoming_data[camera_id] = camera_node_output+ camera_node_incoming_data[+ camera_id] = camera_node_output # type: ignore # noqa //Not sure why this is throwing a linter error, might be too many nested types are confusing the poor machine++ if any([camera_node_output is None for camera_node_output in camera_node_incoming_data.values()]):+ logger.exception(f"Received None from camera nodes! got {camera_node_incoming_data}")+ raise ValueError(f"Received None from camera nodes! got {camera_node_incoming_data}")frame_numbers = set([camera_node_output.frame_metadata.frame_number for camera_node_output in@@ -96,13 +171,20 @@ class CalibrationAggregationProcessNode(BaseAggregationNode):if len(frame_numbers) > 1:logger.exception(f"Frame numbers from camera nodes do not match! got {frame_numbers}")raise ValueError(f"Frame numbers from camera nodes do not match! got {frame_numbers}")- latest_frame_number = frame_numbers.pop()- # TODO - add aggregation logic here- output= CalibrationPipelineOutputData(camera_node_output=camera_node_incoming_data, # type: ignore- aggregation_layer_output=CalibrationAggregationLayerOutputData(- data={"multi_frame_number": latest_frame_number}- )- )+ multi_frame_number = frame_numbers.pop()+ # Accumulate shared views+ incoming_data.append(camera_node_incoming_data)+ shared_view_accumulator.receive_camera_node_output(multi_frame_number=multi_frame_number,+ camera_node_output=camera_node_incoming_data)+ logger.trace(f"Shared view accumulator:\n {shared_view_accumulator.as_pretty_table()}")+ output = CalibrationPipelineOutputData(camera_node_output=camera_node_incoming_data, # type: ignore+ aggregation_layer_output=CalibrationAggregationLayerOutputData(+ multi_frame_number=multi_frame_number,+ points3d={f"camera_{camera_id}": (camera_id, 1, 2) for+ camera_id in input_queues.keys()},+ data=shared_view_accumulator.model_dump()+ )+ )output_queue.put(output)except Exception as e:diff --git a/freemocap/pipelines/calibration_pipeline/calibration_camera_node.py b/freemocap/pipelines/calibration_pipeline/calibration_camera_node.pyindex b752c9e1..61d12ca7 100644--- a/freemocap/pipelines/calibration_pipeline/calibration_camera_node.py+++ b/freemocap/pipelines/calibration_pipeline/calibration_camera_node.py@@ -33,11 +33,16 @@ class CalibrationCameraNodeOutputData(BaseCameraNodeOutputData):charuco_observation: CharucoObservationcalibration_dto: SingleCameraCalibrationDTO+ @property+ def can_see_target(self) -> bool:+ return not self.charuco_observation.charuco_empty+def to_serializable_dict(self) -> dict:return dict(frame_metadata=self.frame_metadata.model_dump(),charuco_observation=self.charuco_observation.to_serializable_dict(),calibration_dto=self.calibration_dto.to_serializable_dict(),+ can_see_target=self.can_see_target,)@dataclassdiff --git a/freemocap/pipelines/mocap_pipeline/mocap_aggregation_node.py b/freemocap/pipelines/mocap_pipeline/mocap_aggregation_node.pyindex c717ebd8..1b1ffca1 100644--- a/freemocap/pipelines/mocap_pipeline/mocap_aggregation_node.py+++ b/freemocap/pipelines/mocap_pipeline/mocap_aggregation_node.py@@ -89,6 +89,9 @@ class MocapAggregationProcessNode(BaseAggregationNode):f"Unexpected data type received from camera {camera_id}: {type(camera_node_output)}")camera_node_incoming_data[camera_id] = camera_node_output+ if any([camera_node_output is None for camera_node_output in camera_node_incoming_data.values()]):+ logger.exception(f"Received None from camera nodes! got {camera_node_incoming_data}")+ raise ValueError(f"Received None from camera nodes! got {camera_node_incoming_data}")frame_numbers = set([camera_node_output.frame_metadata.frame_number for camera_node_output incamera_node_incoming_data.values()])diff --git a/freemocap/pipelines/mocap_pipeline/point_trangulator.py b/freemocap/pipelines/mocap_pipeline/point_trangulator.pyindex 0eea5ec2..eefa9ec9 100644--- a/freemocap/pipelines/mocap_pipeline/point_trangulator.py+++ b/freemocap/pipelines/mocap_pipeline/point_trangulator.py@@ -47,6 +47,8 @@ class CameraCalibrationData:@propertydef rotation_matrix(self):+ if self.rotation_vector is None:+ return np.eye(3)return cv2.Rodrigues(self.rotation_vector)[0]@property