Skip to content

Free Motion Capture for Everyone πŸ’€βœ¨

TypeScript

calibration camera nodes work!

jonmatthis9f3168db7432
diff --git a/freemocap/api/websocket/websocket_server.py b/freemocap/api/websocket/websocket_server.py
index 74e625d3..19cabb07 100644
--- a/freemocap/api/websocket/websocket_server.py
+++ b/freemocap/api/websocket/websocket_server.py
@@ -48,7 +48,7 @@ class FreemocapWebsocketServer:
"""
Relay messages from the sub-processes to the frontend via the websocket.
"""
- logger.info("Starting websocket relay listener...")
+ logger.info("Websocket relay listener started...")
try:
while True:
@@ -89,7 +89,7 @@ class FreemocapWebsocketServer:
Relay image payloads from the shared memory to the frontend via the websocket.
"""
logger.info(
- f"Starting frontend image payload relay...")
+ f"Frontend image payload started...")
camera_group_uuid = None
latest_mf_number = -1
diff --git a/freemocap/freemocap_app/freemocap_app_state.py b/freemocap/freemocap_app/freemocap_app_state.py
index 64111dbf..ca6c62e0 100644
--- a/freemocap/freemocap_app/freemocap_app_state.py
+++ b/freemocap/freemocap_app/freemocap_app_state.py
@@ -22,7 +22,7 @@ class FreemocapAppState:
global_kill_flag: multiprocessing.Value
pipeline_shutdown_event: multiprocessing.Event
skellycam_app_state: SkellycamAppState
- camera_group_shm: SingleSlotCameraGroupSharedMemory | None = None
+ processing_camera_shms: SingleSlotCameraGroupSharedMemory | None = None
@classmethod
def create(cls, global_kill_flag: multiprocessing.Value):
@@ -48,15 +48,16 @@ class FreemocapAppState:
def skellycam_ipc_queue(self):
return self.skellycam_app_state.ipc_queue
- def get_camera_shm_dtos(self) -> CameraSharedMemoryDTOs:
- if not self.camera_group_shm:
- self._create_camera_group_shm()
- return {camera_id: shm.to_dto() for camera_id, shm in self.camera_group_shm.camera_shms.items()}
- def _create_camera_group_shm(self):
+ def get_processor_camera_shms_dtos(self) -> CameraSharedMemoryDTOs:
+
+ self._create_processing_camera_shms()
+ return self.processing_camera_shms.camera_shm_dtos
+
+ def _create_processing_camera_shms(self):
if self.skellycam_app_state.camera_group is None:
- raise ValueError("Cannot get RingBufferCameraSharedMemory without CameraGroup!")
- self.camera_group_shm = SingleSlotCameraGroupSharedMemory.create(camera_configs=self.camera_configs,
+ raise ValueError("Cannot create camera shared memory before camera group is initialized!")
+ self.processing_camera_shms = SingleSlotCameraGroupSharedMemory.create(camera_configs=self.camera_configs,
read_only=True)
def create_processing_server(self) -> BaseProcessingServer:
@@ -76,7 +77,7 @@ class FreemocapAppState:
pipeline_config=CalibrationPipelineConfig.create(camera_configs=self.camera_configs,
tracker_config=CharucoTrackerConfig()
),
- camera_shm_dtos=self.get_camera_shm_dtos(),
+ camera_shm_dtos=self.get_processor_camera_shms_dtos(),
shutdown_event=self.pipeline_shutdown_event,
)
@@ -84,8 +85,8 @@ class FreemocapAppState:
self.pipeline_shutdown_event.set()
self.skellycam_app_state.close()
- if self.camera_group_shm:
- self.camera_group_shm.close_and_unlink()
+ if self.processing_camera_shms:
+ self.processing_camera_shms.close_and_unlink()
FREEMOCAP_APP_STATE: FreemocapAppState | None = None
diff --git a/freemocap/pipelines/calibration_pipeline/calibration_aggregation_node.py b/freemocap/pipelines/calibration_pipeline/calibration_aggregation_node.py
index 1b6aa577..7f0feaab 100644
--- a/freemocap/pipelines/calibration_pipeline/calibration_aggregation_node.py
+++ b/freemocap/pipelines/calibration_pipeline/calibration_aggregation_node.py
@@ -14,9 +14,9 @@ from freemocap.pipelines.pipeline_abcs import BaseAggregationLayerOutputData, Ba
logger = logging.getLogger(__name__)
-
+@dataclass
class CalibrationAggregationLayerOutputData(BaseAggregationLayerOutputData):
- pass
+ data: object = None
@dataclass
@@ -25,10 +25,11 @@ class CalibrationPipelineOutputData(BasePipelineOutputData):
aggregation_layer_output: CalibrationAggregationLayerOutputData
+@dataclass
class CalibrationAggregationNodeConfig(BasePipelineStageConfig):
param2: int = 2
-
+@dataclass
class CalibrationAggregationProcessNode(BaseAggregationNode):
@classmethod
def create(cls,
@@ -55,7 +56,7 @@ class CalibrationAggregationProcessNode(BaseAggregationNode):
logger.trace(f"Aggregation processing node started!")
try:
while not shutdown_event.is_set():
- data_by_camera_id: dict[CameraId, CalibrationCameraNode | None] = {camera_id: None for
+ data_by_camera_id: dict[CameraId, CalibrationCameraNodeOutputData | None] = {camera_id: None for
camera_id in
input_queues.keys()}
while any([value is None for value in data_by_camera_id.values()]):
@@ -63,7 +64,7 @@ class CalibrationAggregationProcessNode(BaseAggregationNode):
for camera_id in input_queues.keys():
if data_by_camera_id[camera_id] is None:
if not input_queues[camera_id].empty():
- camera_node_output = input_queues[camera_id].get()
+ camera_node_output:CalibrationCameraNodeOutputData = input_queues[camera_id].get()
if not isinstance(camera_node_output, CalibrationCameraNodeOutputData):
raise ValueError(
f"Unexpected data type received from camera {camera_id}: {type(camera_node_output)}")
diff --git a/freemocap/pipelines/calibration_pipeline/calibration_camera_node.py b/freemocap/pipelines/calibration_pipeline/calibration_camera_node.py
index 1bc286f8..25d73096 100644
--- a/freemocap/pipelines/calibration_pipeline/calibration_camera_node.py
+++ b/freemocap/pipelines/calibration_pipeline/calibration_camera_node.py
@@ -1,38 +1,48 @@
import logging
import multiprocessing
+import time
from dataclasses import dataclass
from multiprocessing import Queue, Process
-import time
from skellycam import CameraId
from skellycam.core.camera_group.camera.config.camera_config import CameraConfig
from skellycam.core.camera_group.shmorchestrator.shared_memory.single_slot_camera_shared_memory import \
CameraSharedMemoryDTO, SingleSlotCameraSharedMemory
-from skellytracker.trackers.charuco_tracker.charuco_observation import CharucoObservation
+from skellycam.core.frames.payloads.metadata.frame_metadata import FrameMetadata
from skellytracker.trackers.charuco_tracker import CharucoTrackerConfig, CharucoTracker
+from skellytracker.trackers.charuco_tracker.charuco_observation import CharucoObservation
+from freemocap.pipelines.calibration_pipeline.single_camera_calibrator import SingleCameraCalibrator, \
+ SingleCameraCalibrationDTO
from freemocap.pipelines.pipeline_abcs import BaseCameraNode, BasePipelineStageConfig, BasePipelineData, \
BaseCameraNodeOutputData
logger = logging.getLogger(__name__)
+
@dataclass
class CalibrationPipelineAggregationLayerOutputData(BasePipelineData):
pass
+
@dataclass
class CalibrationPipelineAggregationNodeConfig(BasePipelineStageConfig):
param2: int = 2
+
@dataclass
class CalibrationPipelineCameraNodeConfig(BasePipelineStageConfig):
camera_config: CameraConfig
tracker_config: CharucoTrackerConfig
param1: int = 1
+
@dataclass
class CalibrationCameraNodeOutputData(BaseCameraNodeOutputData):
- data: CharucoObservation
+ frame_metadata: FrameMetadata
+ charuco_observation: CharucoObservation
+ calibration_dto: SingleCameraCalibrationDTO
+
@dataclass
class CalibrationCameraNode(BaseCameraNode):
@@ -46,9 +56,9 @@ class CalibrationCameraNode(BaseCameraNode):
):
return cls(camera_id=camera_id,
config=config,
- camera_ring_shm=SingleSlotCameraSharedMemory.recreate(camera_config=config.camera_config,
- camera_shm_dto=camera_shm_dto,
- read_only=False),
+ incoming_frame_shm=SingleSlotCameraSharedMemory.recreate(camera_config=config.camera_config,
+ camera_shm_dto=camera_shm_dto,
+ read_only=False),
process=Process(target=cls._run,
kwargs=dict(camera_id=camera_id,
config=config,
@@ -68,24 +78,46 @@ class CalibrationCameraNode(BaseCameraNode):
shutdown_event: multiprocessing.Event,
):
logger.trace(f"Camera#{camera_id} processing node started!")
- camera_ring_shm = SingleSlotCameraSharedMemory.recreate(
+ frame_intake_shm = SingleSlotCameraSharedMemory.recreate(
camera_config=config.camera_config,
camera_shm_dto=camera_shm_dto,
read_only=False)
charuco_tracker = CharucoTracker.create(config=config.tracker_config)
-
+ camera_calibration_estimator: SingleCameraCalibrator | None = None
try:
while not shutdown_event.is_set():
time.sleep(0.001)
- if camera_ring_shm.new_frame_available:
- frame = camera_ring_shm.retrieve_frame()
+ if frame_intake_shm.new_frame_available:
+ tik = time.perf_counter_ns()
+ frame = frame_intake_shm.retrieve_frame()
+ time_to_retrieve = time.perf_counter_ns() - tik
+ tik = time.perf_counter_ns()
observation = charuco_tracker.process_image(frame.image, annotate_image=False)
- output_queue.put(CalibrationCameraNodeOutputData(data=observation))
+ if camera_calibration_estimator is None:
+ camera_calibration_estimator = SingleCameraCalibrator.create_initial(
+ image_size=frame.image.shape[:2],
+ aruco_marker_ids=list(charuco_tracker.detector.board.getIds()),
+ aruco_corners_in_object_coordinates=charuco_tracker.aruco_corners_in_object_coordinates,
+ charuco_corner_ids=charuco_tracker.charuco_corner_ids,
+ charuco_corners_in_object_coordinates=charuco_tracker.charuco_corners_in_object_coordinates,
+ )
+ if not camera_calibration_estimator.has_calibration and not observation.charuco_empty and frame.frame_number % 10 == 0:
+ camera_calibration_estimator.add_observation(observation)
+ if len(camera_calibration_estimator.charuco_observations) == 30:
+ camera_calibration_estimator.update_calibration_estimate()
+ time_to_process = time.perf_counter_ns() - tik
+ output_queue.put(CalibrationCameraNodeOutputData(frame_metadata=FrameMetadata.from_frame_metadata_array(frame.metadata),
+ charuco_observation=observation,
+ calibration_dto=camera_calibration_estimator.to_dto(),
+ time_to_retrieve_frame_ns=time_to_retrieve,
+ time_to_process_frame_ns=time_to_process
+ ),
+ )
except Exception as e:
logger.exception(f"Error in camera processing node for camera {camera_id}", exc_info=e)
raise
finally:
logger.trace(f"Shutting down camera processing node for camera {camera_id}")
shutdown_event.set()
- camera_ring_shm.close()
+ frame_intake_shm.close()
diff --git a/freemocap/pipelines/calibration_pipeline/single_camera_calibrator.py b/freemocap/pipelines/calibration_pipeline/single_camera_calibrator.py
new file mode 100644
index 00000000..d37057d3
--- /dev/null
+++ b/freemocap/pipelines/calibration_pipeline/single_camera_calibrator.py
@@ -0,0 +1,237 @@
+from dataclasses import dataclass, field
+
+import cv2
+import numpy as np
+
+from skellytracker.trackers.charuco_tracker.charuco_observation import CharucoObservations, CharucoObservation
+
+
+@dataclass
+class SingleCameraCalibrationError:
+ mean_reprojection_error: float
+ reprojection_error_by_view: list[float]
+ jacobian: list[np.ndarray]
+
+
+DEFAULT_INTRINSICS_COEFFICIENTS_COUNT = 5
+MIN_CHARUCO_CORNERS = 6
+
+@dataclass
+class SingleCameraCalibrationDTO:
+ camera_matrix: np.ndarray[3, 3]
+ distortion_coefficients: np.ndarray[..., 1]
+ mean_reprojection_errors: list[float]
+ camera_calibration_residuals: list[float]
+ charuco_observations: CharucoObservations
+ object_points_views: list[np.ndarray[..., 3]]
+ image_points_views: list[np.ndarray[..., 2]]
+ rotation_vectors: list[np.ndarray[..., 3]]
+ translation_vectors: list[np.ndarray[..., 3]]
+ reprojection_error_by_view: list[float]
+
+@dataclass
+class SingleCameraCalibrator:
+
+ """
+ SingleCameraCalibrator class for estimating camera calibration parameters.
+
+ cv2.calibrateCamera docs: https://docs.opencv.org/4.10.0/d9/d0c/group__calib3d.html#ga687a1ab946686f0d85ae0363b5af1d7b
+
+ Attributes:
+ camera_matrix (np.ndarray[3, 3]): 3x3 matrix with rows: [focal_length_x, 0, center_point_x],
+ [0, focal_length_y, center_point_y], [0, 0, 1]
+ distortion_coefficients (np.ndarray[..., 1]): Distortion coefficients to include, e.g. [k1, k2, p1, p2, k3].
+ Can be 4, 5, 8, 12, or 14 elements.
+ object_points_views (list[np.ndarray[..., 3]]): List of 3D points in the world (or object) coordinate space.
+ image_points_views (list[np.ndarray[..., 2]]): List of 2D points in the image coordinate space (i.e. pixel coordinates).
+ rotation_vectors (list[np.ndarray[..., 3]]): List of rotation vectors, containing the rotation of the camera
+ relative to the world coordinate space for each view.
+ translation_vectors (list[np.ndarray[..., 3]]): List of translation vectors, containing the translation of the camera
+ relative to the world coordinate space for each view.
+ error (SingleCameraCalibrationError | None): Calibration error details.
+ """
+ image_size: tuple[int, ...]
+
+ charuco_corner_ids: list[int]
+ charuco_corners_in_object_coordinates: np.ndarray[..., 3]
+
+ aruco_marker_ids: list[int]
+ aruco_corners_in_object_coordinates: list[np.ndarray[..., 3]]
+
+ distortion_coefficients: np.ndarray[..., 1]
+ camera_matrix: np.ndarray[3, 3]
+
+ charuco_observations: CharucoObservations = field(default_factory=list)
+ object_points_views: list[np.ndarray[..., 3]] = field(default_factory=list)
+ image_points_views: list[np.ndarray[..., 2]] = field(default_factory=list)
+ rotation_vectors: list[np.ndarray[..., 3]] = field(default_factory=list)
+ translation_vectors: list[np.ndarray[..., 3]] = field(default_factory=list)
+ reprojection_error_by_view:list[float] = field(default_factory=list)
+ mean_reprojection_errors: list[float] = field(default_factory=list)
+ camera_calibration_residuals: list[float] = field(default_factory=list)
+
+ @property
+ def has_calibration(self):
+ return len(self.mean_reprojection_errors) > 0
+
+ @classmethod
+ def create_initial(cls,
+ image_size: tuple[int, ...],
+ aruco_marker_ids: list[int],
+ aruco_corners_in_object_coordinates: list[np.ndarray[..., 3]],
+ charuco_corner_ids: list[int],
+ charuco_corners_in_object_coordinates: np.ndarray[..., 3],
+ number_of_distortion_coefficients: int = DEFAULT_INTRINSICS_COEFFICIENTS_COUNT):
+ camera_matrix = np.eye(3)
+ camera_matrix[0, 2] = image_size[0] / 2 # x_center
+ camera_matrix[1, 2] = image_size[1] / 2 # y_center
+
+
+ if not number_of_distortion_coefficients in [4, 5, 8, 12, 14]:
+ raise ValueError("Invalid number of distortion coefficients. Must be 4, 5, 8, 12, or 14.")
+
+ if len(charuco_corner_ids) != charuco_corners_in_object_coordinates.shape[0]:
+ raise ValueError("Number of charuco corner IDs must match the number of charuco corners.")
+ if len(aruco_marker_ids) != len(aruco_corners_in_object_coordinates):
+ raise ValueError("Number of aruco marker IDs must match the number of aruco corners.")
+
+ return cls(image_size=image_size,
+ charuco_corner_ids=charuco_corner_ids,
+ charuco_corners_in_object_coordinates=charuco_corners_in_object_coordinates,
+ aruco_marker_ids=aruco_marker_ids,
+ aruco_corners_in_object_coordinates=aruco_corners_in_object_coordinates,
+ camera_matrix=camera_matrix,
+ distortion_coefficients=np.zeros(number_of_distortion_coefficients),
+ )
+
+
+ def add_observation(self, observation: CharucoObservation):
+ if observation.charuco_empty or len(observation.detected_charuco_corner_ids) < MIN_CHARUCO_CORNERS:
+ return
+ self._validate_observation(observation)
+
+ self.charuco_observations.append(observation)
+ self.image_points_views.append(np.squeeze(observation.detected_charuco_corners_image_coordinates))
+ self.object_points_views.append(
+ self.charuco_corners_in_object_coordinates[np.squeeze(observation.detected_charuco_corner_ids), :])
+
+
+ def update_calibration_estimate(self):
+ if len(self.object_points_views) < len(self.charuco_corner_ids):
+ raise ValueError(f"You must have at least as many observations as charuco corners: "
+ f"#Current views: {len(self.object_points_views)}, "
+ f"#Charuco corners: {len(self.charuco_corner_ids)}")
+
+ (residual,
+ self.camera_matrix,
+ self.distortion_coefficients,
+ self.rotation_vectors,
+ self.translation_vectors) = cv2.calibrateCamera(objectPoints=self.object_points_views,
+ imagePoints=self.image_points_views,
+ imageSize=self.image_size,
+ cameraMatrix=self.camera_matrix,
+ distCoeffs=self.distortion_coefficients,
+ )
+
+
+ if not residual:
+ raise ValueError(f"Camera Calibration failed! Check your input data:",
+ f"object_points_views: {self.object_points_views}",
+ f"image_points_views: {self.image_points_views}",
+ f"camera_matrix: {self.camera_matrix}",
+ f"distortion_coefficients: {self.distortion_coefficients}",
+ )
+ self.camera_calibration_residuals.append(residual)
+ self._update_reprojection_error()
+ self._drop_suboptimal_views()
+
+ def get_board_pose(self, object_points: np.ndarray[..., 3], image_points: np.ndarray[..., 2]) -> tuple[
+ np.ndarray[..., 3], np.ndarray[..., 3]]:
+ if len(object_points) < 6:
+ raise ValueError("You must have at least 4 object points to estimate the board pose.")
+ if len(self.camera_calibration_residuals) == 0:
+ raise ValueError("You must first calibrate the camera to get the board pose.")
+ if len(object_points) != len(image_points):
+ raise ValueError("The number of object and image points must be the same")
+ success, rotation_vector, translation_vector = cv2.solvePnP(objectPoints=object_points,
+ imagePoints=image_points,
+ cameraMatrix=self.camera_matrix,
+ distCoeffs=self.distortion_coefficients)
+ if not success:
+ raise ValueError(
+ f"Failed to estimate board pose for object points: {object_points} and image points: {image_points}")
+ return rotation_vector, translation_vector
+
+ def draw_board_axes(self, image: np.ndarray, observation: CharucoObservation) -> np.ndarray:
+ if len(self.camera_calibration_residuals) == 0:
+ raise ValueError("You must first calibrate the camera to draw the board axes.")
+ if observation.detected_charuco_corners_image_coordinates.shape[0] < 6:
+ return image
+ rotation_vector, translation_vector = self.get_board_pose(
+ object_points=observation.detected_charuco_corners_in_object_coordinates,
+ image_points=observation.detected_charuco_corners_image_coordinates
+ )
+ axis_length = 5
+ return cv2.drawFrameAxes(image,
+ self.camera_matrix,
+ self.distortion_coefficients,
+ rotation_vector,
+ translation_vector,
+ axis_length)
+
+ def _validate_observation(self, observation: CharucoObservation):
+ if observation.image_size != self.image_size:
+ raise ValueError("Image size mismatch")
+ if any([corner_id not in self.charuco_corner_ids for corner_id in observation.detected_charuco_corner_ids]):
+ raise ValueError(
+ f"Invalid charuco corner ID detected: {observation.detected_charuco_corner_ids} not all in {self.charuco_corner_ids}")
+
+ def _drop_suboptimal_views(self, ratio_to_keep: float = 0.5):
+ if len(self.reprojection_error_by_view) < 2:
+ return
+ sorted_indices = np.argsort(self.reprojection_error_by_view)
+ number_of_views_to_keep = int(len(sorted_indices) * ratio_to_keep)
+ self.object_points_views = [self.object_points_views[i] for i in sorted_indices[:number_of_views_to_keep]]
+ self.image_points_views = [self.image_points_views[i] for i in sorted_indices[:number_of_views_to_keep]]
+ self.rotation_vectors = [self.rotation_vectors[i] for i in sorted_indices[:number_of_views_to_keep]]
+ self.translation_vectors = [self.translation_vectors[i] for i in sorted_indices[:number_of_views_to_keep]]
+ self.reprojection_error_by_view = [self.reprojection_error_by_view[i] for i in sorted_indices[:number_of_views_to_keep]]
+ self.charuco_observations = [self.charuco_observations[i] for i in sorted_indices[:number_of_views_to_keep]]
+
+
+
+
+ def _update_reprojection_error(self):
+ if len(self.image_points_views) != len(self.object_points_views):
+ raise ValueError("The number of image and object points must be the same")
+ if len(self.image_points_views) == 0:
+ raise ValueError("No image points provided")
+ error = None
+ jacobian = None
+ self.reprojection_error_by_view = []
+ for view_index in range(len(self.image_points_views)):
+ projected_image_points, jacobian = cv2.projectPoints(self.object_points_views[view_index],
+ self.rotation_vectors[view_index],
+ self.translation_vectors[view_index],
+ self.camera_matrix,
+ self.distortion_coefficients)
+
+ self.reprojection_error_by_view.append(np.mean(np.abs(self.image_points_views[view_index] - np.squeeze(projected_image_points))))
+
+ self.mean_reprojection_errors.append(np.mean(self.reprojection_error_by_view) if self.reprojection_error_by_view else -1)
+
+ print(f"Mean reprojection errors: {self.mean_reprojection_errors}")
+
+ def to_dto(self) -> SingleCameraCalibrationDTO:
+ return SingleCameraCalibrationDTO(
+ camera_matrix=self.camera_matrix,
+ distortion_coefficients=self.distortion_coefficients,
+ mean_reprojection_errors=self.mean_reprojection_errors,
+ camera_calibration_residuals=self.camera_calibration_residuals,
+ charuco_observations=self.charuco_observations,
+ object_points_views=self.object_points_views,
+ image_points_views=self.image_points_views,
+ rotation_vectors=self.rotation_vectors,
+ translation_vectors=self.translation_vectors,
+ reprojection_error_by_view=self.reprojection_error_by_view,
+ )
\ No newline at end of file
diff --git a/freemocap/pipelines/dummy_pipeline.py b/freemocap/pipelines/dummy_pipeline.py
index cf3f82fe..8ea4b5f4 100644
--- a/freemocap/pipelines/dummy_pipeline.py
+++ b/freemocap/pipelines/dummy_pipeline.py
@@ -55,9 +55,9 @@ class DummyCameraProcessingNode(BaseCameraNode):
):
return cls(camera_id=camera_id,
config=config,
- camera_ring_shm=SingleSlotCameraSharedMemory.recreate(camera_config=config.camera_config,
- camera_shm_dto=camera_shm_dto,
- read_only=False),
+ incoming_frame_shm=SingleSlotCameraSharedMemory.recreate(camera_config=config.camera_config,
+ camera_shm_dto=camera_shm_dto,
+ read_only=False),
process=Process(target=cls._run,
kwargs=dict(camera_id=camera_id,
config=config,
diff --git a/freemocap/pipelines/pipeline_abcs.py b/freemocap/pipelines/pipeline_abcs.py
index 384a1280..5807562f 100644
--- a/freemocap/pipelines/pipeline_abcs.py
+++ b/freemocap/pipelines/pipeline_abcs.py
@@ -6,13 +6,14 @@ from enum import Enum
from multiprocessing import Process, Queue
from skellycam.core import CameraId
-from skellycam.core.camera_group.shmorchestrator.shared_memory.ring_buffer_camera_shared_memory import \
- RingBufferCameraSharedMemory, RingBufferCameraSharedMemoryDTO
+from skellycam.core.camera_group.shmorchestrator.shared_memory.single_slot_camera_group_shared_memory import \
+ SingleSlotCameraSharedMemory
from skellycam.core.camera_group.shmorchestrator.shared_memory.single_slot_camera_shared_memory import \
CameraSharedMemoryDTO
from skellycam.core.frames.payloads.frame_payload import FramePayload
+from skellycam.core.frames.payloads.metadata.frame_metadata import FrameMetadata
from skellycam.core.frames.payloads.multi_frame_payload import MultiFramePayload
-from skellytracker.trackers.base_tracker.base_tracker import BaseTrackerConfig, BaseTracker, BaseImageAnnotator
+from skellytracker.trackers.base_tracker.base_tracker import BaseTrackerConfig, BaseImageAnnotator
logger = logging.getLogger(__name__)
@@ -23,8 +24,7 @@ class ReadTypes(str, Enum):
@dataclass
class BasePipelineData( ABC):
- data: object
- metadata: dict[object, object] = field(default_factory=dict)
+ pass
@dataclass
class BaseAggregationLayerOutputData(BasePipelineData):
@@ -32,12 +32,20 @@ class BaseAggregationLayerOutputData(BasePipelineData):
@dataclass
class BaseCameraNodeOutputData(BasePipelineData):
- pass
+ frame_metadata: FrameMetadata
+ time_to_retrieve_frame_ns: int
+ time_to_process_frame_ns: int
@dataclass
class BasePipelineOutputData(ABC):
camera_node_output: dict[CameraId, BaseCameraNodeOutputData]
aggregation_layer_output: BaseAggregationLayerOutputData
+ @property
+ def multi_frame_number(self) -> int:
+ frame_numbers = [camera_node_output.frame_metadata.frame_number for camera_node_output in self.camera_node_output.values()]
+ if len(set(frame_numbers)) > 1:
+ raise ValueError("Frame numbers from camera nodes do not match!")
+ return frame_numbers[0]
@dataclass
class BasePipelineStageConfig( ABC):
@@ -58,7 +66,7 @@ class BasePipelineConfig( ABC):
class BaseCameraNode(ABC):
config: BasePipelineStageConfig
camera_id: CameraId
- camera_ring_shm: RingBufferCameraSharedMemory
+ incoming_frame_shm: SingleSlotCameraSharedMemory
process: Process
shutdown_event: multiprocessing.Event
@@ -67,7 +75,7 @@ class BaseCameraNode(ABC):
def create(cls,
config: BasePipelineStageConfig,
camera_id: CameraId,
- camera_ring_shm_dto: RingBufferCameraSharedMemoryDTO,
+ incoming_frame_shm_dto: CameraSharedMemoryDTO,
output_queue: Queue,
shutdown_event: multiprocessing.Event):
raise NotImplementedError(
@@ -90,12 +98,12 @@ class BaseCameraNode(ABC):
# )
def intake_data(self, frame_payload: FramePayload):
- self.camera_ring_shm.put_frame(frame_payload.image, frame_payload.metadata)
+ self.incoming_frame_shm.put_frame(frame_payload.image, frame_payload.metadata)
@staticmethod
def _run(camera_id: CameraId,
config: BasePipelineStageConfig,
- camera_shm_dto: CameraSharedMemoryDTO,
+ incoming_frame_shm_dto: CameraSharedMemoryDTO,
output_queue: Queue,
shutdown_event: multiprocessing.Event):
raise NotImplementedError(
@@ -187,12 +195,16 @@ class BaseAggregationNode(ABC):
self.shutdown_event.set()
self.process.join()
+@dataclass
+class PipelineImageAnnotator(ABC):
+ pass
@dataclass
class BaseProcessingPipeline(ABC):
config: BasePipelineStageConfig
camera_nodes: dict[CameraId, BaseCameraNode]
aggregation_node: BaseAggregationNode
+ image_annotator: PipelineImageAnnotator
shutdown_event: multiprocessing.Event
annotator: BaseImageAnnotator | None = None
@@ -201,7 +213,7 @@ class BaseProcessingPipeline(ABC):
@classmethod
def create(cls,
config: BasePipelineStageConfig,
- camera_shm_dtos: dict[CameraId, RingBufferCameraSharedMemoryDTO],
+ camera_shm_dtos: dict[CameraId, CameraSharedMemoryDTO],
shutdown_event: multiprocessing.Event):
raise NotImplementedError(
"You need to re-implement this method with your pipeline's version of the CameraGroupProcessingPipeline "
@@ -247,15 +259,23 @@ class BaseProcessingPipeline(ABC):
return self.latest_pipeline_data
+ def get_output_for_frame(self, target_frame_number:int) -> BasePipelineOutputData | None:
+ while not self.aggregation_node.output_queue.empty():
+ self.latest_pipeline_data:BasePipelineOutputData = self.aggregation_node.output_queue.get()
+ if self.latest_pipeline_data.multi_frame_number > target_frame_number:
+ raise ValueError(f"We missed the target frame number {target_frame_number} - current output is for frame {self.latest_pipeline_data.multi_frame_number}")
+ if self.latest_pipeline_data.multi_frame_number == target_frame_number:
+ return self.latest_pipeline_data
+
+ return self.latest_pipeline_data
def annotate_images(self, multiframe_payload: MultiFramePayload) -> MultiFramePayload:
- latest_output = self.get_latest_data()
- if latest_output is not None:
+ pipeline_output = self.get_output_for_frame(target_frame_number=multiframe_payload.multi_frame_number)
+ if pipeline_output is not None:
for camera_id, frame in multiframe_payload.frames.items():
- if latest_output.camera_node_output[camera_id] is not None:
+ if pipeline_output.camera_node_output[camera_id] is not None:
frame.image = self.annotator.annotate_image(image=frame.image,
- latest_observation=latest_output.camera_node_output[camera_id].data, # type: ignore
-
+ latest_observation=pipeline_output.camera_node_output[camera_id].charuco_observation, # type: ignore
)
return multiframe_payload
@@ -281,7 +301,7 @@ class BaseProcessingServer(ABC):
@classmethod
def create(cls,
processing_pipeline: BaseProcessingPipeline,
- camera_shm_dtos: dict[CameraId, RingBufferCameraSharedMemoryDTO],
+ camera_shm_dtos: dict[CameraId, CameraSharedMemoryDTO],
shutdown_event: multiprocessing.Event):
raise NotImplementedError(
"You need to re-implement this method with your pipeline's version of the CameraGroupProcessingServer "
diff --git a/uv.lock b/uv.lock
index d3d02c2d..b0722adb 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1401,7 +1401,7 @@ dependencies = [
[[package]]
name = "skellytracker"
version = "2024.9.1019"
-source = { git = "https://github.com/freemocap/skellytracker?branch=jon%2Fdevelopment#c0eda885727d9381fcc4764e6654afbbbdc26db5" }
+source = { git = "https://github.com/freemocap/skellytracker?branch=jon%2Fdevelopment#b78fd2456ddb84bb7e6aa05d085fc17cfe4fa7bd" }
dependencies = [
{ name = "mediapipe" },
{ name = "numpy" },