aboutsummaryrefslogtreecommitdiff
path: root/src/argaze/ArUcoMarker/ArUcoOpticCalibrator.py
blob: 6b2a74cb77a2e8acaed20a60c4dfe5deb7ddb967 (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
""" """

"""
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"

from dataclasses import dataclass, field

from argaze import DataFeatures
from argaze.ArUcoMarker import ArUcoBoard

import json
import numpy
import cv2
import cv2.aruco as aruco


def K0(focal_length: tuple, width: int, height: int) -> numpy.array:
	"""Define default optic intrinsic parameters' matrix.

    Parameters:
        focal_length:
        width: in pixel.
        height: in pixel.
    """

	return numpy.array([[focal_length[0], 0., width / 2], [0., focal_length[1], height / 2], [0., 0., 1.]])


D0 = numpy.array([0.0, 0.0, 0.0, 0.0, 0.0])
"""Define default optic distortion coefficients vector."""


@dataclass
class OpticParameters():
	"""Define optic parameters output by optic calibrator."""

	rms: float = field(default=0)
	"""Root Mean Square error of calibration."""

	dimensions: numpy.array = field(default_factory=lambda: numpy.array([0, 0]))
	"""Image dimensions in pixels from which the calibration have been done."""

	K: numpy.array = field(default_factory=lambda: K0((0, 0), 0, 0))
	"""Intrinsic parameters matrix (focal lengths and principal point)."""

	D: numpy.array = field(default_factory=lambda: D0)
	"""Distortion coefficients vector."""

	@classmethod
	def from_json(cls, json_filepath):
		"""Load optical parameters from .json file."""

		with open(json_filepath) as calibration_file:
			return OpticParameters(**json.load(calibration_file))

	def to_json(self, json_filepath):
		"""Save optical parameters into .json file."""

		with open(json_filepath, 'w', encoding='utf-8') as calibration_file:
			json.dump(self, calibration_file, ensure_ascii=False, indent=4, cls=DataFeatures.JsonEncoder)

	def __str__(self) -> str:
		"""String display"""

		output = f'\trms: {self.rms}\n'
		output += f'\tdimensions: {self.dimensions}\n'
		output += f'\tK: {self.K}\n'
		output += f'\tD: {self.D}\n'

		return output

	def draw(self, image: numpy.array, width: float = 0., height: float = 0., z: float = 0., point_size: int = 1,
	         point_color: tuple = (0, 0, 0)):
		"""Draw grid to display K and D"""

		if width * height > 0.:

			# Edit 3D grid
			grid_3D = []
			for x in range(-int(width / 2), int(width / 2)):
				for y in range(-int(height / 2), int(height / 2)):
					grid_3D.append([x, y, z])

			# Project 3d grid
			grid_2D, _ = cv2.projectPoints(numpy.array(grid_3D).astype(float), numpy.array([0., 0., 0.]),
			                               numpy.array([0., 0., 0.]), numpy.array(self.K), -numpy.array(self.D))

			# Draw projection
			for point in grid_2D:

				# Ignore point out field
				try:

					cv2.circle(image, point.astype(int)[0], point_size, point_color, -1)

				except:

					pass


class ArUcoOpticCalibrator():
	"""Handle optic calibration process."""

	def __init__(self):

		# Calibration data
		self.__corners_set_number = 0
		self.__corners_set = []
		self.__corners_set_ids = []

	def calibrate(self, board: ArUcoBoard.ArUcoBoard, dimensions: list = None) -> OpticParameters:
		"""Retrieve K and D parameters from stored calibration data.

		Parameters:
			board: [ArUcoBoard](argaze.md/#argaze.ArUcoMarker.ArUcoBoard.ArUcoBoard) instance
			dimensions: camera image dimensions

		Returns:
			Optic parameters
		"""

		if dimensions is None:
			dimensions = [0, 0]

		if self.__corners_set_number > 0:
			rms, K, D, r, t = aruco.calibrateCameraCharuco(self.__corners_set, self.__corners_set_ids, board.model,
			                                               dimensions, None, None)

			return OpticParameters(rms, dimensions, K, D)

	def reset_calibration_data(self):
		"""Clear all calibration data."""

		self.__corners_set_number = 0
		self.__corners_set = []
		self.__corners_set_ids = []

	def store_calibration_data(self, corners, corners_identifiers):
		"""Store calibration data."""

		self.__corners_set_number += 1
		self.__corners_set.append(corners)
		self.__corners_set_ids.append(corners_identifiers)

	@property
	def calibration_data_count(self) -> int:
		"""Get how much calibration data are stored."""

		return self.__corners_set_number