-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathneuralangelo_addon.py
1574 lines (1278 loc) · 56.9 KB
/
neuralangelo_addon.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
import collections
import json
import os
import shutil
import struct
import bmesh
import bpy
import math
import numpy as np
from bpy.props import (StringProperty,
BoolProperty,
FloatProperty,
FloatVectorProperty,
PointerProperty,
)
from bpy.types import (Operator,
PropertyGroup,
)
from mathutils import Matrix
from typing import Union
# ------------------------------------------------------------------------
# COLMAP code: https://github.com/colmap/colmap/blob/dev/scripts/python/read_write_model.py
# ------------------------------------------------------------------------
CameraModel = collections.namedtuple(
"CameraModel", ["model_id", "model_name", "num_params"])
Camera = collections.namedtuple(
"Camera", ["id", "model", "width", "height", "params"])
BaseImage = collections.namedtuple(
"Image", ["id", "qvec", "tvec", "camera_id", "name", "xys", "point3D_ids"])
Point3D = collections.namedtuple(
"Point3D", ["id", "xyz", "rgb", "error", "image_ids", "point2D_idxs"])
class Image(BaseImage):
def qvec2rotmat(self):
return qvec2rotmat(self.qvec)
CAMERA_MODELS = {
CameraModel(model_id=0, model_name="SIMPLE_PINHOLE", num_params=3),
CameraModel(model_id=1, model_name="PINHOLE", num_params=4),
CameraModel(model_id=2, model_name="SIMPLE_RADIAL", num_params=4),
CameraModel(model_id=3, model_name="RADIAL", num_params=5),
CameraModel(model_id=4, model_name="OPENCV", num_params=8),
CameraModel(model_id=5, model_name="OPENCV_FISHEYE", num_params=8),
CameraModel(model_id=6, model_name="FULL_OPENCV", num_params=12),
CameraModel(model_id=7, model_name="FOV", num_params=5),
CameraModel(model_id=8, model_name="SIMPLE_RADIAL_FISHEYE", num_params=4),
CameraModel(model_id=9, model_name="RADIAL_FISHEYE", num_params=5),
CameraModel(model_id=10, model_name="THIN_PRISM_FISHEYE", num_params=12)
}
CAMERA_MODEL_IDS = dict([(camera_model.model_id, camera_model)
for camera_model in CAMERA_MODELS])
CAMERA_MODEL_NAMES = dict([(camera_model.model_name, camera_model)
for camera_model in CAMERA_MODELS])
def read_next_bytes(fid, num_bytes, format_char_sequence, endian_character="<"):
"""Read and unpack the next bytes from a binary file.
:param fid:
:param num_bytes: Sum of combination of {2, 4, 8}, e.g. 2, 6, 16, 30, etc.
:param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}.
:param endian_character: Any of {@, =, <, >, !}
:return: Tuple of read and unpacked values.
"""
data = fid.read(num_bytes)
return struct.unpack(endian_character + format_char_sequence, data)
def read_cameras_text(path):
"""
see: src/base/reconstruction.cc
void Reconstruction::WriteCamerasText(const std::string& path)
void Reconstruction::ReadCamerasText(const std::string& path)
"""
cameras = {}
with open(path, "r") as fid:
while True:
line = fid.readline()
if not line:
break
line = line.strip()
if len(line) > 0 and line[0] != "#":
elems = line.split()
camera_id = int(elems[0])
model = elems[1]
width = int(elems[2])
height = int(elems[3])
params = np.array(tuple(map(float, elems[4:])))
cameras[camera_id] = Camera(id=camera_id, model=model,
width=width, height=height,
params=params)
return cameras
def read_cameras_binary(path_to_model_file):
"""
see: src/base/reconstruction.cc
void Reconstruction::WriteCamerasBinary(const std::string& path)
void Reconstruction::ReadCamerasBinary(const std::string& path)
"""
cameras = {}
with open(path_to_model_file, "rb") as fid:
num_cameras = read_next_bytes(fid, 8, "Q")[0]
for _ in range(num_cameras):
camera_properties = read_next_bytes(
fid, num_bytes=24, format_char_sequence="iiQQ")
camera_id = camera_properties[0]
model_id = camera_properties[1]
model_name = CAMERA_MODEL_IDS[camera_properties[1]].model_name
width = camera_properties[2]
height = camera_properties[3]
num_params = CAMERA_MODEL_IDS[model_id].num_params
params = read_next_bytes(fid, num_bytes=8 * num_params,
format_char_sequence="d" * num_params)
cameras[camera_id] = Camera(id=camera_id,
model=model_name,
width=width,
height=height,
params=np.array(params))
assert len(cameras) == num_cameras
return cameras
def read_images_text(path):
"""
see: src/base/reconstruction.cc
void Reconstruction::ReadImagesText(const std::string& path)
void Reconstruction::WriteImagesText(const std::string& path)
"""
images = {}
with open(path, "r") as fid:
while True:
line = fid.readline()
if not line:
break
line = line.strip()
if len(line) > 0 and line[0] != "#":
elems = line.split()
image_id = int(elems[0])
qvec = np.array(tuple(map(float, elems[1:5])))
tvec = np.array(tuple(map(float, elems[5:8])))
camera_id = int(elems[8])
image_name = elems[9]
elems = fid.readline().split()
xys = np.column_stack([tuple(map(float, elems[0::3])),
tuple(map(float, elems[1::3]))])
point3D_ids = np.array(tuple(map(int, elems[2::3])))
images[image_id] = Image(
id=image_id, qvec=qvec, tvec=tvec,
camera_id=camera_id, name=image_name,
xys=xys, point3D_ids=point3D_ids)
return images
def read_images_binary(path_to_model_file):
"""
see: src/base/reconstruction.cc
void Reconstruction::ReadImagesBinary(const std::string& path)
void Reconstruction::WriteImagesBinary(const std::string& path)
"""
images = {}
with open(path_to_model_file, "rb") as fid:
num_reg_images = read_next_bytes(fid, 8, "Q")[0]
for _ in range(num_reg_images):
binary_image_properties = read_next_bytes(
fid, num_bytes=64, format_char_sequence="idddddddi")
image_id = binary_image_properties[0]
qvec = np.array(binary_image_properties[1:5])
tvec = np.array(binary_image_properties[5:8])
camera_id = binary_image_properties[8]
image_name = ""
current_char = read_next_bytes(fid, 1, "c")[0]
while current_char != b"\x00": # look for the ASCII 0 entry
image_name += current_char.decode("utf-8")
current_char = read_next_bytes(fid, 1, "c")[0]
num_points2D = read_next_bytes(fid, num_bytes=8,
format_char_sequence="Q")[0]
x_y_id_s = read_next_bytes(fid, num_bytes=24 * num_points2D,
format_char_sequence="ddq" * num_points2D)
xys = np.column_stack([tuple(map(float, x_y_id_s[0::3])),
tuple(map(float, x_y_id_s[1::3]))])
point3D_ids = np.array(tuple(map(int, x_y_id_s[2::3])))
images[image_id] = Image(
id=image_id, qvec=qvec, tvec=tvec,
camera_id=camera_id, name=image_name,
xys=xys, point3D_ids=point3D_ids)
return images
def read_points3D_text(path):
"""
see: src/base/reconstruction.cc
void Reconstruction::ReadPoints3DText(const std::string& path)
void Reconstruction::WritePoints3DText(const std::string& path)
"""
points3D = {}
with open(path, "r") as fid:
while True:
line = fid.readline()
if not line:
break
line = line.strip()
if len(line) > 0 and line[0] != "#":
elems = line.split()
point3D_id = int(elems[0])
xyz = np.array(tuple(map(float, elems[1:4])))
rgb = np.array(tuple(map(int, elems[4:7])))
error = float(elems[7])
image_ids = np.array(tuple(map(int, elems[8::2])))
point2D_idxs = np.array(tuple(map(int, elems[9::2])))
points3D[point3D_id] = Point3D(id=point3D_id, xyz=xyz, rgb=rgb,
error=error, image_ids=image_ids,
point2D_idxs=point2D_idxs)
return points3D
def read_points3D_binary(path_to_model_file):
"""
see: src/base/reconstruction.cc
void Reconstruction::ReadPoints3DBinary(const std::string& path)
void Reconstruction::WritePoints3DBinary(const std::string& path)
"""
points3D = {}
with open(path_to_model_file, "rb") as fid:
num_points = read_next_bytes(fid, 8, "Q")[0]
for _ in range(num_points):
binary_point_line_properties = read_next_bytes(
fid, num_bytes=43, format_char_sequence="QdddBBBd")
point3D_id = binary_point_line_properties[0]
xyz = np.array(binary_point_line_properties[1:4])
rgb = np.array(binary_point_line_properties[4:7])
error = np.array(binary_point_line_properties[7])
track_length = read_next_bytes(
fid, num_bytes=8, format_char_sequence="Q")[0]
track_elems = read_next_bytes(
fid, num_bytes=8 * track_length,
format_char_sequence="ii" * track_length)
image_ids = np.array(tuple(map(int, track_elems[0::2])))
point2D_idxs = np.array(tuple(map(int, track_elems[1::2])))
points3D[point3D_id] = Point3D(
id=point3D_id, xyz=xyz, rgb=rgb,
error=error, image_ids=image_ids,
point2D_idxs=point2D_idxs)
return points3D
def detect_model_format(path, ext):
if os.path.isfile(os.path.join(path, "cameras" + ext)) and \
os.path.isfile(os.path.join(path, "images" + ext)) and \
os.path.isfile(os.path.join(path, "points3D" + ext)):
print("Detected model format: '" + ext + "'")
return True
return False
def read_model(path, ext=""):
# try to detect the extension automatically
if ext == "":
if detect_model_format(path, ".bin"):
ext = ".bin"
elif detect_model_format(path, ".txt"):
ext = ".txt"
else:
print("Provide model format: '.bin' or '.txt'")
return
if ext == ".txt":
cameras = read_cameras_text(os.path.join(path, "cameras" + ext))
images = read_images_text(os.path.join(path, "images" + ext))
points3D = read_points3D_text(os.path.join(path, "points3D") + ext)
else:
cameras = read_cameras_binary(os.path.join(path, "cameras" + ext))
images = read_images_binary(os.path.join(path, "images" + ext))
points3D = read_points3D_binary(os.path.join(path, "points3D") + ext)
return cameras, images, points3D
def qvec2rotmat(qvec):
return np.array([
[1 - 2 * qvec[2] ** 2 - 2 * qvec[3] ** 2,
2 * qvec[1] * qvec[2] - 2 * qvec[0] * qvec[3],
2 * qvec[3] * qvec[1] + 2 * qvec[0] * qvec[2]],
[2 * qvec[1] * qvec[2] + 2 * qvec[0] * qvec[3],
1 - 2 * qvec[1] ** 2 - 2 * qvec[3] ** 2,
2 * qvec[2] * qvec[3] - 2 * qvec[0] * qvec[1]],
[2 * qvec[3] * qvec[1] - 2 * qvec[0] * qvec[2],
2 * qvec[2] * qvec[3] + 2 * qvec[0] * qvec[1],
1 - 2 * qvec[1] ** 2 - 2 * qvec[2] ** 2]])
def rotmat2qvec(R):
Rxx, Ryx, Rzx, Rxy, Ryy, Rzy, Rxz, Ryz, Rzz = R.flat
K = np.array([
[Rxx - Ryy - Rzz, 0, 0, 0],
[Ryx + Rxy, Ryy - Rxx - Rzz, 0, 0],
[Rzx + Rxz, Rzy + Ryz, Rzz - Rxx - Ryy, 0],
[Ryz - Rzy, Rzx - Rxz, Rxy - Ryx, Rxx + Ryy + Rzz]]) / 3.0
eigvals, eigvecs = np.linalg.eigh(K)
qvec = eigvecs[[3, 0, 1, 2], np.argmax(eigvals)]
if qvec[0] < 0:
qvec *= -1
return qvec
def convert_to_blender_coord(tvec_w2c, qvec_w2c):
cv2blender = np.array([[1, 0, 0],
[0, -1, 0],
[0, 0, -1]])
R = qvec2rotmat(qvec_w2c)
tvec_blender = -np.dot(R.T, tvec_w2c)
rotation = np.dot(R.T, cv2blender)
qvec_blender = rotmat2qvec(rotation)
return tvec_blender, qvec_blender
# ------------------------------------------------------------------------
# Borrowed from BlenderProc:
# https://github.com/DLR-RM/BlenderProc
# ------------------------------------------------------------------------
def set_intrinsics_from_K_matrix(K: Union[np.ndarray, Matrix], image_width: int, image_height: int,
clip_start: float = None, clip_end: float = None):
""" Set the camera intrinsics via a K matrix.
The K matrix should have the format:
[[fx, 0, cx],
[0, fy, cy],
[0, 0, 1]]
This method is based on https://blender.stackexchange.com/a/120063.
:param K: The 3x3 K matrix.
:param image_width: The image width in pixels.
:param image_height: The image height in pixels.
:param clip_start: Clipping start.
:param clip_end: Clipping end.
"""
K = Matrix(K)
cam = bpy.context.scene.objects['Input Camera'].data
if abs(K[0][1]) > 1e-7:
raise ValueError(f"Skew is not supported by blender and therefore "
f"not by BlenderProc, set this to zero: {K[0][1]} and recalibrate")
fx, fy = K[0][0], K[1][1]
cx, cy = K[0][2], K[1][2]
# If fx!=fy change pixel aspect ratio
pixel_aspect_x = pixel_aspect_y = 1
if fx > fy:
pixel_aspect_y = fx / fy
elif fx < fy:
pixel_aspect_x = fy / fx
# Compute sensor size in mm and view in px
pixel_aspect_ratio = pixel_aspect_y / pixel_aspect_x
view_fac_in_px = get_view_fac_in_px(cam, pixel_aspect_x, pixel_aspect_y, image_width, image_height)
sensor_size_in_mm = get_sensor_size(cam)
# Convert focal length in px to focal length in mm
f_in_mm = fx * sensor_size_in_mm / view_fac_in_px
# Convert principal point in px to blenders internal format
shift_x = (cx - (image_width - 1) / 2) / -view_fac_in_px
shift_y = (cy - (image_height - 1) / 2) / view_fac_in_px * pixel_aspect_ratio
# Finally set all intrinsics
set_intrinsics_from_blender_params(f_in_mm, image_width, image_height, clip_start, clip_end, pixel_aspect_x,
pixel_aspect_y, shift_x, shift_y, "MILLIMETERS")
def get_sensor_size(cam: bpy.types.Camera) -> float:
""" Returns the sensor size in millimeters based on the configured sensor_fit.
:param cam: The camera object.
:return: The sensor size in millimeters.
"""
if cam.sensor_fit == 'VERTICAL':
sensor_size_in_mm = cam.sensor_height
else:
sensor_size_in_mm = cam.sensor_width
return sensor_size_in_mm
def get_view_fac_in_px(cam: bpy.types.Camera, pixel_aspect_x: float, pixel_aspect_y: float,
resolution_x_in_px: int, resolution_y_in_px: int) -> int:
""" Returns the camera view in pixels.
:param cam: The camera object.
:param pixel_aspect_x: The pixel aspect ratio along x.
:param pixel_aspect_y: The pixel aspect ratio along y.
:param resolution_x_in_px: The image width in pixels.
:param resolution_y_in_px: The image height in pixels.
:return: The camera view in pixels.
"""
# Determine the sensor fit mode to use
if cam.sensor_fit == 'AUTO':
if pixel_aspect_x * resolution_x_in_px >= pixel_aspect_y * resolution_y_in_px:
sensor_fit = 'HORIZONTAL'
else:
sensor_fit = 'VERTICAL'
else:
sensor_fit = cam.sensor_fit
# Based on the sensor fit mode, determine the view in pixels
pixel_aspect_ratio = pixel_aspect_y / pixel_aspect_x
if sensor_fit == 'HORIZONTAL':
view_fac_in_px = resolution_x_in_px
else:
view_fac_in_px = pixel_aspect_ratio * resolution_y_in_px
return view_fac_in_px
def set_intrinsics_from_blender_params(lens: float = None, image_width: int = None, image_height: int = None,
clip_start: float = None, clip_end: float = None,
pixel_aspect_x: float = None, pixel_aspect_y: float = None, shift_x: int = None,
shift_y: int = None, lens_unit: str = None):
""" Sets the camera intrinsics using blenders represenation.
:param lens: Either the focal length in millimeters or the FOV in radians, depending on the given lens_unit.
:param image_width: The image width in pixels.
:param image_height: The image height in pixels.
:param clip_start: Clipping start.
:param clip_end: Clipping end.
:param pixel_aspect_x: The pixel aspect ratio along x.
:param pixel_aspect_y: The pixel aspect ratio along y.
:param shift_x: The shift in x direction.
:param shift_y: The shift in y direction.
:param lens_unit: Either FOV or MILLIMETERS depending on whether the lens is defined as focal length in
millimeters or as FOV in radians.
"""
cam = bpy.context.scene.objects['Input Camera'].data
if lens_unit is not None:
cam.lens_unit = lens_unit
if lens is not None:
# Set focal length
if cam.lens_unit == 'MILLIMETERS':
if lens < 1:
raise Exception("The focal length is smaller than 1mm which is not allowed in blender: " + str(lens))
cam.lens = lens
elif cam.lens_unit == "FOV":
cam.angle = lens
else:
raise Exception("No such lens unit: " + lens_unit)
# Set resolution
if image_width is not None:
bpy.context.scene.render.resolution_x = image_width
if image_height is not None:
bpy.context.scene.render.resolution_y = image_height
# Set clipping
if clip_start is not None:
cam.clip_start = clip_start
if clip_end is not None:
cam.clip_end = clip_end
# Set aspect ratio
if pixel_aspect_x is not None:
bpy.context.scene.render.pixel_aspect_x = pixel_aspect_x
if pixel_aspect_y is not None:
bpy.context.scene.render.pixel_aspect_y = pixel_aspect_y
# Set shift
if shift_x is not None:
cam.shift_x = shift_x
if shift_y is not None:
cam.shift_y = shift_y
# ------------------------------------------------------------------------
# AddOn code:
# useful tutorial: https://blender.stackexchange.com/questions/57306/how-to-create-a-custom-ui
# ------------------------------------------------------------------------
# bl_info
bl_info = {
"name": "BlenderNeuralangelo",
"version": (1, 0),
"blender": (3, 3, 1),
"location": "PROPERTIES",
"warning": "", # used for warning icon and text in addons panel
"support": "COMMUNITY",
"category": "Interface"
}
# global variables for easier access
colmap_data = None
old_box_offset = [0, 0, 0, 0, 0, 0]
view_port = None
point_cloud_vertices = None
select_point_index = []
radius = 0
center = (0, 0, 0)
bounding_box = []
# ------------------------------------------------------------------------
# Utility scripts
# ------------------------------------------------------------------------
def display_pointcloud(points3D):
'''
load and display point cloud
borrowed from https://github.com/TombstoneTumbleweedArt/import-ply-as-verts
'''
xyzs = np.stack([point.xyz for point in points3D.values()])
rgbs = np.stack([point.rgb for point in points3D.values()]) # / 255.0
# Copy the positions
ply_name = 'Point Cloud'
mesh = bpy.data.meshes.new(name=ply_name)
mesh.vertices.add(xyzs.shape[0])
mesh.vertices.foreach_set("co", [a for v in xyzs for a in v])
obj = bpy.data.objects.new(ply_name, mesh)
bpy.context.scene.collection.objects.link(obj)
def generate_cropping_planes():
global point_cloud_vertices
max_coordinate = np.max(point_cloud_vertices, axis=0)
min_coordinate = np.min(point_cloud_vertices, axis=0)
x_min = min_coordinate[0]
x_max = max_coordinate[0]
y_min = min_coordinate[1]
y_max = max_coordinate[1]
z_min = min_coordinate[2]
z_max = max_coordinate[2]
verts = [[x_max, y_max, z_min],
[x_max, y_min, z_min],
[x_min, y_min, z_min],
[x_min, y_max, z_min],
[x_max, y_max, z_max],
[x_max, y_min, z_max],
[x_min, y_min, z_max],
[x_min, y_max, z_max]]
faces = [[0, 1, 5, 4],
[3, 2, 6, 7],
[0, 3, 7, 4],
[1, 2, 6, 5],
[0, 1, 2, 3],
[4, 5, 6, 7]]
msh = bpy.data.meshes.new('Bounding Box')
msh.from_pydata(verts, [], faces)
obj = bpy.data.objects.new('Bounding Box', msh)
bpy.context.scene.collection.objects.link(obj)
bpy.context.scene.objects['Bounding Box'].hide_set(True)
# Add plane text
text_object_xmin = bpy.data.objects.new("x_min_label", bpy.data.curves.new(type="FONT", name="x_min"))
text_object_xmin.data.body = "x min"
text_object_xmin.data.size *= 2
bpy.context.scene.collection.objects.link(text_object_xmin)
bpy.context.scene.objects['x_min_label'].hide_set(True)
text_object_xmax = bpy.data.objects.new("x_max_label", bpy.data.curves.new(type="FONT", name="x_max"))
text_object_xmax.data.body = "x max"
text_object_xmax.data.size *= 2
bpy.context.scene.collection.objects.link(text_object_xmax)
bpy.context.scene.objects['x_max_label'].hide_set(True)
text_object_ymin = bpy.data.objects.new("y_min_label", bpy.data.curves.new(type="FONT", name="y_min"))
text_object_ymin.data.body = "y min"
text_object_ymin.data.size *= 2
bpy.context.scene.collection.objects.link(text_object_ymin)
bpy.context.scene.objects['y_min_label'].hide_set(True)
text_object_ymax = bpy.data.objects.new("y_max_label", bpy.data.curves.new(type="FONT", name="y_max"))
text_object_ymax.data.body = "y max"
text_object_ymax.data.size *= 2
bpy.context.scene.collection.objects.link(text_object_ymax)
bpy.context.scene.objects['y_max_label'].hide_set(True)
text_object_zmin = bpy.data.objects.new("z_min_label", bpy.data.curves.new(type="FONT", name="z_min"))
text_object_zmin.data.body = "z min"
text_object_zmin.data.size *= 2
bpy.context.scene.collection.objects.link(text_object_zmin)
bpy.context.scene.objects['z_min_label'].hide_set(True)
text_object_zmax = bpy.data.objects.new("z_max_label", bpy.data.curves.new(type="FONT", name="z_max"))
text_object_zmax.data.body = "z max"
text_object_zmax.data.size *= 2
bpy.context.scene.collection.objects.link(text_object_zmax)
bpy.context.scene.objects['z_max_label'].hide_set(True)
text_object_xmin.rotation_euler = (-math.radians(90), -math.radians(90), math.radians(90))
text_object_xmax.rotation_euler = (-math.radians(90), -math.radians(90), -math.radians(90))
text_object_ymin.rotation_euler = (-math.radians(90), 0, math.radians(180))
text_object_ymax.rotation_euler = (-math.radians(90), 0, 0)
text_object_zmin.rotation_euler = (-math.radians(180), 0, 0)
text_object_zmax.rotation_euler = (0, 0, 0)
text_object_xmin.location = (x_min - 1, (y_max + y_min) / 2, (z_max + z_min) / 2)
text_object_xmax.location = (x_max + 0.5, (y_max + y_min) / 2, (z_max + z_min) / 2)
text_object_ymin.location = ((x_max + x_min) / 2, y_min - 1, (z_max + z_min) / 2)
text_object_ymax.location = ((x_max + x_min) / 2, y_max + 0.5, (z_max + z_min) / 2)
text_object_zmin.location = ((x_max + x_min) / 2, (y_max + y_min) / 2, z_min - 1)
text_object_zmax.location = ((x_max + x_min) / 2, (y_max + y_min) / 2, z_max + 0.5)
return
def set_plane_location(x_max, x_min, y_max, y_min, z_max, z_min):
crop_plane = bpy.data.objects['Bounding Box']
text_object_xmin = bpy.data.objects['x_min_label']
text_object_xmax = bpy.data.objects['x_max_label']
text_object_ymin = bpy.data.objects['y_min_label']
text_object_ymax = bpy.data.objects['y_max_label']
text_object_zmin = bpy.data.objects['z_min_label']
text_object_zmax = bpy.data.objects['z_max_label']
crop_plane.data.vertices[0].co.x = x_max
crop_plane.data.vertices[0].co.y = y_max
crop_plane.data.vertices[0].co.z = z_min
crop_plane.data.vertices[1].co.x = x_max
crop_plane.data.vertices[1].co.y = y_min
crop_plane.data.vertices[1].co.z = z_min
crop_plane.data.vertices[2].co.x = x_min
crop_plane.data.vertices[2].co.y = y_min
crop_plane.data.vertices[2].co.z = z_min
crop_plane.data.vertices[3].co.x = x_min
crop_plane.data.vertices[3].co.y = y_max
crop_plane.data.vertices[3].co.z = z_min
crop_plane.data.vertices[4].co.x = x_max
crop_plane.data.vertices[4].co.y = y_max
crop_plane.data.vertices[4].co.z = z_max
crop_plane.data.vertices[5].co.x = x_max
crop_plane.data.vertices[5].co.y = y_min
crop_plane.data.vertices[5].co.z = z_max
crop_plane.data.vertices[6].co.x = x_min
crop_plane.data.vertices[6].co.y = y_min
crop_plane.data.vertices[6].co.z = z_max
crop_plane.data.vertices[7].co.x = x_min
crop_plane.data.vertices[7].co.y = y_max
crop_plane.data.vertices[7].co.z = z_max
# update text location and rotation
text_width = bpy.context.scene.objects['x_min_label'].dimensions[0] / 2
text_object_xmin.location = (x_min - 1, (y_max + y_min) / 2, (z_max + z_min) / 2 - text_width)
text_object_xmax.location = (x_max + 0.5, (y_max + y_min) / 2, (z_max + z_min) / 2 - text_width)
text_object_ymin.location = ((x_max + x_min) / 2 + text_width, y_min - 1, (z_max + z_min) / 2)
text_object_ymax.location = ((x_max + x_min) / 2 - text_width, y_max + 0.5, (z_max + z_min) / 2)
text_object_zmin.location = ((x_max + x_min) / 2 - text_width, (y_max + y_min) / 2, z_min - 1)
text_object_zmax.location = ((x_max + x_min) / 2 - text_width, (y_max + y_min) / 2, z_max + 1)
def update_cropping_plane(self, context):
global old_box_offset
global point_cloud_vertices
if point_cloud_vertices is None: # stop if point cloud vertices are not yet loaded
return
max_coordinate = np.max(point_cloud_vertices, axis=0)
min_coordinate = np.min(point_cloud_vertices, axis=0)
x_min = min_coordinate[0]
x_max = max_coordinate[0]
y_min = min_coordinate[1]
y_max = max_coordinate[1]
z_min = min_coordinate[2]
z_max = max_coordinate[2]
slider = bpy.context.scene.my_tool.box_slider
x_min_change = -slider[0]
x_max_change = -slider[1]
y_min_change = -slider[2]
y_max_change = -slider[3]
z_min_change = -slider[4]
z_max_change = -slider[5]
if -x_min_change != old_box_offset[0] and x_max + x_max_change < x_min - x_min_change:
x_min_change = x_min - (x_max + x_max_change)
slider[0] = old_box_offset[0]
elif -x_max_change != old_box_offset[1] and x_max + x_max_change < x_min - x_min_change:
x_max_change = x_min - x_min_change - x_max
slider[1] = old_box_offset[1]
elif -y_min_change != old_box_offset[2] and y_max + y_max_change < y_min - y_min_change:
y_min_change = y_min - (y_max + y_max_change)
slider[2] = old_box_offset[2]
elif -y_max_change != old_box_offset[3] and y_max + y_max_change < y_min - y_min_change:
y_max_change = y_min - y_min_change - y_max
slider[3] = old_box_offset[3]
elif -z_min_change != old_box_offset[4] and z_max + z_max_change < z_min - z_min_change:
z_min_change = z_min - (z_max + z_max_change)
slider[4] = old_box_offset[4]
elif -z_max_change != old_box_offset[5] and z_max + z_max_change < z_min - z_min_change:
z_max_change = z_min - z_min_change - z_max
slider[5] = old_box_offset[5]
old_box_offset = [n for n in slider]
set_plane_location(x_max + x_max_change, x_min - x_min_change, y_max + y_max_change, y_min - y_min_change,
z_max + z_max_change, z_min - z_min_change)
def reset_my_slider_to_default():
bpy.context.scene.my_tool.box_slider[0] = 0
bpy.context.scene.my_tool.box_slider[1] = 0
bpy.context.scene.my_tool.box_slider[2] = 0
bpy.context.scene.my_tool.box_slider[3] = 0
bpy.context.scene.my_tool.box_slider[4] = 0
bpy.context.scene.my_tool.box_slider[5] = 0
def delete_bounding_sphere():
if 'Bounding Sphere' in bpy.data.objects:
obj = bpy.context.scene.objects['Bounding Sphere']
bpy.data.meshes.remove(obj.data, do_unlink=True)
# TODO: can this be cleaned up??
# TODO: when loading, not set to solid mode??
def switch_viewport_to_solid(self, context):
toggle = context.scene.my_tool.transparency_toggle
for area in bpy.context.screen.areas:
if area.type == 'VIEW_3D':
for space in area.spaces:
if space.type == 'VIEW_3D':
space.shading.type = 'SOLID'
space.shading.show_xray = toggle
def enable_texture_mode():
# change color mode
for area in bpy.context.screen.areas:
if area.type == 'VIEW_3D':
for space in area.spaces:
if space.type == 'VIEW_3D':
space.shading.color_type = 'TEXTURE'
def update_transparency(self, context):
for area in bpy.context.screen.areas:
if area.type == 'VIEW_3D':
for space in area.spaces:
if space.type == 'VIEW_3D':
alpha = context.scene.my_tool.transparency_slider
space.shading.xray_alpha = alpha
def set_keyframe_camera(camera, qvec_w2c, tvec_w2c, idx, inter_frames=1):
# Set rotation and translation of Camera in each frame
tvec, qvec = convert_to_blender_coord(tvec_w2c, qvec_w2c)
camera.rotation_quaternion = qvec
camera.location = tvec
camera.keyframe_insert(data_path='location', frame=idx * inter_frames)
camera.keyframe_insert(data_path='rotation_quaternion', frame=idx * inter_frames)
def set_keyframe_image(idx, plane, inter_frames=1):
# Set vertices of image plane in each frame
bpy.context.view_layer.update()
# Set image texture of image plane in each frame
material = plane.material_slots[0].material
texture = material.node_tree.nodes.get("Image Texture")
texture.image_user.frame_offset = idx - 1
texture.image_user.keyframe_insert(data_path="frame_offset", frame=idx * inter_frames)
def select_all_vert(obj_name):
if obj_name in bpy.data.objects:
obj = bpy.context.scene.objects[obj_name]
bpy.context.view_layer.objects.active = obj
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_mode(type="VERT")
bpy.ops.mesh.select_all(action='SELECT')
def generate_camera_plane(camera, image_width, image_height, intrinsic_matrix):
if 'Image Plane' in bpy.data.objects:
obj = bpy.context.scene.objects['Image Plane']
bpy.data.meshes.remove(obj.data, do_unlink=True)
bpy.context.view_layer.update()
# create a plane with 4 corners
verts = camera.data.view_frame()
faces = [[0, 1, 2, 3]]
msh = bpy.data.meshes.new('Image Plane')
msh.from_pydata(verts, [], faces)
obj = bpy.data.objects.new('Image Plane', msh)
bpy.context.scene.collection.objects.link(obj)
plane = bpy.context.scene.objects['Image Plane']
bpy.context.view_layer.objects.active = plane
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.uv.unwrap(method='ANGLE_BASED', margin=0)
# change each uv vertex
bm = bmesh.from_edit_mesh(plane.data)
uv_layer = bm.loops.layers.uv.active
for idx, v in enumerate(bm.verts):
for l in v.link_loops:
uv_data = l[uv_layer]
if idx == 0:
uv_data.uv[0] = 0.0
uv_data.uv[1] = 0.0
elif idx == 1:
uv_data.uv[0] = 0.0
uv_data.uv[1] = 1.0
elif idx == 2:
uv_data.uv[0] = 1.0
uv_data.uv[1] = 1.0
elif idx == 3:
uv_data.uv[0] = 1.0
uv_data.uv[1] = 0.0
break
bpy.ops.object.mode_set(mode='OBJECT')
plane.parent = camera
# set plane vertex location
camera_vert_origin = camera.data.view_frame()
corners = np.array([
[0, 0, 1],
[0, image_height, 1],
[image_width, image_height, 1],
[image_width, 0, 1]
])
corners_3D = corners @ (np.linalg.inv(intrinsic_matrix).transpose(-1, -2))
for vert, corner in zip(camera_vert_origin, corners_3D):
vert[0] = corner[0]
vert[1] = corner[1]
vert[2] = -1.0 # blender coord
for i in range(4):
plane.data.vertices[i].co = camera_vert_origin[i]
def copy_all_images(blender_img_path, image_folder_path, image_names, sort_image_id):
file_names = []
for idx, sorted_idx in enumerate(sort_image_id):
shutil.copyfile(image_folder_path + image_names[sorted_idx],
blender_img_path + '%05d.' % (idx + 1) + image_names[sorted_idx].split('.')[-1])
file_names.append('%05d.' % (idx + 1) + image_names[sorted_idx].split('.')[-1])
return file_names
def generate_camera_plane_texture(image_sequence):
plane = bpy.context.scene.objects['Image Plane']
if 'Image Material' not in bpy.data.materials:
material = bpy.data.materials.new(name="Image Material")
else:
material = bpy.data.materials["Image Material"]
if len(plane.material_slots) == 0:
plane.data.materials.append(material)
material = plane.active_material
material.use_nodes = True
image_texture = material.node_tree.nodes.new(type='ShaderNodeTexImage')
principled_bsdf = material.node_tree.nodes.get('Principled BSDF')
material.node_tree.links.new(image_texture.outputs['Color'], principled_bsdf.inputs['Base Color'])
image_texture.image = image_sequence
image_texture.image_user.use_cyclic = True
image_texture.image_user.use_auto_refresh = True
image_texture.image_user.frame_duration = 1
image_texture.image_user.frame_start = 0
image_texture.image_user.frame_offset = 0
def load_camera(colmap_data, context):
if 'Input Camera' in bpy.data.cameras:
camera = bpy.data.cameras['Input Camera']
bpy.data.cameras.remove(camera)
if 'Image Material' in bpy.data.materials:
material = bpy.data.materials['Image Material']
bpy.data.materials.remove(material, do_unlink=True)
# Load colmap data
intrinsic_param = np.array([camera.params for camera in colmap_data['cameras'].values()])
intrinsic_matrix = np.array([[intrinsic_param[0][0], 0, intrinsic_param[0][2]],
[0, intrinsic_param[0][1], intrinsic_param[0][3]],
[0, 0, 1]]) # TODO: only supports single camera for now
image_width = np.array([camera.width for camera in colmap_data['cameras'].values()])
image_height = np.array([camera.height for camera in colmap_data['cameras'].values()])
image_quaternion = np.stack([img.qvec for img in colmap_data['images'].values()])
image_translation = np.stack([img.tvec for img in colmap_data['images'].values()])
camera_id = np.stack([img.camera_id for img in colmap_data['images'].values()]) - 1 # make it zero-indexed
image_names = np.stack([img.name for img in colmap_data['images'].values()])
num_image = image_names.shape[0]
# set start and end frame
context.scene.frame_start = 1
context.scene.frame_end = num_image
# Load image file
sort_image_id = np.argsort(image_names)
image_folder_path = bpy.path.abspath(bpy.context.scene.my_tool.colmap_path + 'images/')
## make a copy of images to comply with the continuous numbering requirement of sequence
blender_img_path = bpy.context.scene.my_tool.colmap_path + 'blender_images/'
if os.path.isdir(blender_img_path):
if os.listdir(blender_img_path):
blender_file_names = sorted(os.listdir(blender_img_path))
else:
blender_file_names = copy_all_images(blender_img_path, image_folder_path, image_names, sort_image_id)
else:
os.mkdir(blender_img_path)
blender_file_names = copy_all_images(blender_img_path, image_folder_path, image_names, sort_image_id)
blender_file_names_formatted = [{"name": file_name} for file_name in blender_file_names]
bpy.ops.image.open(filepath=blender_img_path, directory=blender_img_path, files=blender_file_names_formatted,
relative_path=True, show_multiview=False)
## sequence named after the first image filename
image_sequence = bpy.data.images[blender_file_names_formatted[0]['name']]
image_sequence.source = 'SEQUENCE'
# Camera initialization
camera_data = bpy.data.cameras.new(name="Input Camera")
camera_object = bpy.data.objects.new(name="Input Camera", object_data=camera_data)
bpy.context.scene.collection.objects.link(camera_object)
bpy.data.objects['Input Camera'].rotation_mode = 'QUATERNION'
set_intrinsics_from_K_matrix(intrinsic_matrix, int(image_width[0]),
int(image_height[0])) # set intrinsic matrix
camera = bpy.context.scene.objects['Input Camera']
# Image Plane Setting
generate_camera_plane(camera, int(image_width[0]), int(image_height[0]), intrinsic_matrix) # create plane
generate_camera_plane_texture(image_sequence)
# Setting Camera & Image Plane frame data
plane = bpy.context.scene.objects['Image Plane']
for idx, (i_id, c_id) in enumerate(zip(sort_image_id, camera_id)):
frame_id = idx + 1 # one-indexed
set_keyframe_camera(camera, image_quaternion[i_id], image_translation[i_id], frame_id)
set_keyframe_image(frame_id, plane)
# enable texture mode to visualize images
enable_texture_mode()
# keep point cloud highlighted
select_all_vert('Point Cloud')
return
def update_depth(self, context):
depth_coef = bpy.context.scene.my_tool.imagedepth_slider
scale_coef = 1 + depth_coef
camera = bpy.context.scene.objects['Input Camera']
camera.scale = (scale_coef, scale_coef, scale_coef)
# ------------------------------------------------------------------------
# Scene Properties
# ------------------------------------------------------------------------
class MyProperties(PropertyGroup):
'''
slider bar, path, and everything else ....
'''
colmap_path: StringProperty(
name="Directory",
description="Choose a directory:",
default="",
maxlen=1024,