aboutsummaryrefslogtreecommitdiff
path: root/src/argaze/ArUcoMarkers/ArUcoCamera.py
blob: 43a7cf56785b9bcb94112fc6d2f6c4d2700b7d86 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
#!/usr/bin/env python

"""ArCamera based of ArUco markers technology."""

__author__ = "Théo de la Hogue"
__credits__ = []
__copyright__ = "Copyright 2023, Ecole Nationale de l'Aviation Civile (ENAC)"
__license__ = "BSD"

from typing import TypeVar, Tuple
from dataclasses import dataclass, field
import json
import os

from argaze import ArFeatures, DataStructures
from argaze.ArUcoMarkers import ArUcoMarkersDictionary, ArUcoDetector, ArUcoOpticCalibrator, ArUcoScene
from argaze.AreaOfInterest import AOI2DScene

import cv2
import numpy

ArUcoCameraType = TypeVar('ArUcoCamera', bound="ArUcoCamera")
# Type definition for type annotation convenience

# Define default ArUcoCamera image_paremeters values
DEFAULT_ARUCOCAMERA_IMAGE_PARAMETERS = {
    "draw_detected_markers": {
		"color": (0, 255, 0),
		"draw_axes": {
			"thickness": 3
		}
	}
}

@dataclass
class ArUcoCamera(ArFeatures.ArCamera):
	"""
	Define an ArCamera based on ArUco marker detection.

		aruco_detector: ArUco marker detector
	"""

	aruco_detector: ArUcoDetector.ArUcoDetector = field(default_factory=ArUcoDetector.ArUcoDetector)

	def __post_init__(self):

		super().__post_init__()

		# Check optic parameters
		if self.aruco_detector.optic_parameters is not None:

			# Optic parameters dimensions should be equal to camera frame size 
			if self.aruco_detector.optic_parameters.dimensions != self.size:

				raise ArFeatures.LoadingFailed('ArUcoCamera: aruco_detector.optic_parameters.dimensions have to be equal to size.')

		# No optic parameters loaded
		else:

			# TODO: Create default optic parameters adapted to frame size
			raise ArFeatures.LoadingFailed('ArUcoCamera: no aruco_detector.optic_parameters.')

	def __str__(self) -> str:
		"""
		Returns:
			String representation
		"""

		output = super().__str__()
		output += f'ArUcoDetector:\n{self.aruco_detector}\n'

		return output

	@classmethod
	def from_dict(self, aruco_camera_data, working_directory: str = None) -> ArUcoCameraType:
		"""
		Load ArUcoCamera from dictionary.

		Parameters:
			aruco_camera_data: dictionary
			working_directory: folder path where to load files when a dictionary value is a relative filepath.
		"""

		# Load ArUco detector
		new_aruco_detector = ArUcoDetector.ArUcoDetector.from_dict(aruco_camera_data.pop('aruco_detector'), working_directory)

		# Load ArUcoScenes
		new_scenes = {}

		try:

			for aruco_scene_name, aruco_scene_data in aruco_camera_data.pop('scenes').items():

				# Append name
				aruco_scene_data['name'] = aruco_scene_name

				# Create new aruco scene
				new_aruco_scene = ArUcoScene.ArUcoScene.from_dict(aruco_scene_data, working_directory)

				# Append new scene
				new_scenes[aruco_scene_name] = new_aruco_scene
				
		except KeyError:

			pass

		# Set image_parameters to default if there is not
		if 'image_parameters' not in aruco_camera_data.keys():

			aruco_camera_data['image_parameters'] = {**ArFeatures.DEFAULT_ARFRAME_IMAGE_PARAMETERS, **DEFAULT_ARUCOCAMERA_IMAGE_PARAMETERS}
			
			# Set draw_layers to default if there is not
			if 'draw_layers' not in aruco_camera_data['image_parameters'].keys():

				aruco_camera_data['image_parameters']['draw_layers'] = {}

				for layer_name, layer_data in aruco_camera_data['layers'].items():
					aruco_camera_data['image_parameters']['draw_layers'][layer_name] = ArFeatures.DEFAULT_ARLAYER_DRAW_PARAMETERS

		# Get values of temporary ar frame created from aruco_camera_data
		temp_ar_frame_values = DataStructures.as_dict(ArFeatures.ArFrame.from_dict(aruco_camera_data, working_directory))

		# Create new aruco camera using temporary ar frame values
		return ArUcoCamera(aruco_detector=new_aruco_detector, scenes=new_scenes, **temp_ar_frame_values)

	@classmethod
	def from_json(self, json_filepath: str) -> ArUcoCameraType:
		"""
		Load ArUcoCamera from .json file.

		Parameters:
			json_filepath: path to json file
		"""

		with open(json_filepath) as configuration_file:

			aruco_camera_data = json.load(configuration_file)
			working_directory = os.path.dirname(json_filepath)

			return ArUcoCamera.from_dict(aruco_camera_data, working_directory)

	def watch(self, image: numpy.array) -> Tuple[float, dict]:
		"""Detect environment aruco markers from image and project scenes into camera frame.

		Returns:
            - detection_time: aruco marker detection time in ms
            - exceptions: dictionary with exception raised per scene
        """

		# Detect aruco markers
		detection_time = self.aruco_detector.detect_markers(image)

		# Lock camera frame exploitation
		self._frame_lock.acquire()

		# Fill camera frame background with image
		self.background = image

		# Clear former layers projection into camera frame
		for layer_name, layer in self.layers.items():
		
			layer.aoi_scene = AOI2DScene.AOI2DScene()

		# Store exceptions for each scene
		exceptions = {}

		# Project each aoi 3d scene into camera frame
		for scene_name, scene in self.scenes.items():

			''' TODO: Enable aruco_aoi processing
			if scene.aruco_aoi:

				try:

					# Build AOI scene directly from detected ArUco marker corners
					self.layers[??].aoi_2d_scene |= scene.build_aruco_aoi_scene(self.aruco_detector.detected_markers)

				except ArFeatures.PoseEstimationFailed:

					pass
			'''

			try:

				# Estimate scene markers poses
				self.aruco_detector.estimate_markers_pose(scene.aruco_markers_group.identifiers)

				# Estimate scene pose from detected scene markers
				tvec, rmat, _, _ = scene.estimate_pose(self.aruco_detector.detected_markers)

				# Project scene into camera frame according estimated pose
				for layer_name, layer_projection in scene.project(tvec, rmat):

					try:

						self.layers[layer_name].aoi_scene |= layer_projection

					except KeyError:

						pass

			# Store exceptions and continue
			except Exception as e:

				exceptions[scene_name] = e

		# Unlock camera frame exploitation
		self._frame_lock.release()

		# Return dection time and exceptions
		return detection_time, exceptions

	def __image(self, draw_detected_markers: dict = None, draw_optic_parameters_grid: dict = None, **kwargs) -> numpy.array:
		"""Get frame image with ArUco detection visualisation.

		Parameters:
            draw_detected_markers: ArucoMarker.draw parameters (if None, no marker drawn)
            draw_optic_parameters_grid: OpticParameter.draw parameters (if None, no grid drawn)
            kwargs: ArCamera.image parameters
		"""

		# Can't use camera frame when it is locked
		if self._frame_lock.locked():
			return

		# Lock camera frame exploitation
		self._frame_lock.acquire()

		# Get camera frame image
		image = super().image(**kwargs)

		# Draw detected markers if required
		if draw_detected_markers is not None:

			self.aruco_detector.draw_detected_markers(image, draw_detected_markers)

		# Draw optic parameters grid if required
		if draw_optic_parameters_grid is not None:

			self.aruco_detector.optic_parameters.draw(image, **draw_optic_parameters_grid)

		# Unlock camera frame exploitation
		self._frame_lock.release()

		return image

	def image(self, **kwargs) -> numpy.array:
		"""
		Get frame image.

		Parameters:
			kwargs: ArUcoCamera.__image parameters
		"""

		# Use image_parameters attribute if no kwargs
		if kwargs:

			return self.__image(**kwargs)

		return self.__image(**self.image_parameters)