This repository has been archived by the owner on Jan 14, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 95
/
blam.py
2043 lines (1706 loc) 路 79.5 KB
/
blam.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
'''
blam - Blender Camera Calibration Tools
Copyright (C) 2012-2014 Per Gantelius
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 http://www.gnu.org/licenses/
'''
import bpy
import mathutils
import math, cmath
bl_info = { \
'name': 'BLAM - The Blender camera calibration toolkit',
'author': 'Per Gantelius',
'version': (0, 0, 6),
'blender': (2, 6, 2),
'location': 'Move Clip Editor > Tools Panel > Static Camera Calibration and 3D View > Tools Panel > Photo Modeling Tools',
'description': 'Reconstruction of 3D geometry and estimation of camera orientation and focal length based on photographs.',
'tracker_url': 'https://github.com/stuffmatic/blam/issues',
'wiki_url': 'https://github.com/stuffmatic/blam/wiki',
'support': 'COMMUNITY',
'category': '3D View'}
'''
Public domain pure python linear algebra
stuff from http://users.rcn.com/python/download/python.htm
'''
import operator, math, random
from functools import reduce
NPRE, NPOST = 0, 0 # Disables pre and post condition checks
def iszero(z): return abs(z) < .000001
def getreal(z):
try:
return z.real
except AttributeError:
return z
def getimag(z):
try:
return z.imag
except AttributeError:
return 0
def getconj(z):
try:
return z.conjugate()
except AttributeError:
return z
separator = [ '', '\t', '\n', '\n----------\n', '\n===========\n' ]
class Table(list):
dim = 1
concat = list.__add__ # A substitute for the overridden __add__ method
def __getslice__( self, i, j ):
return self.__class__( list.__getslice__(self,i,j) )
def __init__( self, elems ):
elems = list(elems)
list.__init__( self, elems )
if len(elems) and hasattr(elems[0], 'dim'): self.dim = elems[0].dim + 1
def __str__( self ):
return separator[self.dim].join( map(str, self) )
def map( self, op, rhs=None ):
'''Apply a unary operator to every element in the matrix or a binary operator to corresponding
elements in two arrays. If the dimensions are different, broadcast the smaller dimension over
the larger (i.e. match a scalar to every element in a vector or a vector to a matrix).'''
if rhs is None: # Unary case
return self.dim==1 and self.__class__( map(op, self) ) or self.__class__( [elem.map(op) for elem in self] )
elif not hasattr(rhs,'dim'): # List / Scalar op
return self.__class__( [op(e,rhs) for e in self] )
elif self.dim == rhs.dim: # Same level Vec / Vec or Matrix / Matrix
assert NPRE or len(self) == len(rhs), 'Table operation requires len sizes to agree'
return self.__class__( map(op, self, rhs) )
elif self.dim < rhs.dim: # Vec / Matrix
return self.__class__( [op(self,e) for e in rhs] )
return self.__class__( [op(e,rhs) for e in self] ) # Matrix / Vec
def __mul__( self, rhs ): return self.map( operator.mul, rhs )
def __div__( self, rhs ): return self.map( operator.div, rhs )
def __sub__( self, rhs ): return self.map( operator.sub, rhs )
def __add__( self, rhs ): return self.map( operator.add, rhs )
def __rmul__( self, lhs ): return self*lhs
#def __rdiv__( self, lhs ): return self*(1.0/lhs)
def __rsub__( self, lhs ): return -(self-lhs)
def __radd__( self, lhs ): return self+lhs
def __abs__( self ): return self.map( abs )
def __neg__( self ): return self.map( operator.neg )
def conjugate( self ): return self.map( getconj )
def real( self ): return self.map( getreal )
def imag( self ): return self.map( getimag )
def flatten( self ):
if self.dim == 1: return self
return reduce( lambda cum, e: e.flatten().concat(cum), self, [] )
def prod( self ): return reduce(operator.mul, self.flatten(), 1.0)
def sum( self ): return reduce(operator.add, self.flatten(), 0.0)
def exists( self, predicate ):
for elem in self.flatten():
if predicate(elem):
return 1
return 0
def forall( self, predicate ):
for elem in self.flatten():
if not predicate(elem):
return 0
return 1
def __eq__( self, rhs ): return (self - rhs).forall( iszero )
class Vec(Table):
def dot( self, otherVec ): return reduce(operator.add, map(operator.mul, self, otherVec), 0.0)
def norm( self ): return math.sqrt(abs( self.dot(self.conjugate()) ))
def normalize( self ): return self * (1.0 / self.norm())
def outer( self, otherVec ): return Mat([otherVec*x for x in self])
def cross( self, otherVec ):
'Compute a Vector or Cross Product with another vector'
assert len(self) == len(otherVec) == 3, 'Cross product only defined for 3-D vectors'
u, v = self, otherVec
return Vec([ u[1]*v[2]-u[2]*v[1], u[2]*v[0]-u[0]*v[2], u[0]*v[1]-u[1]*v[0] ])
def house( self, index ):
'Compute a Householder vector which zeroes all but the index element after a reflection'
v = Vec( Table([0]*index).concat(self[index:]) ).normalize()
t = v[index]
sigma = 1.0 - t**2
if sigma != 0.0:
t = v[index] = t<=0 and t-1.0 or -sigma / (t + 1.0)
v = v * (1.0/ t)
return v, 2.0 * t**2 / (sigma + t**2)
def polyval( self, x ):
'Vec([6,3,4]).polyval(5) evaluates to 6*x**2 + 3*x + 4 at x=5'
return reduce( lambda cum,c: cum*x+c, self, 0.0 )
def ratval( self, x ):
'Vec([10,20,30,40,50]).ratfit(5) evaluates to (10*x**2 + 20*x + 30) / (40*x**2 + 50*x + 1) at x=5.'
degree = len(self) / 2
num, den = self[:degree+1], self[degree+1:] + [1]
return num.polyval(x) / den.polyval(x)
class Matrix(Table):
__slots__ = ['size', 'rows', 'cols']
def __init__( self, elems ):
'Form a matrix from a list of lists or a list of Vecs'
elems = list(elems)
Table.__init__( self, hasattr(elems[0], 'dot') and elems or map(Vec,map(tuple,elems)) )
self.size = self.rows, self.cols = len(elems), len(elems[0])
def tr( self ):
'Tranpose elements so that Transposed[i][j] = Original[j][i]'
return Mat(zip(*self))
def star( self ):
'Return the Hermetian adjoint so that Star[i][j] = Original[j][i].conjugate()'
return self.tr().conjugate()
def diag( self ):
'Return a vector composed of elements on the matrix diagonal'
return Vec( [self[i][i] for i in range(min(self.size))] )
def trace( self ): return self.diag().sum()
def mmul( self, other ):
'Matrix multiply by another matrix or a column vector '
if other.dim==2: return Mat( map(self.mmul, other.tr()) ).tr()
assert NPRE or self.cols == len(other)
return Vec( map(other.dot, self) )
def augment( self, otherMat ):
'Make a new matrix with the two original matrices laid side by side'
assert self.rows == otherMat.rows, 'Size mismatch: %s * %s' % (self.size, otherMat.size)
return Mat( map(Table.concat, self, otherMat) )
def qr( self, ROnly=0 ):
'QR decomposition using Householder reflections: Q*R==self, Q.tr()*Q==I(n), R upper triangular'
R = self
m, n = R.size
for i in range(min(m,n)):
v, beta = R.tr()[i].house(i)
R -= v.outer( R.tr().mmul(v)*beta )
for i in range(1,min(n,m)): R[i][:i] = [0] * i
R = Mat(R[:n])
if ROnly: return R
Q = R.tr().solve(self.tr()).tr() # Rt Qt = At nn nm = nm
self.qr = lambda r=0, c=self: not r and c==self and (Q,R) or Matrix.qr(self,r) #Cache result
assert NPOST or m>=n and Q.size==(m,n) and isinstance(R,UpperTri) or m<n and Q.size==(m,m) and R.size==(m,n)
assert NPOST or Q.mmul(R)==self and Q.tr().mmul(Q)==eye(min(m,n))
return Q, R
def _solve( self, b ):
'''General matrices (incuding) are solved using the QR composition.
For inconsistent cases, returns the least squares solution'''
Q, R = self.qr()
return R.solve( Q.tr().mmul(b) )
def solve( self, b ):
'Divide matrix into a column vector or matrix and iterate to improve the solution'
if b.dim==2: return Mat( map(self.solve, b.tr()) ).tr()
assert NPRE or self.rows == len(b), 'Matrix row count %d must match vector length %d' % (self.rows, len(b))
x = self._solve( b )
diff = b - self.mmul(x)
maxdiff = diff.dot(diff)
for i in range(10):
xnew = x + self._solve( diff )
diffnew = b - self.mmul(xnew)
maxdiffnew = diffnew.dot(diffnew)
if maxdiffnew >= maxdiff: break
x, diff, maxdiff = xnew, diffnew, maxdiffnew
#print >> sys.stderr, i+1, maxdiff
assert NPOST or self.rows!=self.cols or self.mmul(x) == b
return x
def rank( self ): return Vec([ not row.forall(iszero) for row in self.qr(ROnly=1) ]).sum()
class Square(Matrix):
def lu( self ):
'Factor a square matrix into lower and upper triangular form such that L.mmul(U)==A'
n = self.rows
L, U = eye(n), Mat(self[:])
for i in range(n):
for j in range(i+1,U.rows):
assert U[i][i] != 0.0, 'LU requires non-zero elements on the diagonal'
L[j][i] = m = 1.0 * U[j][i] / U[i][i]
U[j] -= U[i] * m
assert NPOST or isinstance(L,LowerTri) and isinstance(U,UpperTri) and L*U==self
return L, U
def __pow__( self, exp ):
'Raise a square matrix to an integer power (i.e. A**3 is the same as A.mmul(A.mmul(A))'
assert NPRE or exp==int(exp) and exp>0, 'Matrix powers only defined for positive integers not %s' % exp
if exp == 1: return self
if exp&1: return self.mmul(self ** (exp-1))
sqrme = self ** (exp/2)
return sqrme.mmul(sqrme)
def det( self ): return self.qr( ROnly=1 ).det()
def inverse( self ): return self.solve( eye(self.rows) )
def hessenberg( self ):
'''Householder reduction to Hessenberg Form (zeroes below the diagonal)
while keeping the same eigenvalues as self.'''
for i in range(self.cols-2):
v, beta = self.tr()[i].house(i+1)
self -= v.outer( self.tr().mmul(v)*beta )
self -= self.mmul(v).outer(v*beta)
return self
def eigs( self ):
'Estimate principal eigenvalues using the QR with shifts method'
origTrace, origDet = self.trace(), self.det()
self = self.hessenberg()
eigvals = Vec([])
for i in range(self.rows-1,0,-1):
while not self[i][:i].forall(iszero):
shift = eye(i+1) * self[i][i]
q, r = (self - shift).qr()
self = r.mmul(q) + shift
eigvals.append( self[i][i] )
self = Mat( [self[r][:i] for r in range(i)] )
eigvals.append( self[0][0] )
assert NPOST or iszero( (abs(origDet) - abs(eigvals.prod())) / 1000.0 )
assert NPOST or iszero( origTrace - eigvals.sum() )
return Vec(eigvals)
class Triangular(Square):
def eigs( self ): return self.diag()
def det( self ): return self.diag().prod()
class UpperTri(Triangular):
def _solve( self, b ):
'Solve an upper triangular matrix using backward substitution'
x = Vec([])
for i in range(self.rows-1, -1, -1):
assert NPRE or self[i][i], 'Backsub requires non-zero elements on the diagonal'
x.insert(0, (b[i] - x.dot(self[i][i+1:])) / self[i][i] )
return x
class LowerTri(Triangular):
def _solve( self, b ):
'Solve a lower triangular matrix using forward substitution'
x = Vec([])
for i in range(self.rows):
assert NPRE or self[i][i], 'Forward sub requires non-zero elements on the diagonal'
x.append( (b[i] - x.dot(self[i][:i])) / self[i][i] )
return x
def Mat( elems ):
'Factory function to create a new matrix.'
elems = list(elems)
m, n = len(elems), len(elems[0])
if m != n: return Matrix(elems)
if n <= 1: return Square(elems)
for i in range(1, len(elems)):
if not iszero( max(map(abs, elems[i][:i])) ):
break
else: return UpperTri(elems)
for i in range(0, len(elems)-1):
if not iszero( max(map(abs, elems[i][i+1:])) ):
return Square(elems)
return LowerTri(elems)
def funToVec( tgtfun, low=-1, high=1, steps=40, EqualSpacing=0 ):
'''Compute x,y points from evaluating a target function over an interval (low to high)
at evenly spaces points or with Chebyshev abscissa spacing (default) '''
if EqualSpacing:
h = (0.0+high-low)/steps
xvec = [low+h/2.0+h*i for i in range(steps)]
else:
scale, base = (0.0+high-low)/2.0, (0.0+high+low)/2.0
xvec = [base+scale*math.cos(((2*steps-1-2*i)*math.pi)/(2*steps)) for i in range(steps)]
yvec = map(tgtfun, xvec)
return Mat( [xvec, yvec] )
def funfit(xvec, yvec, basisfuns ):
'Solves design matrix for approximating to basis functions'
return Mat([ map(form,xvec) for form in basisfuns ]).tr().solve(Vec(yvec))
def polyfit(xvec, yvec, degree=2 ):
'Solves Vandermonde design matrix for approximating polynomial coefficients'
return Mat([ [x**n for n in range(degree,-1,-1)] for x in xvec ]).solve(Vec(yvec))
def ratfit(xvec, yvec, degree=2 ):
'Solves design matrix for approximating rational polynomial coefficients (a*x**2 + b*x + c)/(d*x**2 + e*x + 1)'
return Mat([[x**n for n in range(degree,-1,-1)]+[-y*x**n for n in range(degree,0,-1)] for x,y in zip(xvec,yvec)]).solve(Vec(yvec))
def genmat(m, n, func):
if not n: n=m
return Mat([ [func(i,j) for i in range(n)] for j in range(m) ])
def zeroes(m=1, n=None):
'Zero matrix with side length m-by-m or m-by-n.'
return genmat(m,n, lambda i,j: 0)
def eye(m=1, n=None):
'Identity matrix with side length m-by-m or m-by-n'
return genmat(m,n, lambda i,j: int(i==j))
def hilb(m=1, n=None):
'Hilbert matrix with side length m-by-m or m-by-n. Elem[i][j]=1/(i+j+1)'
return genmat(m,n, lambda i,j: 1.0/(i+j+1.0))
def rand(m=1, n=None):
'Random matrix with side length m-by-m or m-by-n'
return genmat(m,n, lambda i,j: random.random())
'''
Generic math stuff
'''
def normalize(vec):
l = length(vec)
return [x / l for x in vec]
def length(vec):
return math.sqrt(sum([x * x for x in vec]))
def dot(x, y):
return sum([x[i] * y[i] for i in range(len(x))])
def cbrt(x):
if x >= 0:
return math.pow(x, 1.0/3.0)
else:
return -math.pow(abs(x), 1.0/3.0)
def polar(x, y, deg=0): # radian if deg=0; degree if deg=1
if deg:
return math.hypot(x, y), 180.0 * math.atan2(y, x) / math.pi
else:
return math.hypot(x, y), math.atan2(y, x)
def quadratic(a, b, c=None):
if c: # (ax^2 + bx + c = 0)
a, b = b / float(a), c / float(a)
t = a / 2.0
r = t**2 - b
if r >= 0: # real roots
y1 = math.sqrt(r)
else: # complex roots
y1 = cmath.sqrt(r)
y2 = -y1
return y1 - t, y2 - t
def solveCubic(a, b, c, d):
cIn = [a, b, c, d]
a, b, c = b / float(a), c / float(a), d / float(a)
t = a / 3.0
p, q = b - 3 * t**2, c - b * t + 2 * t**3
u, v = quadratic(q, -(p/3.0)**3)
if type(u) == type(0j): # complex cubic root
r, w = polar(u.real, u.imag)
y1 = 2 * cbrt(r) * math.cos(w / 3.0)
else: # real root
y1 = cbrt(u) + cbrt(v)
y2, y3 = quadratic(y1, p + y1**2)
x1 = y1 - t
x2 = y2 - t
x3 = y3 - t
return x1, x2, x3
#helper function to determine if the current version
#of the python api represents matrices as column major
#or row major.
'''
def arePythonMatricesRowMajor():
v = bpy.app.version
is262OrGreater = v[0] >= 2 and v[1] >= 62
is260OrLess = v[0] <= 2 and v[1] <= 60
is261 = v[0] == 2 and v[1] == 61
rev = bpy.app.build_revision
if is262OrGreater:
return True
if is260OrLess:
return False
#apparently, build_revision is not always just a number:
#http://code.google.com/p/blam/issues/detail?id=11
#TODO: find out what the format of bpy.app.build_revision is
#for now, remove anything that isn't a digit
digits = [str(d) for d in range(9)]
numberString = ''
for ch in rev:
if ch in digits:
numberString = numberString + ch
#do revision check if we're running 2.61
#matrices are row major starting in revision r42816
return int(numberString) >= 42816
'''
#helper function that returns the faces of a mesh. in bmesh builds,
#this is a list of polygons, and in pre-bmesh builds this is a list
#of triangles and quads
def getMeshFaces(meshObject):
try:
return meshObject.data.faces
except:
return meshObject.data.polygons
'''
PROJECTOR CALIBRATION STUFF
'''
'''
class ProjectorCalibrationPanel(bpy.types.Panel):
bl_label = "Video Projector Calibration"
bl_space_type = "CLIP_EDITOR"
bl_region_type = "TOOLS"
def draw(self, context):
scn = bpy.context.scene
l = self.layout
r = l.row()
r.operator("object.create_proj_calib_win")
r = l.row()
r.operator("object.set_calib_window_to_clip")
r = l.row()
r.operator("object.set_calib_window_to_view3d")
'''
class CreateProjectorCalibrationWindowOperator(bpy.types.Operator):
bl_idname = "object.create_proj_calib_win"
bl_label = "Create calibration window"
bl_description = "TODO"
def execute(self, context):
ws = bpy.context.window_manager.windows
if len(ws) > 1:
self.report({'ERROR'}, "Other windows exist. Close them and try again.")
return{'CANCELLED'}
return bpy.ops.screen.area_dupli('INVOKE_DEFAULT')
class SetCalibrationWindowToClipEditor(bpy.types.Operator):
bl_idname = "object.set_calib_window_to_clip"
bl_label = "Clip editor"
bl_description = ""
def execute(self, context):
windows = bpy.context.window_manager.windows
if len(windows) > 2:
self.report({'ERROR'}, "Expected two windows. Found " + str(len(windows)))
return{'CANCELLED'}
#operate on the window with one area
window = None
for w in windows:
areas = w.screen.areas
if len(areas) == 1:
window = w
break
if not window:
self.report({'ERROR'}, "Could not find single area window.")
return{'CANCELLED'}
area = window.screen.areas[0]
toolsHidden = False
propsHidden = False
for i in area.regions:
print(i.type, i.width, i.height)
if i.type == 'TOOLS' and i.width <= 1:
toolsHidden = True
elif i.type == 'TOOL_PROPS' and i.width <= 1:
propsHidden = True
area.type = "CLIP_EDITOR"
override = {'window': window, 'screen': window.screen, 'area': area}
if not toolsHidden:
bpy.ops.clip.tools(override)
if not propsHidden:
bpy.ops.clip.properties(override)
bpy.ops.clip.view_all(override)
bpy.ops.clip.view_zoom_ratio(override, ratio=1)
return{'FINISHED'}
class SetCalibrationWindowToView3D(bpy.types.Operator):
bl_idname = "object.set_calib_window_to_view3d"
bl_label = "3D view"
bl_description = ""
def execute(self, context):
windows = bpy.context.window_manager.windows
if len(windows) > 2:
self.report({'ERROR'}, "Expected two windows. Found " + str(len(windows)))
return{'CANCELLED'}
#operate on the window with one area
window = None
for w in windows:
areas = w.screen.areas
if len(areas) == 1:
window = w
break
if not window:
self.report({'ERROR'}, "Could not find single area window.")
return{'CANCELLED'}
area = window.screen.areas[0]
toolsHidden = False
propsHidden = False
for i in area.regions:
print(i.type, i.width, i.height)
if i.type == 'TOOLS' and i.width <= 1:
toolsHidden = True
elif i.type == 'TOOL_PROPS' and i.width <= 1:
propsHidden = True
area.type = "VIEW_3D"
override = {'window': window, 'screen': window.screen, 'area': area}
if not toolsHidden:
bpy.ops.view3d.toolshelf(override)
if not propsHidden:
bpy.ops.view3d.properties(override)
s3d = area.spaces.active
s3d.region_3d.view_camera_offset[0] = 0.0
s3d.region_3d.view_camera_offset[1] = 0.0
bpy.ops.view3d.zoom_camera_1_to_1(override)
return{'FINISHED'}
'''
CAMERA CALIBRATION STUFF
'''
class PhotoModelingToolsPanel(bpy.types.Panel):
bl_label = "Photo Modeling Tools"
bl_space_type = "VIEW_3D"
bl_region_type = "TOOLS"
def draw(self, context):
scn = bpy.context.scene
l = self.layout
r = l.row()
b = r.box()
b.operator("object.compute_depth_information")
b.prop(scn, 'separate_faces')
r = l.row()
b = r.box()
b.operator("object.project_bg_onto_mesh")
b.prop(scn, 'projection_method')
#self.layout.operator("object.make_edge_x")
l.operator("object.set_los_scale_pivot")
class SetLineOfSightScalePivot(bpy.types.Operator):
bl_idname = "object.set_los_scale_pivot"
bl_label = "Set line of sight scale pivot"
bl_description = "Set the pivot to the camera origin, which makes scaling equivalent to translation along the line of sight."
def execute(self, context):
bpy.ops.object.mode_set(mode='OBJECT')
selStates = []
objs = bpy.context.scene.objects
for obj in objs:
selStates.append(obj.select)
obj.select = False
#select the camera
bpy.context.scene.camera.select = True
#snap the cursor to the camer
bpy.ops.view3d.snap_cursor_to_selected()
#set the cursor to be the pivot
space = bpy.context.area.spaces.active
print(space.pivot_point)
space.pivot_point = 'CURSOR'
for i in range(len(objs)):
obj = objs[i]
obj.select = selStates[i]
return{'FINISHED'}
class ProjectBackgroundImageOntoMeshOperator(bpy.types.Operator):
bl_idname = "object.project_bg_onto_mesh"
bl_label = "Project background image onto mesh"
bl_description = "Projects the current 3D view background image onto a mesh (the active object) from the active camera."
projectorName = 'tex_projector'
materialName = 'cam_map_material'
def meshVerticesToNDC(self, cam, mesh):
#compute a projection matrix transforming
#points in camera space to points in NDC
near = cam.data.clip_start
far = cam.data.clip_end
rs = bpy.context.scene.render
rx = rs.resolution_x
ry = rs.resolution_y
tall = rx < ry
if tall:
fov = cam.data.angle_x
aspect = rx / float(ry)
h = math.tan(0.5 * fov)
w = aspect * h
else:
fov = cam.data.angle_x
aspect = ry / float(rx)
w = math.tan(0.5 * fov)
h = aspect * w
pm = mathutils.Matrix()
pm[0][0] = 1 / w
pm[1][1] = 1 / h
pm[2][2] = (near + far) / (near - far)
pm[2][3] = 2 * near * far / (near - far)
pm[3][2] = -1.0
pm[3][3] = 0.0
#if not arePythonMatricesRowMajor():
# pm.transpose()
returnVerts = []
for v in mesh.data.vertices:
#the vert in local coordinates
vec = v.co.to_4d()
#the vert in world coordinates
vec = mesh.matrix_world * vec
#the vert in clip coordinates
vec = pm * cam.matrix_world.inverted() * vec
#the vert in normalized device coordinates
w = vec[3]
vec = [x / w for x in vec]
returnVerts.append((vec[0], vec[1], vec[2]))
return returnVerts
def addUVsProjectedFromView(self, mesh):
cam = bpy.context.scene.camera
#get the mesh vertices in normalized device coordinates
#as seen through the active camera
ndcVerts = self.meshVerticesToNDC(cam, mesh)
#create a uv layer
bpy.ops.object.mode_set(mode='EDIT')
#projecting from view here, but the current view might not
#be the camera, so the uvs are computed manually a couple
#of lines down
bpy.ops.uv.project_from_view(scale_to_bounds=True)
bpy.ops.object.mode_set(mode='OBJECT')
#set uvs to match the vertex x and y components in NDC
isBmesh = True
try:
f = mesh.data.faces
isBmesh = False
except:
pass
if isBmesh:
loops = mesh.data.loops
uvLoops = mesh.data.uv_layers[0].data
for loop, uvLoop in zip(loops, uvLoops):
vIdx = loop.vertex_index
print("loop", loop, "vertex", loop.vertex_index, "uvLoop", uvLoop)
ndcVert = ndcVerts[vIdx]
uvLoop.uv[0] = 0.5 * (ndcVert[0] + 1.0)
uvLoop.uv[1] = 0.5 * (ndcVert[1] + 1.0)
else:
assert(len(getMeshFaces(mesh)) == len(mesh.data.uv_textures[0].data))
for meshFace, uvFace in zip(getMeshFaces(mesh), mesh.data.uv_textures[0].data):
faceVerts = [ndcVerts[i] for i in meshFace.vertices]
for i in range(len(uvFace.uv)):
uvFace.uv[i][0] = 0.5 * (faceVerts[i][0] + 1.0)
uvFace.uv[i][1] = 0.5 * (faceVerts[i][1] + 1.0)
def performSimpleProjection(self, camera, mesh, img):
if len(mesh.material_slots) == 0:
mat = bpy.data.materials.new(self.materialName)
mesh.data.materials.append(mat)
else:
mat = mesh.material_slots[0].material
mat.use_shadeless = True
mat.use_face_texture = True
self.addUVsProjectedFromView(mesh)
for f in mesh.data.uv_textures[0].data:
f.image = img
def performHighQualityProjection(self, camera, mesh, img):
if len(mesh.material_slots) == 0:
mat = bpy.data.materials.new(self.materialName)
mesh.data.materials.append(mat)
else:
mat = mesh.material_slots[0].material
mat.use_shadeless = True
mat.use_face_texture = True
#the texture sampling is not perspective correct
#when directly using sticky UVs or UVs projected from the view
#this is a pretty messy workaround that gives better looking results
self.addUVsProjectedFromView(mesh)
#then create an empty object that will serve as a texture projector
#if the mesh has a child with the name of a texture projector,
#reuse it
reusedProjector = None
for ch in mesh.children:
if self.projectorName in ch.name:
reusedProjector = ch
break
if reusedProjector:
projector = reusedProjector
else:
bpy.ops.object.camera_add()
projector = bpy.context.active_object
bpy.context.scene.objects.active = projector
projector.name = mesh.name + '_' + self.projectorName
projector.matrix_world = camera.matrix_world
projector.select = False
projector.scale = [0.1, 0.1, 0.1]
projector.data.lens = camera.data.lens
projector.data.sensor_width = camera.data.sensor_width
projector.data.sensor_height = camera.data.sensor_height
projector.data.sensor_fit = camera.data.sensor_fit
#parent the projector to the mesh for convenience
for obj in bpy.context.scene.objects:
obj.select = False
projector.select = True
bpy.context.scene.objects.active = mesh
#bpy.ops.object.parent_set()
#lock the projector to the mesh
#bpy.context.scene.objects.active = projector
#bpy.ops.object.constraint_add(type='COPY_LOCATION')
#projector.constraints[-1].target = mesh
#create a simple subdivision modifier on the mesh object.
#this subdivision is what alleviates the texture sampling
#artefacts.
bpy.context.scene.objects.active = mesh
levels = 3
bpy.ops.object.modifier_add()
modifier = mesh.modifiers[-1]
modifier.subdivision_type = 'SIMPLE'
modifier.levels = levels
modifier.render_levels = levels
#then create a uv project modifier that will project the
#image onto the subdivided mesh using our projector object.
bpy.ops.object.modifier_add(type='UV_PROJECT')
modifier = mesh.modifiers[-1]
modifier.aspect_x = bpy.context.scene.render.resolution_x / float(bpy.context.scene.render.resolution_y)
modifier.image = img
modifier.use_image_override = True
modifier.projectors[0].object = projector
modifier.uv_layer = mesh.data.uv_textures[0].name
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.object.mode_set(mode='OBJECT')
def prepareMesh(self, mesh):
#remove all uv layers
while len(mesh.data.uv_textures) > 0:
bpy.ops.mesh.uv_texture_remove()
#remove all modifiers
for m in mesh.modifiers:
bpy.ops.object.modifier_remove(modifier=m.name)
def execute(self, context):
'''
Get the active object and make sure it is a mesh
'''
mesh = bpy.context.active_object
if mesh == None:
self.report({'ERROR'}, "There is no active object")
return{'CANCELLED'}
elif not 'Mesh' in str(type(mesh.data)):
self.report({'ERROR'}, "The active object is not a mesh")
return{'CANCELLED'}
'''
Get the current camera
'''
camera = bpy.context.scene.camera
if not camera:
self.report({'ERROR'}, "No active camera.")
return{'CANCELLED'}
activeSpace = bpy.context.area.spaces.active
if len(activeSpace.background_images) == 0:
self.report({'ERROR'}, "No backround images of clips found.")
return{'CANCELLED'}
#check what kind of background we're dealing with
bg = activeSpace.background_images[0]
if bg.image != None:
img = bg.image
elif bg.clip != None:
path = bg.clip.filepath
#create an image texture from the (first) background clip
try:
img = bpy.data.images.load(path)
except:
self.report({'ERROR'}, "Cannot load image %s" % path)
return{'CANCELLED'}
else:
#shouldnt end up here
self.report({'ERROR'}, "Both background clip and image are None")
return{'CANCELLED'}
#if we made it here, we have a camera, a mesh and an image.
self.prepareMesh(mesh)
method = bpy.context.scene.projection_method
if method == 'hq':
self.performHighQualityProjection(camera, mesh, img)
elif method == 'simple':
self.performSimpleProjection(camera, mesh, img)
else:
self.report({'ERROR'}, "Unknown projection method")
return{'CANCELLED'}
activeSpace.viewport_shade = 'TEXTURED'
return{'FINISHED'}
class Reconstruct3DMeshOperator(bpy.types.Operator):
bl_idname = "object.compute_depth_information"
bl_label = "Reconstruct 3D geometry"
bl_description = "Reconstructs a 3D mesh with rectangular faces based on a mesh with faces lining up with the corresponding faces in the image. Relies on the active camera being properly calibrated."
def evalEq17(self, origin, p1, p2):
a = [x - y for x, y in zip(origin, p1)]
b = [x - y for x, y in zip(origin, p2)]
return dot(a, b)
def evalEq27(self, l):
return self.C4 * l ** 4 + self.C3 * l ** 3 + self.C2 * l ** 2 + self.C1 * l + self.C0
def evalEq28(self, l):
return self.B4 * l ** 4 + self.B3 * l ** 3 + self.B2 * l ** 2 + self.B1 * l + self.B0
def evalEq29(self, l):
return self.D3 * l ** 3 + self.D2 * l ** 2 + self.D1 * l + self.D0
def worldToCameraSpace(self, verts):
ret = []
for v in verts:
#the vert in local coordinates
vec = v.co.to_4d()
#the vert in world coordinates
vec = self.mesh.matrix_world * vec
#the vert in camera coordinates
vec = self.camera.matrix_world.inverted() * vec
ret.append(vec[0:3])
return ret
def computeCi(self, Qab, Qac, Qad, Qbc, Qbd, Qcd):
self.C4 = Qad * Qbc * Qbd - Qac * Qbd ** 2
self.C3 = Qab * Qad * Qbd * Qcd - Qad ** 2 * Qcd + Qac * Qad * Qbd ** 2 - Qad ** 2 * Qbc * Qbd - Qbc * Qbd + 2 * Qab * Qac * Qbd - Qab * Qad * Qbc
self.C2 = -Qab * Qbd * Qcd - Qab ** 2 * Qad * Qcd + 2 * Qad * Qcd + Qad * Qbc * Qbd - 3 * Qab * Qac * Qad * Qbd + Qab * Qad ** 2 * Qbc + Qab * Qbc + Qac * Qad ** 2 - Qab ** 2 * Qac
self.C1 = Qab ** 2 * Qcd - Qcd + Qab * Qac * Qbd - Qab * Qad * Qbc + 2 * Qab ** 2 * Qac * Qad - 2 * Qac * Qad
self.C0 = Qac - Qab ** 2 * Qac
def computeBi(self, Qab, Qac, Qad, Qbc, Qbd, Qcd):
self.B4 = Qbd - Qbd * Qcd ** 2
self.B3 = 2 * Qad * Qbd * Qcd ** 2 + Qab * Qcd ** 2 + Qac * Qbd * Qcd - Qad * Qbc * Qcd - 2 * Qad * Qbd - Qab
self.B2 = - Qbd * Qcd ** 2 - Qab * Qad * Qcd ** 2 - 3 * Qac * Qad * Qbd * Qcd + Qad ** 2 * Qbc * Qcd + Qbc * Qcd - Qab * Qac * Qcd + Qad ** 2 * Qbd + Qac * Qad * Qbc + 2 * Qab * Qad
self.B1 = 2 * Qac * Qbd * Qcd - Qad * Qbc * Qcd + Qab * Qac * Qad * Qcd + Qac ** 2 * Qad * Qbd - Qac * Qad ** 2 * Qbc - Qac * Qbc - Qab * Qad ** 2
self.B0 = Qac * Qad * Qbc - Qac ** 2 * Qbd
def computeQuadDepthInformation(self, qHatA, qHatB, qHatC, qHatD):
#print()
#print("computeQuadDepthInformation")
'''
compute the coefficients Qij
'''
Qab = dot(qHatA, qHatB)
Qac = dot(qHatA, qHatC)
Qad = dot(qHatA, qHatD)
Qba = dot(qHatB, qHatA)
Qbc = dot(qHatB, qHatC)
Qbd = dot(qHatB, qHatD)
Qca = dot(qHatC, qHatA)
Qcb = dot(qHatC, qHatB)
Qcd = dot(qHatC, qHatD)
#print("Qab", Qab, "Qac", Qac, "Qad", Qad)
#print("Qba", Qba, "Qbc", Qbc, "Qbd", Qbd)
#print("Qca", Qca, "Qcb", Qcb, "Qcd", Qcd)
'''
compute the coefficients Ci of equation (27)
'''
self.computeCi(Qab, Qac, Qad, Qbc, Qbd, Qcd)
'''
compute the coefficients Bi of equation (28)
'''
self.computeBi(Qab, Qac, Qad, Qbc, Qbd, Qcd)
'''
compute the cofficients Di of equation (29)
'''
self.D3 = (self.C4 / self.B4) * self.B3 - self.C3
self.D2 = (self.C4 / self.B4) * self.B2 - self.C2
self.D1 = (self.C4 / self.B4) * self.B1 - self.C1
self.D0 = (self.C4 / self.B4) * self.B0 - self.C0
#print("Di", self.D3, self.D2, self.D1, self.D0)
'''
solve eq 29 for lambdaD, i.e the depth in camera space of vertex D.
'''
roots = solveCubic(self.D3, self.D2, self.D1, self.D0)
#print("Eq 29 Roots", roots)
'''
choose one of the three computed roots. Tan, Sullivan and Baker propose
choosing a real root that satisfies "(27) or (28)". Since these
equations are derived from the orthogonality equations (17) and
since we're interested in a quad with edges that are "as
orthogonal as possible", in this implementation the positive real
root that minimizes the quad orthogonality error is chosen instead.
'''
chosenRoot = None
minError = None
#print()
#print("Finding root")
for root in roots:
#print("Root", root)
if type(root) == type(0j):
#complex root. do nothing
continue