-
Notifications
You must be signed in to change notification settings - Fork 1
/
pinhole_camera.py
1823 lines (1589 loc) · 54.1 KB
/
pinhole_camera.py
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import division
import copy
import warnings
import numpy as np
import PIL
from PIL import Image
from PIL import ImageDraw
import yaml
try:
import cv2
_cv2_available = True
except ImportError:
_cv2_available = False
def pil_to_cv2_interpolation(interpolation):
if isinstance(interpolation, str):
interpolation = interpolation.lower()
if interpolation == 'nearest':
cv_interpolation = cv2.INTER_NEAREST
elif interpolation == 'bilinear':
cv_interpolation = cv2.INTER_LINEAR
elif interpolation == 'bicubic':
cv_interpolation = cv2.INTER_CUBIC
elif interpolation == 'lanczos':
cv_interpolation = cv2.INTER_LANCZOS4
else:
raise ValueError(
'Not valid Interpolation. '
'Valid interpolation methods are '
'nearest, bilinear, bicubic and lanczos.')
else:
if interpolation == PIL.Image.NEAREST:
cv_interpolation = cv2.INTER_NEAREST
elif interpolation == PIL.Image.BILINEAR:
cv_interpolation = cv2.INTER_LINEAR
elif interpolation == PIL.Image.BICUBIC:
cv_interpolation = cv2.INTER_CUBIC
elif interpolation == PIL.Image.LANCZOS:
cv_interpolation = cv2.INTER_LANCZOS4
else:
raise ValueError(
'Not valid Interpolation. '
'Valid interpolation methods are '
'PIL.Image.NEAREST, PIL.Image.BILINEAR, '
'PIL.Image.BICUBIC and PIL.Image.LANCZOS.')
return cv_interpolation
def format_mat(x, precision):
return ("[%s]" % (
np.array2string(x, precision=precision,
suppress_small=True, separator=", ")
.replace("[", "").replace("]", "").replace("\n", "\n ")))
def get_valid_roi(height, width, roi):
y1, x1, y2, x2 = roi
y1 = max(0, y1)
x1 = max(0, x1)
y2 = min(height, y2)
x2 = min(width, x2)
roi_height = y2 - y1
roi_width = x2 - x1
# ROI with non-positive height or width is
# considered the same as full resolution.
if x1 == 0 and y1 == 0 \
and roi_width == 0 and roi_height == 0:
return [0, 0, height, width]
elif roi_width <= 0 or roi_height <= 0:
warnings.warn(
"Invalid ROI, [left: {}, top: {}, right: {}, bottom: {}]".format(
roi[0], roi[1], roi[2], roi[3]))
return [0, 0, height, width]
else:
return [y1, x1, y2, x2]
class PinholeCameraModel(object):
"""A Pinhole Camera Model
more detail, see http://wiki.ros.org/image_pipeline/CameraInfo
http://docs.ros.org/api/sensor_msgs/html/msg/CameraInfo.html
Parameters
----------
image_height : int
height of camera image.
image_width : int
width of camera image.
K : numpy.ndarray
3x3 intrinsic matrix.
P : numpy.ndarray
3x4 projection matrix
R : numpy.ndarray
3x3 rectification matrix.
D : numpy.ndarray
distortion.
roi : None or list[float]
[top, left, bottom, right] order.
tf_frame : None or str
tf frame. This is for ROS compatibility.
stamp : None
timestamp. This is for ROS compatibility.
distortion_model : str
type of distortion model.
name : None or str
name of this camera.
full_K : numpy.ndarray or None
original intrinsic matrix of full resolution.
If `None`, set copy of K.
full_P : numpy.ndarray or None
original projection matrix of full resolution.
If `None`, set copy of P.
full_height : int or None
This value is indicating original image height.
full_width : int or None
This value is indicating original image width.
"""
def __init__(self,
image_height,
image_width,
K,
P,
R=np.eye(3),
D=np.zeros(5),
roi=None,
tf_frame=None,
stamp=None,
distortion_model='plumb_bob',
name='',
full_K=None,
full_P=None,
full_height=None,
full_width=None,
binning_x=1,
binning_y=1,
target_size=None):
self._width = int(image_width)
self._height = int(image_height)
self._full_width = full_width or self._width
self._full_height = full_height or self._height
self.K = K
self.D = D
self.R = R
self.P = P
self.distortion_model = distortion_model
self.name = name
if full_K is not None:
self._full_K = full_K
else:
self._full_K = self.K.copy()
if full_P is not None:
self._full_P = full_P
else:
self._full_P = self.P.copy()
self._binning_x = binning_x
self._binning_y = binning_y
self._roi = roi or [0, 0, self._height, self._width]
self._target_size = target_size
self.tf_frame = tf_frame
self.stamp = stamp
# finally calculate K and P considering ROI and binning.
self._adjust()
def _adjust(self):
"""Adjust K and P for binning and ROI
"""
y1, x1, y2, x2 = self.roi
K = self.full_K.copy()
P = self.full_P.copy()
# Adjust K and P for binning and ROI
if self._target_size is not None:
self._binning_x = (x2 - x1) / self._target_size[0]
self._binning_y = (y2 - y1) / self._target_size[1]
K[0, 0] /= self._binning_x
K[1, 1] /= self._binning_y
K[0, 2] = (K[0, 2] - x1) / self._binning_x
K[1, 2] = (K[1, 2] - y1) / self._binning_y
P[0, 0] /= self._binning_x
P[1, 1] /= self._binning_y
P[0, 2] = (P[0, 2] - x1) / self._binning_x
P[1, 2] = (P[1, 2] - y1) / self._binning_y
self.K = K
self.P = P
self._width = x2 - x1
self._height = y2 - y1
self._aspect = 1.0 * self.width / self.height
self._fovx = 2.0 * np.rad2deg(np.arctan(self.width / (2.0 * self.fx)))
self._fovy = 2.0 * np.rad2deg(np.arctan(self.height / (2.0 * self.fy)))
self.mapx = np.ndarray(shape=(self.height, self.width, 1),
dtype='float32')
self.mapy = np.ndarray(shape=(self.height, self.width, 1),
dtype='float32')
cv2.initUndistortRectifyMap(
self.K, self.D, self.R, self.P,
(self.width, self.height),
cv2.CV_32FC1, self.mapx, self.mapy)
@property
def width(self):
"""Returns image width
Returns
-------
self._width : int
image width
"""
return self._width
@width.setter
def width(self, width):
"""Setter of image width
Parameters
----------
width : float
image width of this camera
"""
if width <= 0:
raise ValueError
self._width = width
self._fovx = 2.0 * np.rad2deg(np.arctan(self.width / (2.0 * self.fx)))
self._aspect = 1.0 * self.width / self.height
@property
def height(self):
"""Returns image height
Returns
-------
self._height : int
image height
"""
return self._height
@height.setter
def height(self, height):
"""Setter of image height
Parameters
----------
height : float
image height of this camera
"""
if height <= 0:
raise ValueError
self._height = height
self._fovy = 2.0 * np.rad2deg(np.arctan(self.height / (2.0 * self.fy)))
self._aspect = 1.0 * self.width / self.height
@property
def aspect(self):
"""Return aspect ratio
Returns
-------
self._aspect : float
ascpect ratio of this camera.
"""
return self._aspect
@property
def cx(self):
"""Returns x center
Returns
-------
cx : numpy.float32
"""
return self.P[0, 2]
@property
def cy(self):
"""Returns y center
Returns
-------
cy : numpy.float32
"""
return self.P[1, 2]
@property
def fx(self):
"""Returns x focal length
Returns
-------
fx : numpy.float32
"""
return self.P[0, 0]
@property
def fy(self):
"""Returns y focal length
Returns
-------
fy : numpy.float32
"""
return self.P[1, 1]
@property
def Tx(self):
"""Return Tx.
For monocular cameras, Tx = Ty = Tz = 0.
For a stereo pair, the fourth column [Tx Ty Tz]' is related to the
position of the optical center of the second camera in the first
camera's frame.
Returns
-------
Tx : numpy.float32
"""
return self.P[0, 3]
@property
def Ty(self):
"""Return Ty.
For monocular cameras, Tx = Ty = Tz = 0.
For a stereo pair, the fourth column [Tx Ty Tz]' is related to the
position of the optical center of the second camera in the first
camera's frame.
Returns
-------
Ty : numpy.float32
"""
return self.P[1, 3]
@property
def Tz(self):
"""Return Tz.
For monocular cameras, Tx = Ty = Tz = 0.
For a stereo pair, the fourth column [Tx Ty Tz]' is related to the
position of the optical center of the second camera in the first
camera's frame.
Returns
-------
Tz : numpy.float32
"""
return self.P[2, 3]
@property
def fov(self):
"""Property of fov.
Returns
-------
fov : tuple(float)
tuple of (fovx, fovy).
"""
return (self._fovx, self._fovy)
@property
def fovx(self):
"""Property of horizontal fov.
Returns
-------
self._fovx : float
horizontal fov of this camera.
"""
return self._fovx
@property
def fovy(self):
"""Property of vertical fov.
Returns
-------
self._fovy : float
vertical fov of this camera.
"""
return self._fovy
def get_camera_matrix(self):
"""Return camera matrix
Returns
-------
camera_matrix : numpy.ndarray
camera matrix from Projection matrix.
"""
return self.P[:3, :3]
@property
def K(self):
"""Intrinsic camera matrix for the raw (distorted) images.
.. math::
K = \\left(
\\begin{array}{ccc}
f_x & 0 & c_x \\\\
0 & f_y & c_y \\\\
0 & 0 & 1
\\end{array}
\\right)
Projects 3D points in the camera coordinate frame to 2D pixel
coordinates using the focal lengths (fx, fy) and principal point
(cx, cy).
Returns
-------
self._K : numpy.ndarray
3x3 intrinsic matrix.
"""
return self._K
@K.setter
def K(self, k):
self._K = np.array(k, dtype=np.float32).reshape(3, 3)
@property
def K_inv(self):
"""Inverse of Intrinsic camera matrix for the raw (distorted) images.
.. math::
K^{-1} = \\left(
\\begin{array}{ccc}
1 / f_x & 0 & - c_x / f_x \\\\
0 & 1 / f_y & - c_y / f_y \\\\
0 & 0 & 1
\\end{array}
\\right)
Projects 3D points in the camera coordinate frame to 2D pixel
coordinates using the focal lengths (fx, fy) and principal point
(cx, cy).
Returns
-------
self._K : numpy.ndarray
3x3 intrinsic matrix.
"""
return np.array([
[1.0 / self.fx, 0, - self.cx / self.fx],
[0, 1.0 / self.fy, - self.cy / self.fy],
[0, 0, 1]])
@property
def P(self):
"""Projection camera_matrix
By convention, this matrix specifies the intrinsic
(camera) matrix of the processed (rectified) image.
.. math::
P = \\left(
\\begin{array}{cccc}
{f_x}' & 0 & {c_x}' & T_x \\\\
0 & {f_y}' & {c_y}' & T_y \\\\
0 & 0 & 1 & 0
\\end{array}
\\right)
Returns
-------
self._P : numpy.ndarray
4x3 projection matrix.
"""
return self._P
@P.setter
def P(self, p):
self._P = np.array(p, dtype=np.float32).reshape(3, 4)
self._fovx = 2.0 * np.rad2deg(np.arctan(self.width / (2.0 * self.fx)))
self._fovy = 2.0 * np.rad2deg(np.arctan(self.height / (2.0 * self.fy)))
@property
def R(self):
"""Rectification matrix (stereo cameras only)
A rotation matrix aligning the camera coordinate system to the ideal
stereo image plane so that epipolar lines in both stereo images are
parallel.
Returns
-------
self._R : numpy.ndarray
rectification matrix.
"""
return self._R
@R.setter
def R(self, r):
self._R = np.array(r, dtype=np.float32).reshape(3, 3)
@property
def D(self):
"""Property of distortion parameters
The distortion parameters, size depending on the distortion model.
For "plumb_bob", the 5 parameters are: (k1, k2, t1, t2, k3).
Returns
-------
self._D : numpy.ndarray
distortion array.
"""
return self._D
@D.setter
def D(self, d):
self._D = np.array(d, dtype=np.float32)
@property
def full_K(self):
"""Return the original camera matrix for full resolution
Returns
-------
self.full_K : numpy.ndarray
intrinsic matrix.
"""
return self._full_K
@property
def full_P(self):
"""Return the projection matrix for full resolution
Returns
-------
self.full_P : numpy.ndarray
projection matrix.
"""
return self._full_P
@property
def binning_x(self):
"""Return number of pixels to decimate to one horizontally.
Returns
-------
self._binning_x : int
binning x.
"""
return self._binning_x
@binning_x.setter
def binning_x(self, binning_x):
"""Setter of binning_x
Note that this setter internally changes target_size, K and P.
Parameters
-----------
binning_x : float
decimation value.
"""
if binning_x <= 0:
raise ValueError("binning should be greater than 0.")
self._binning_x = binning_x
roi_width = self.roi[3] - self.roi[1]
_, target_height = self._target_size
target_width = int(roi_width / binning_x)
self._binning_x = roi_width / target_width
self._target_size = (target_width, target_height)
self._adjust()
@property
def binning_y(self):
"""Return number of pixels to decimate to one vertically.
Returns
-------
self._binning_y : int
binning y.
"""
return self._binning_y
@binning_y.setter
def binning_y(self, binning_y):
"""Setter of binning_y
Note that this setter internally changes target_size, K and P.
Parameters
-----------
binning_y : float
decimation value.
"""
if binning_y <= 0:
raise ValueError("binning should be greater than 0.")
self._binning_y = binning_y
roi_height = self.roi[2] - self.roi[0]
target_width, _ = self._target_size
target_height = int(roi_height / binning_y)
self._binning_y = roi_height / target_height
self._target_size = (target_width, target_height)
self._adjust()
@property
def target_size(self):
"""Return target_size
Returns
-------
self._target_size : None or tuple(int)
(width, height).
If this value is `None`, target size is not specified.
"""
return self._target_size
@target_size.setter
def target_size(self, target_size):
"""Setter of target_size
This setter internally changes value of binning_x, binning_y, K and P.
Parameters
----------
target_size : tuple(int)
(width, height)
"""
if len(target_size) != 2:
raise ValueError('target_size length should be 2')
roi_height = self.roi[2] - self.roi[0]
roi_width = self.roi[3] - self.roi[1]
self._binning_x = roi_width / target_size[0]
self._binning_y = roi_height / target_size[1]
self._target_size = target_size
self._adjust()
@property
def roi(self):
"""Return roi
Returns
-------
self._roi : None or list[float]
[top, left, bottom, right] order.
"""
return self._roi
@roi.setter
def roi(self, roi):
"""Setter of roi.
Parameters
----------
roi : list[float]
[top, left, bottom, right] order.
"""
self._roi = get_valid_roi(self._full_height, self._full_width, roi)
self._adjust()
@property
def open3d_intrinsic(self):
"""Return open3d.camera.PinholeCameraIntrinsic instance.
Returns
-------
intrinsic : open3d.camera.PinholeCameraIntrinsic
open3d PinholeCameraIntrinsic
"""
try:
import open3d
except ImportError:
raise RuntimeError(
"Open3d is not installed. Please install Open3d")
intrinsic = open3d.camera.PinholeCameraIntrinsic(
self.width,
self.height,
self.fx,
self.fy,
self.cx,
self.cy)
return intrinsic
@staticmethod
def calc_fovx(fovy, height, width):
"""Return fovx from fovy, height and width.
Parameters
----------
fovy : float
field of view in degree.
height : int
height of camera.
width : int
width of camera.
Returns
-------
fovx : float
calculated fovx.
"""
aspect = 1.0 * width / height
fovx = np.rad2deg(2 * np.arctan(
np.tan(0.5 * np.deg2rad(fovy)) * aspect))
return fovx
@staticmethod
def calc_fovy(fovx, height, width):
"""Return fovy from fovx, height and width.
Parameters
----------
fovx : float
horizontal field of view in degree.
height : int
height of camera.
width : int
width of camera.
Returns
-------
fovy : float
calculated fovy.
"""
aspect = 1.0 * width / height
fovy = np.rad2deg(
2 * np.arctan(
np.tan(0.5 * np.deg2rad(fovx)) / aspect))
return fovy
@staticmethod
def calc_f_from_fov(fov, aperture):
"""Return focal length.
Parameters
----------
fov : float
field of view in degree.
aperture : float
aperture.
Returns
-------
focal_length : float
calculated focal length.
"""
return aperture / (2.0 * np.tan(np.deg2rad(fov / 2.0)))
@staticmethod
def from_fov(fovy, height, width, **kwargs):
"""Return PinholeCameraModel from fovy.
Parameters
----------
fovy : float
vertical field of view in degree.
height : int
height of camera.
width : int
width of camera.
Returns
-------
cameramodel : cameramodels.PinholeCameraModel
camera model
"""
return PinholeCameraModel.from_fovy(fovy, height, width, **kwargs)
@staticmethod
def from_fovx(fovx, height, width, **kwargs):
"""Return PinholeCameraModel from fovx.
Parameters
----------
fovx : float
horizontal field of view in degree.
height : int
height of camera.
width : int
width of camera.
Returns
-------
cameramodel : cameramodels.PinholeCameraModel
camera model
"""
fovy = PinholeCameraModel.calc_fovy(fovx, height, width)
fy = PinholeCameraModel.calc_f_from_fov(fovy, height)
fx = PinholeCameraModel.calc_f_from_fov(fovx, width)
K = [fx, 0, width / 2.0,
0, fy, height / 2.0,
0, 0, 1]
P = [fx, 0, width / 2.0, 0,
0, fy, height / 2.0, 0,
0, 0, 1, 0]
return PinholeCameraModel(
image_height=height,
image_width=width,
K=K,
P=P,
**kwargs)
@staticmethod
def from_fovy(fovy, height, width, **kwargs):
"""Return PinholeCameraModel from fovy.
Parameters
----------
fovy : float
vertical field of view in degree.
height : int
height of camera.
width : int
width of camera.
Returns
-------
cameramodel : cameramodels.PinholeCameraModel
camera model
"""
fovx = PinholeCameraModel.calc_fovx(fovy, height, width)
fy = PinholeCameraModel.calc_f_from_fov(fovy, height)
fx = PinholeCameraModel.calc_f_from_fov(fovx, width)
K = [fx, 0, width / 2.0,
0, fy, height / 2.0,
0, 0, 1]
P = [fx, 0, width / 2.0, 0,
0, fy, height / 2.0, 0,
0, 0, 1, 0]
return PinholeCameraModel(
image_height=height,
image_width=width,
K=K,
P=P,
**kwargs)
@staticmethod
def from_open3d_intrinsic(open3d_pinhole_intrinsic):
"""Return PinholeCameraModel from open3d's pinhole camera intrinsic.
Parameters
----------
open3d_pinhole_intrinsic : open3d.camera.PinholeCameraIntrinsic
open3d PinholeCameraIntrinsic
Returns
-------
cameramodel : cameramodels.PinholeCameraModel
camera model
"""
width = open3d_pinhole_intrinsic.width
height = open3d_pinhole_intrinsic.height
K = open3d_pinhole_intrinsic.intrinsic_matrix
P = np.zeros((3, 4), dtype=np.float64)
P[:3, :3] = K.copy()
return PinholeCameraModel(height, width, K, P)
@staticmethod
def from_intrinsic_matrix(intrinsic_matrix, height, width,
**kwargs):
"""Return PinholeCameraModel from intrinsic_matrix.
Parameters
----------
intrinsic_matrix : numpy.ndarray
[3, 3] intrinsic matrix.
height : int
height of camera.
width : int
width of camera.
kwargs : dict
keyword args. These values are passed to
cameramodels.PinholeCameraModel
Returns
-------
cameramodel : cameramodels.PinholeCameraModel
camera model
"""
K = np.array(intrinsic_matrix, dtype=np.float64)
P = np.zeros((3, 4), dtype=np.float64)
P[:3, :3] = K.copy()
return PinholeCameraModel(height, width, K, P,
**kwargs)
@staticmethod
def from_yaml_file(filename):
"""Create instance of PinholeCameraModel from yaml file.
This function is supporting OpenCV calibration program's
YAML format and sensor_msgs/CameraInfo's YAML format in ROS.
Parameters
----------
filename : str
path of yaml file.
Returns
-------
cameramodel : cameramodels.PinholeCameraModel
camera model
"""
with open(filename, 'r') as f:
data = yaml.load(f, Loader=yaml.FullLoader)
roi = None
binning_x = 1
binning_y = 1
if 'image_width' in data:
# opencv format
image_width = data['image_width']
image_height = data['image_height']
K = np.array(
data['camera_matrix']['data'],
dtype=np.float32).reshape(3, 3)
P = np.array(
data['projection_matrix']['data'],
dtype=np.float32).reshape(3, 4)
R = np.array(
data['rectification_matrix']['data'],
dtype=np.float32).reshape(3, 3)
D = np.array(
data['distortion_coefficients']['data'],
dtype=np.float32)
distortion_model = 'plumb_bob'
if 'camera_name' in data:
name = data['camera_name'] or ''
else:
name = ''
elif 'width' in data:
# ROS yaml format
image_width = data['width']
image_height = data['height']
K = np.array(
data['K'],
dtype=np.float32).reshape(3, 3)
P = np.array(
data['P'],
dtype=np.float32).reshape(3, 4)
R = np.array(
data['R'],
dtype=np.float32).reshape(3, 3)
D = np.array(
data['D'],
dtype=np.float32)
distortion_model = data['distortion_model']
name = ''
else:
raise RuntimeError("Not supported YAML file.")
if 'binning_x' in data:
binning_x = 1 if data['binning_x'] == 0 else data['binning_x']
if 'binning_y' in data:
binning_y = 1 if data['binning_y'] == 0 else data['binning_y']
roi_width = image_width
roi_height = image_height
if 'roi' in data:
x_offset = data['roi']['x_offset']
y_offset = data['roi']['y_offset']
roi_width = data['roi']['width']
roi_height = data['roi']['height']
roi = get_valid_roi(
image_height, image_width,
[y_offset,
x_offset,
y_offset + roi_height,
x_offset + roi_width])
roi_width = roi[3] - roi[1]
roi_height = roi[2] - roi[0]
full_K = K.copy()
full_P = P.copy()
return PinholeCameraModel(
roi_height, roi_width,
K, P, R, D,
roi=roi,
distortion_model=distortion_model,
name=name,
full_K=full_K,
full_P=full_P,
full_width=image_width,
full_height=image_height,
binning_x=binning_x,
binning_y=binning_y)
@staticmethod
def from_camera_info(camera_info_msg):
"""Return PinholeCameraModel from camera_info_msg
Parameters
----------
camera_info_msg : sensor_msgs.msg.CameraInfo
message of camera info.