aboutsummaryrefslogtreecommitdiff
path: root/src/argaze/ArUcoMarker/ArUcoCamera.py
blob: 8ae8cb8fa3f9556cf63827198488504c08eed612 (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
"""ArCamera based of ArUco markers technology."""

"""
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <https://www.gnu.org/licenses/>.
"""

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

import logging

import cv2
import numpy

from argaze import ArFeatures, DataFeatures
from argaze.ArUcoMarker import ArUcoDetector, ArUcoOpticCalibrator, ArUcoScene
from argaze.AreaOfInterest import AOI2DScene

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


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

	@DataFeatures.PipelineStepInit
	def __init__(self, **kwargs):
		"""Initialize ArUcoCamera"""

		# Init ArCamera class
		super().__init__()

		# Init private attribute
		self.__aruco_detector = None
		self.__sides_mask = 0

		# Init protected attributes
		self._image_parameters = {**ArFeatures.DEFAULT_ARFRAME_IMAGE_PARAMETERS, **DEFAULT_ARUCOCAMERA_IMAGE_PARAMETERS}

	@property
	def aruco_detector(self) -> ArUcoDetector.ArUcoDetector:
		"""ArUco marker detector."""
		return self.__aruco_detector

	@aruco_detector.setter
	@DataFeatures.PipelineStepAttributeSetter
	def aruco_detector(self, aruco_detector: ArUcoDetector.ArUcoDetector):

		self.__aruco_detector = aruco_detector

		# 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 DataFeatures.PipelineStepLoadingFail('ArUcoCamera: aruco_detector.optic_parameters.dimensions have to be equal to size.')

		# No optic parameters loaded
		else:

			# Create default optic parameters adapted to frame size
			# Note: The choice of 1000 for default focal length should be discussed...
			self.__aruco_detector.optic_parameters = ArUcoOpticCalibrator.OpticParameters(rms=-1, dimensions=self.size, K=ArUcoOpticCalibrator.K0(focal_length=(1000., 1000.), width=self.size[0], height=self.size[1]))

		# Edit parent
		if self.__aruco_detector is not None:
			self.__aruco_detector.parent = self

	@property
	def sides_mask(self) -> int:
		"""Size of mask (pixel) to hide video left and right sides."""
		return self.__sides_mask

	@sides_mask.setter
	def sides_mask(self, size: int):

		self.__sides_mask = size

	@ArFeatures.ArCamera.scenes.setter
	@DataFeatures.PipelineStepAttributeSetter
	def scenes(self, scenes: dict):

		self._scenes = {}

		for scene_name, scene_data in scenes.items():
			self._scenes[scene_name] = ArUcoScene.ArUcoScene(name=scene_name, **scene_data)

		# Edit parent
		for name, scene in self._scenes.items():
			scene.parent = self

		# Update expected and excluded aoi
		self._update_expected_and_excluded_aoi()

	@DataFeatures.PipelineStepMethod
	@DataFeatures.PipelineStepExecutionTime
	def watch(self, image: DataFeatures.TimestampedImage):
		"""Detect environment aruco markers from image and project scenes into camera frame."""

		logging.debug('ArUcoCamera.watch')

		# Use camera frame lock feature
		with self._lock:

			# Draw black rectangles to mask sides
			if self.__sides_mask > 0:
				logging.debug('\t> drawing sides mask (%i px)', self.__sides_mask)

				height, width, _ = image.shape

				cv2.rectangle(image, (0, 0), (self.__sides_mask, height), (0, 0, 0), -1)
				cv2.rectangle(image, (width - self.__sides_mask, 0), (width, height), (0, 0, 0), -1)

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

			# Read projection from the cache if required
			if not self._read_projection_cache(image.timestamp):

				# Detect aruco markers
				logging.debug('\t> detect markers')

				self.__aruco_detector.detect_markers(image)

				# Clear former layers projection into camera frame
				self._clear_projection()

				# 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
					'''

					# Estimate scene pose from detected scene markers
					logging.debug('\t> estimate %s scene pose', scene_name)

					try:

						tvec, rmat, _ = scene.estimate_pose(self.__aruco_detector.detected_markers(), timestamp=image.timestamp)

						# Project scene into camera frame according estimated pose
						for layer_name, layer_projection in scene.project(tvec, rmat, self.visual_hfov, self.visual_vfov, timestamp=image.timestamp):

							logging.debug('\t> project %s scene %s layer', scene_name, layer_name)

							try:

								# Update camera layer aoi
								self.layers[layer_name].aoi_scene |= layer_projection

								# Timestamp camera layer
								self.layers[layer_name].timestamp = image.timestamp

							except KeyError:

								pass

						# Write projection into the cache if required
						self._write_projection_cache(image.timestamp)

					except DataFeatures.TimestampedException as e:

						# Write exception into the cache if required
						self._write_projection_cache(image.timestamp, e)

						# Raise exception
						raise e

			# Copy camera frame background into scene frames background if required
			if self.copy_background_into_scenes_frames:

				self._copy_background_into_scenes_frames()

	@DataFeatures.PipelineStepImage
	@DataFeatures.PipelineStepExecutionTime
	def image(self, draw_detected_markers: dict = None, draw_scenes: dict = None,
	          draw_optic_parameters_grid: dict = None, **kwargs: dict) -> numpy.array:
		"""Get frame image with ArUco detection visualization.

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

		logging.debug('ArUcoCamera.image %s', self.name)

		# Get camera frame image
		# Note: don't lock/unlock camera frame here as super().image manage it.
		image = super().image(**kwargs)

		# Use frame lock feature
		with self._lock:

			# Draw optic parameters grid if required
			if draw_optic_parameters_grid is not None:
				logging.debug('\t> drawing optic parameters')

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

			# Draw scenes if required
			if draw_scenes is not None:

				for scene_name, draw_scenes_parameters in draw_scenes.items():
					logging.debug('\t> drawing %s scene', scene_name)

					self.scenes[scene_name].draw(image, **draw_scenes_parameters)

			# Draw detected markers if required
			if draw_detected_markers is not None:
				logging.debug('\t> drawing detected markers')

				self.__aruco_detector.draw_detected_markers(image, draw_detected_markers)

		return image