forked from Akatmks/Akatsumekusa-Aegisub-Scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
aae-export.py
1812 lines (1523 loc) · 86 KB
/
aae-export.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
# aae-export.py
# Copyright (c) Akatsumekusa, arch1t3cht, bucket3432, Martin Herkt and
# contributors
#
# ::: ::: ::::::::::
# :+: :+: :+: :+: :+:
# +:+ +:+ +:+ +:+ +:+
# +#++:++#++: +#++:++#++: +#++:++#
# +#+ +#+ +#+ +#+ +#+
# #+# #+# #+# #+# #+#
# ### ### ### ### ##########
# :::::::::: ::: ::: ::::::::: :::::::: ::::::::: :::::::::::
# :+: :+: :+: :+: :+: :+: :+: :+: :+: :+:
# +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+
# +#++:++# +#++:+ +#++:++#+ +#+ +:+ +#++:++#: +#+
# +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+
# #+# #+# #+# #+# #+# #+# #+# #+# #+#
# ########## ### ### ### ######## ### ### ###
#
# ---------------------------------------------------------------------
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ---------------------------------------------------------------------
# Title font: Alligator by Simon Bradley
# ---------------------------------------------------------------------
bl_info = {
"name": "AAE Export",
"description": "Export tracks and plane tracks to Aegisub-Motion and Aegisub-Perspective-Motion compatible AAE data",
"author": "Akatsumekusa, arch1t3cht, bucket3432, Martin Herkt and contributors",
"version": (1, 1, 6),
"support": "COMMUNITY",
"category": "Video Tools",
"blender": (3, 1, 0),
"location": "Clip Editor > Tools > Solve > AAE Export",
"warning": "",
"doc_url": "https://github.com/Akatmks/Akatsumekusa-Aegisub-Scripts",
"tracker_url": "https://github.com/Akatmks/Akatsumekusa-Aegisub-Scripts/issues"
}
import bpy
import bpy_extras.io_utils
# ("import name", "PyPI name", "minimum version")
smoothing_modules = (("numpy", "numpy", ""),
("sklearn", "scikit-learn", "0.18"),
("matplotlib", "matplotlib", ""),
("PIL", "Pillow", ""))
is_smoothing_modules_available = False
def get_smoothing_modules_install_description():
from pathlib import PurePath
import sys
pre_modules = "This will download and install "
modules = " and ".join([", ".join(["pip"] + [module[1] for module in smoothing_modules[:-1]]), smoothing_modules[-1][1]]) if len(smoothing_modules) != 0 else "pip"
post_modules_pre_path = " to Blender's python environment at „"
path = PurePath(sys.prefix).as_posix()
post_path = "“. This process normally takes about 2 minutes"
if len(pre_modules) + len(modules) + len(post_modules_pre_path) + len(path) + len(post_path) < 240:
return pre_modules + modules + post_modules_pre_path + path + post_path
else:
available_len = 240 - len(pre_modules) - len(modules) - len(post_modules_pre_path) - len(post_path)
path_last_two_parts = "/" + (parts := PurePath(path).parts)[-2] + "/" + parts[-1]
return pre_modules + modules + post_modules_pre_path + path[:available_len - len(path_last_two_parts) - 3] + "..." + path_last_two_parts + post_path
class AAEExportSettings(bpy.types.PropertyGroup):
bl_label = "AAEExportSettings"
bl_idname = "AAEExportSettings"
do_includes_power_pin: bpy.props.BoolProperty(name="Includes Power Pin",
description="Includes Power Pin data in the export for tracks and plane tracks.\nIf Aegisub-Perspective-Motion is unable to recognise the data, please update Aegisub-Perspective-Motion to the newest version.\nThis option will be removed by late January and Power Pin data will be included by default",
default=True)
do_smoothing_fake: bpy.props.BoolProperty(name="Enable",
description="Perform smoothing on tracking data.\nThis feature requires additional packages to be installed. Please head to „Edit > Preference > Add-ons > Video Tools: AAE Export > Preferences“ to install the dependencies",
default=False)
do_smoothing: bpy.props.BoolProperty(name="Enable",
description="Perform smoothing on tracking data.\nThis uses position data, scale data, rotation data and Power Pin data of individual tracks and plane tracks to fit polynomial regression models, and then uses the fit models to generate smoothed data.\n\nPlease note that this smoothing feature is very rudimentary and may cause more problems than it solves. Akatsumekusa recommends trying it only if the tracking is unbearably poor.\n\nAlso, Akatsumekusa is working on a new script that will provide this feature much better than it is right now. Please expect Non Carbonated AAE Export to come out sometime in the year",
default=False)
smoothing_do_position: bpy.props.BoolProperty(name="Smooth",
description="Perform smoothing on position data",
default=True)
smoothing_position_degree: bpy.props.IntProperty(name="Max Degree",
description="The maximal polynomial degree of position data.\nA degree of 1 means the data scales linearly.\nA degree of 2 means the data scales quadratically.\nA degree of 3 means the data scales cubically.\n\nAkatsumekusa recommends setting this value to the exact polynomial degree of the data, as setting it too high may cause overfitting.\n\nFor more information, please visit „https://scikit-learn.org/stable/modules/linear_model.html#polynomial-regression-extending-linear-models-with-basis-functions“ and „https://en.wikipedia.org/wiki/Polynomial_regression“",
default=2,
min=1,
soft_max=16)
smoothing_do_scale: bpy.props.BoolProperty(name="Smooth",
description="Perform smoothing on scale data",
default=True)
smoothing_scale_degree: bpy.props.IntProperty(name="Max Degree",
description="The maximal polynomial degree of scale data.\nA degree of 1 means the data scales linearly.\nA degree of 2 means the data scales quadratically.\nA degree of 3 means the data scales cubically.\n\nAkatsumekusa recommends setting this value to the exact polynomial degree of the data, as setting it too high may cause overfitting.\n\nFor more information, please visit „https://scikit-learn.org/stable/modules/linear_model.html#polynomial-regression-extending-linear-models-with-basis-functions“ and „https://en.wikipedia.org/wiki/Polynomial_regression“",
default=2,
min=1,
soft_max=16)
smoothing_do_rotation: bpy.props.BoolProperty(name="Smooth",
description="Perform smoothing on rotation data.\nPlease note that rotation calculation in AAE Export is very basic. Performing smoothing on rotations with high velocity may yield unexpected results",
default=True)
smoothing_rotation_degree: bpy.props.IntProperty(name="Max Degree",
description="The maximal polynomial degree of rotation data.\nA degree of 1 means the data scales linearly.\nA degree of 2 means the data scales quadratically.\nA degree of 3 means the data scales cubically.\n\nAkatsumekusa recommends setting this value to the exact polynomial degree of the data, as setting it too high may cause overfitting.\n\nFor more information, please visit „https://scikit-learn.org/stable/modules/linear_model.html#polynomial-regression-extending-linear-models-with-basis-functions“ and „https://en.wikipedia.org/wiki/Polynomial_regression“",
default=1,
min=1,
soft_max=16)
smoothing_do_power_pin: bpy.props.BoolProperty(name="Smooth",
description="Perform smoothing on Power Pin data",
default=True)
smoothing_power_pin_degree: bpy.props.IntProperty(name="Max Degree",
description="The maximal polynomial degree of Power Pin data.\nA degree of 1 means the data scales linearly.\nA degree of 2 means the data scales quadratically.\nA degree of 3 means the data scales cubically.\n\nPlease note that regression model is fit to Power Pin data relative to the position data instead of absolute.\n\nAkatsumekusa recommends setting this value to the exact polynomial degree of the data, as setting it too high may cause overfitting.\n\nFor more information, please visit „https://scikit-learn.org/stable/modules/linear_model.html#polynomial-regression-extending-linear-models-with-basis-functions“ and „https://en.wikipedia.org/wiki/Polynomial_regression“",
default=2,
min=1,
soft_max=16)
smoothing_position_regressor: bpy.props.EnumProperty(items=(("HUBER", "Huber Regressor", "Huber Regressor is an L2-regularised regression model that is robust to outliers.\n\nFor more information, visit „https://scikit-learn.org/stable/modules/linear_model.html#robustness-regression-outliers-and-modeling-errors“ and „https://en.wikipedia.org/wiki/Huber_loss“"),
("LASSO", "Lasso Regressor", "Lasso Regressor is an L1-regularised regression model.\n\nFor more information, please visit „https://scikit-learn.org/stable/modules/linear_model.html#lasso“ and „https://en.wikipedia.org/wiki/Lasso_(statistics)“"),
("LINEAR", "Linear Regressor", "Ordinary least squares regression model.\n\nFor more information, please visit „https://scikit-learn.org/stable/modules/linear_model.html#ordinary-least-squares“ and „https://en.wikipedia.org/wiki/Ordinary_least_squares“")),
name="Linear Model",
default="LINEAR")
smoothing_position_huber_epsilon: bpy.props.FloatProperty(name="Epsilon",
description="The epsilon of a Huber Regressor controls the number of samples that should be classified as outliers. The smaller the epsilon, the more robust it is to outliers.\n\nFor more information, please visit „https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.HuberRegressor.html“",
default=1.50,
min=1.00,
soft_max=10.00,
step=1,
precision=2)
smoothing_position_lasso_alpha: bpy.props.FloatProperty(name="Alpha",
description="The alpha of a Lasso Regressor controls the regularisation strength.\n\nFor more information, please visit „https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Lasso.html“",
default=0.10,
min=0.00,
soft_max=100.0,
step=1,
precision=2)
smoothing_do_predictive_smoothing: bpy.props.BoolProperty(name="Predictive Filling",
description="Generates position data, scale data, rotation data and Power Pin data over the whole length of the clip, even if the track or plane track is only enabled on a section of the clip.\n\nThe four options above, „Smooth Position“, „Smooth Scale“, „Smooth Rotation“ and „Smooth Power Pin“, decides whether to use predicted data to replace the existing data on frames where the track is enabled, while this option decides whether to use predicted data to fill the gaps in the frames where the marker is not enabled.\n\nAkatsumekusa recommends enabling this option only if the subtitle line covers the whole length of the trimmed clip",
default=False)
do_also_export: bpy.props.BoolProperty(name="Auto export",
description="Automatically export the selected track to file while copying",
default=True)
do_do_not_overwrite: bpy.props.BoolProperty(name="Do not overwrite",
description="Generate unique files every time",
default=False)
class AAEExportExportAll(bpy.types.Operator):
bl_label = "Export"
bl_description = "Export all tracking markers and plane tracks to AAE files next to the original movie clip"
bl_idname = "movieclip.aae_export_export_all"
def execute(self, context):
clip = context.edit_movieclip
settings = context.screen.AAEExportSettings
for track in clip.tracking.tracks:
AAEExportExportAll._export_to_file(clip, track, AAEExportExportAll._generate(clip, track, settings), None, settings.do_do_not_overwrite)
for plane_track in clip.tracking.plane_tracks:
AAEExportExportAll._export_to_file(clip, plane_track, AAEExportExportAll._generate(clip, plane_track, settings), None, settings.do_do_not_overwrite)
return { "FINISHED" }
@staticmethod
def _generate(clip, track, settings):
"""
Parameters
----------
clip : bpy.types.MovieClip
track : bpy.types.MovieTrackingTrack or bpy.types.MovieTrackingPlaneTrack
settings : AAEExportSettings or None
AAEExportSettings.
Returns
-------
aae : str
"""
if is_smoothing_modules_available:
ratio, multiplier \
= AAEExportExportAll._calculate_aspect_ratio( \
clip)
position, scale, semilimited_rotation, power_pin \
= AAEExportExportAll._prepare_data( \
clip, track, ratio)
if settings.do_smoothing:
position \
= AAEExportExportAll._smoothing( \
position, \
settings.smoothing_do_position, settings.smoothing_do_predictive_smoothing, \
settings.smoothing_position_degree, \
settings.smoothing_position_regressor, settings.smoothing_position_huber_epsilon, settings.smoothing_position_lasso_alpha)
scale \
= AAEExportExportAll._smoothing( \
scale, \
settings.smoothing_do_scale, settings.smoothing_do_predictive_smoothing, \
settings.smoothing_scale_degree, \
settings.smoothing_position_regressor, settings.smoothing_position_huber_epsilon, settings.smoothing_position_lasso_alpha)
rotation \
= AAEExportExportAll._unlimit_rotation( \
semilimited_rotation)
rotation \
= AAEExportExportAll._smoothing( \
rotation, \
settings.smoothing_do_rotation, settings.smoothing_do_predictive_smoothing, \
settings.smoothing_rotation_degree, \
settings.smoothing_position_regressor, settings.smoothing_position_huber_epsilon, settings.smoothing_position_lasso_alpha)
limited_rotation \
= AAEExportExportAll._limit_rotation( \
rotation)
for i in range(4):
power_pin[i] \
= AAEExportExportAll._smoothing( \
power_pin[i], \
settings.smoothing_do_power_pin, settings.smoothing_do_predictive_smoothing, \
settings.smoothing_power_pin_degree, \
settings.smoothing_position_regressor, settings.smoothing_position_huber_epsilon, settings.smoothing_position_lasso_alpha)
else:
limited_rotation \
= AAEExportExportAll._limit_rotation( \
semilimited_rotation)
aae_position, aae_scale, aae_rotation, aae_power_pin_0002, aae_power_pin_0003, aae_power_pin_0004, aae_power_pin_0005 \
= AAEExportExportAll._generate_aae( \
position, scale, limited_rotation, power_pin, \
multiplier)
else: # not is_smoothing_modules_available
aae_position, aae_scale, aae_rotation, aae_power_pin_0002, aae_power_pin_0003, aae_power_pin_0004, aae_power_pin_0005 \
= AAEExportExportAll._generate_aae_non_numpy( \
clip, track)
aae \
= AAEExportExportAll._combine_aae( \
clip, \
aae_position, aae_scale, aae_rotation, aae_power_pin_0002, aae_power_pin_0003, aae_power_pin_0004, aae_power_pin_0005, \
settings.do_includes_power_pin)
return aae
@staticmethod
def _plot_graph(clip, track, settings):
"""
Parameters
----------
clip : bpy.types.MovieClip
track : bpy.types.MovieTrackingTrack or bpy.types.MovieTrackingPlaneTrack
settings : AAEExportSettings or None
AAEExportSettings.
Returns
-------
aae : str
"""
import numpy as np
ratio, multiplier \
= AAEExportExportAll._calculate_aspect_ratio( \
clip)
position, scale, semilimited_rotation, power_pin \
= AAEExportExportAll._prepare_data( \
clip, track, ratio)
smoothed_position \
= AAEExportExportAll._smoothing( \
position, \
settings.smoothing_do_position, settings.smoothing_do_predictive_smoothing, \
settings.smoothing_position_degree, \
settings.smoothing_position_regressor, settings.smoothing_position_huber_epsilon, settings.smoothing_position_lasso_alpha)
smoothed_scale \
= AAEExportExportAll._smoothing( \
scale, \
settings.smoothing_do_scale, settings.smoothing_do_predictive_smoothing, \
settings.smoothing_scale_degree, \
settings.smoothing_position_regressor, settings.smoothing_position_huber_epsilon, settings.smoothing_position_lasso_alpha)
rotation \
= AAEExportExportAll._unlimit_rotation( \
semilimited_rotation)
smoothed_rotation \
= AAEExportExportAll._smoothing( \
rotation, \
settings.smoothing_do_rotation, settings.smoothing_do_predictive_smoothing, \
settings.smoothing_rotation_degree, \
settings.smoothing_position_regressor, settings.smoothing_position_huber_epsilon, settings.smoothing_position_lasso_alpha)
smoothed_power_pin \
= np.empty_like(power_pin)
for i in range(4):
smoothed_power_pin[i] \
= AAEExportExportAll._smoothing( \
power_pin[i], \
settings.smoothing_do_power_pin, settings.smoothing_do_predictive_smoothing, \
settings.smoothing_power_pin_degree, \
settings.smoothing_position_regressor, settings.smoothing_position_huber_epsilon, settings.smoothing_position_lasso_alpha)
AAEExportExportAll._plot( \
position, scale, rotation, power_pin, \
smoothed_position, smoothed_scale, smoothed_rotation, smoothed_power_pin, \
settings.smoothing_do_position, settings.smoothing_do_scale, settings.smoothing_do_rotation, settings.smoothing_do_power_pin)
@staticmethod
def _calculate_aspect_ratio(clip):
"""
Calculate aspect ratio.
Parameters
----------
clip : bpy.types.MovieClip
Returns
-------
ratio : npt.NDArray[float64]
multiplier: float
"""
import numpy as np
ar = clip.size[0] / clip.size[1]
# As of 2021/2022
if ar < 1 / 1.35: # 9:16, 9:19 and higher videos
return np.array([1 / 1.35, 1 / 1.35 / ar], dtype=np.float64), clip.size[0] / 1 * 1.35
elif ar < 1: # vertical videos from 1:1, 3:4, up to 1:1.35
return np.array([ar, 1], dtype=np.float64), clip.size[1]
elif ar <= 1.81: # 1:1, 4:3, 16:9, up to 1920 x 1061
return np.array([ar, 1], dtype=np.float64), clip.size[1]
else: # Ultrawide
return np.array([1.81, 1.81 / ar], dtype=np.float64), clip.size[0] / 1.81
@staticmethod
def _prepare_data(clip, track, ratio):
"""
Create position, scale, rotation and Power Pin array from tracking markers. [Step 04]
Parameters
----------
clip : bpy.types.MovieClip
track : bpy.types.MovieTrackingTrack or bpy.types.MovieTrackingPlaneTrack
ratio : npt.NDArray[float]
ratio likely from Step 03
Returns
-------
position : npt.NDArray[float64]
scale : npt.NDArray[float64]
semilimited_rotation : npt.NDArray[float64]
power_pin : npt.NDArray[float64]
"""
if track.__class__.__name__ == "MovieTrackingTrack":
position, misshapen_power_pin \
= AAEExportExportAll._prepare_position_and_misshapen_power_pin_marker_track( \
clip, track, ratio)
elif track.__class__.__name__ == "MovieTrackingPlaneTrack":
position, misshapen_power_pin \
= AAEExportExportAll._prepare_position_and_misshapen_power_pin_plane_track( \
clip, track, ratio)
else:
raise ValueError("track.__class__.__name__ \"" + track.__class__.__name__ + "\" not recognised")
scale, semilimited_rotation \
= AAEExportExportAll._prepare_scale_and_semilimited_rotation( \
misshapen_power_pin)
power_pin \
= AAEExportExportAll._prepare_power_pin( \
misshapen_power_pin)
return position, scale, semilimited_rotation, power_pin
@staticmethod
def _prepare_position_and_misshapen_power_pin_marker_track(clip, track, ratio):
"""
Create position and misshapen_power_pin array from marker track.
Parameters
----------
clip : bpy.types.MovieClip
track : bpy.types.MovieTrackingTrack
ratio : npt.NDArray[float]
Returns
-------
position : npt.NDArray[float64]
misshapen_power_pin : npt.NDArray[float64]
As explained below.
"""
import numpy as np
if not clip.frame_duration >= 1:
raise ValueError("clip.frame_duration must be greater than or equal to 1")
# position array structure
# +----------+----------------------------------------------------------+
# | | Frame 0 Frame 1 Frame 2 Frame 3 Frame 4 |
# +----------+----------------------------------------------------------+
# | Position | array([ [x, y], [x, y], [x, y], [x, y], [x, y] ]) |
# +----------+----------------------------------------------------------+
# The origin will be located at the upper left corner of the video,
# contrary to Blender's usual lower left corner.
#
# The x and y value will have a pixel aspect ratio of 1:1. See
# _calculate_aspect_ratio for the range where x and y value is on
# screen.
#
# The start frame of a video will be frame 0, instead of Blender's
# usual frame 1.
#
# Also, on the topic of precision, NC AAE Export uses float64 across
# the whole script instead of Blender's float32.
position = np.full((clip.frame_duration, 2), np.nan, dtype=np.float64)
# power_pin array structure
# +--------------------+------------------------------------------------------------+
# | | Frame 0 Frame 1 Frame 2 Frame 3 Frame 4 |
# +--------------------+------------------------------------------------------------+
# | Upper-Left Corner | array([[ [x, y], [x, y], [x, y], [x, y], [x, y] ], |
# | (Power Pin-0002) | |
# | Upper-Right Corner | [ [x, y], [x, y], [x, y], [x, y], [x, y] ], |
# | (Power Pin-0003) | |
# | Lower-Left Corner | [ [x, y], [x, y], [x, y], [x, y], [x, y] ], |
# | (Power Pin-0004) | |
# | Lower-Right Corner | [ [x, y], [x, y], [x, y], [x, y], [x, y] ]]) |
# | (Power Pin-0005) | |
# +--------------------+------------------------------------------------------------+
# power pin position is not absolute and is relative to the position
# array
#
# misshapen_power_pin array structure
# +---------+-----------------------------------------------------------------+
# | | Upper-Left Upper-Right Lower-Left Lower-Right |
# +---------+-----------------------------------------------------------------+
# | Frame 0 | array([[ x, y, x, y, x, y x, y ], |
# | Frame 1 | [ x, y, x, y, x, y x, y ], |
# | Frame 2 | [ x, y, x, y, x, y x, y ], |
# | Frame 3 | [ x, y, x, y, x, y x, y ], |
# | Frame 4 | [ x, y, x, y, x, y x, y ]]) |
# +---------+-----------------------------------------------------------------+
misshapen_power_pin = np.full((clip.frame_duration, 8), np.nan, dtype=np.float64)
for marker in track.markers:
if not 0 < marker.frame <= clip.frame_duration:
continue
if marker.mute:
continue
position[marker.frame - 1] = [marker.co[0], 1 - marker.co[1]]
misshapen_power_pin[marker.frame - 1] = [marker.pattern_corners[3][0], -marker.pattern_corners[3][1], \
marker.pattern_corners[2][0], -marker.pattern_corners[2][1], \
marker.pattern_corners[0][0], -marker.pattern_corners[0][1], \
marker.pattern_corners[1][0], -marker.pattern_corners[1][1]]
position *= ratio
misshapen_power_pin *= np.tile(ratio, 4)
return position, misshapen_power_pin
@staticmethod
def _prepare_position_and_misshapen_power_pin_plane_track(clip, track, ratio):
"""
Create position and misshapen_power_pin array from plane track.
Parameters
----------
clip : bpy.types.MovieClip
track : bpy.types.MovieTrackingTrack
ratio : npt.NDArray[float]
Returns
-------
position : npt.NDArray[float64]
misshapen_power_pin : npt.NDArray[float64]
As explained in _prepare_position_and_power_pin_marker_track().
"""
import numpy as np
import numpy.linalg as LA
if not clip.frame_duration >= 1:
raise ValueError("clip.frame_duration must be greater than or equal to 1")
# As explained in _prepare_position_and_power_pin_marker_track()
misshapen_power_pin = np.full((clip.frame_duration, 8), np.nan, dtype=np.float64)
for marker in track.markers:
if not 0 < marker.frame <= clip.frame_duration:
continue
if marker.mute:
continue
misshapen_power_pin[marker.frame - 1] = [marker.corners[3][0], 1 - marker.corners[3][1],
marker.corners[2][0], 1 - marker.corners[2][1],
marker.corners[0][0], 1 - marker.corners[0][1],
marker.corners[1][0], 1 - marker.corners[1][1]]
misshapen_power_pin *= np.tile(ratio, 4)
# This is discarded due to it being unstable, despite its slightly
# faster speed.
# https://stackoverflow.com/questions/563198/
# def eat(slice):
# if slice[0] == np.nan:
# return np.full((2), np.nan, dtype=np.float64)
# else:
# p = slice[0:2]
# r = slice[6:8] - slice[0:2]
# q = slice[4:6]
# s = slice[2:4] - slice[4:6]
# t = np.cross((q - p), s) / np.cross(r, s)
# return p + t * r
# https://stackoverflow.com/questions/563198/
def eat_(slice):
if np.isnan(slice[0]):
return np.full((2), np.nan, dtype=np.float64)
try:
t = LA.solve(np.transpose(np.vstack((slice[6:8] - slice[0:2], slice[2:4] - slice[4:6]))), slice[2:4] - slice[0:2])[0]
except LA.LinAlgError:
return np.mean(slice.reshape((4, 2)), axis=0)
else:
return (1 - t) * slice[0:2] + t * slice[6:8]
position = np.apply_along_axis(eat_, 1, misshapen_power_pin)
misshapen_power_pin -= np.tile(position, 4)
return position, misshapen_power_pin
@staticmethod
def _prepare_scale_and_semilimited_rotation(misshapen_power_pin):
"""
Create scale and rotation array.
Parameters
----------
misshapen_power_pin : npt.NDArray[float64]
Returns
-------
scale : npt.NDArray[float64]
scale is a 2D array unmultiplied.
semilimited_rotation : npt.NDArray[float64]
rotation is an 1D array unmultiplied as well.
"""
import numpy as np
import numpy.linalg as LA
# https://stackoverflow.com/questions/1401712/
scale_x = LA.norm(misshapen_power_pin[:, 0:2] - misshapen_power_pin[:, 2:4] + misshapen_power_pin[:, 4:6] - misshapen_power_pin[:, 6:8], axis=1)
scale_y = LA.norm(misshapen_power_pin[:, 0:2] - misshapen_power_pin[:, 4:6] + misshapen_power_pin[:, 2:4] - misshapen_power_pin[:, 6:8], axis=1)
scale = np.hstack((scale_x.reshape((-1, 1)), scale_y.reshape((-1, 1))))
try:
scale /= scale[np.nonzero(~np.isnan(scale_x))[0][0]]
except IndexError:
raise ValueError("At least one marker in track.markers needs to be not marker.mute")
rotation_x = (misshapen_power_pin[:, 0] + misshapen_power_pin[:, 2]) / 2
rotation_y = (misshapen_power_pin[:, 1] + misshapen_power_pin[:, 3]) / 2
semilimited_rotation = np.arctan2(rotation_x, -rotation_y)
return scale, semilimited_rotation
@staticmethod
def _prepare_power_pin(misshapen_power_pin):
"""
Create scale and rotation array.
Parameters
----------
misshapen_power_pin : npt.NDArray[float64]
Returns
-------
power_pin : npt.NDArray[float64]
"""
import numpy as np
return np.swapaxes(misshapen_power_pin.reshape((-1, 4, 2)), 0, 1)
@staticmethod
def _smoothing(data, do_smoothing, do_predictive_smoothing, degree, regressor, huber_epsilon, lasso_alpha):
"""
Perform smoothing depending on the smoothing settings.
Parameters
----------
data : npt.NDArray[float64]
position, scale, rotation and each power_pin
do_smoothing : bool
do_predictive_smoothing : bool
degree : int
regressor : str
huber_epsilon : int
lasso_alpha : int
Returns
-------
data : npt.NDArray[float64]
"""
import numpy as np
if data.ndim == 2:
predicted_data \
= np.empty_like(data)
for i in range(data.shape[1]):
predicted_data[:, i] \
= AAEExportExportAll._smoothing( \
data[:, i], do_smoothing, do_predictive_smoothing, degree, regressor, huber_epsilon, lasso_alpha)
return predicted_data
elif data.ndim == 1:
match (do_smoothing << 1) + do_predictive_smoothing: # match case requires Python 3.10 (Blender 3.1)
case 0b11:
predicted_data = AAEExportExportAll._smoothing_univariate(data, degree, regressor, huber_epsilon, lasso_alpha)
return predicted_data
case 0b10:
predicted_data = AAEExportExportAll._smoothing_univariate(data, degree, regressor, huber_epsilon, lasso_alpha)
predicted_data[np.isnan(data)] = np.nan
return predicted_data
case 0b01:
predicted_data = AAEExportExportAll._smoothing_univariate(data, degree, regressor, huber_epsilon, lasso_alpha)
data[np.isnan(data)] = predicted_data[np.isnan(data)]
return data
case 0b00:
return data
else:
raise ValueError("data.ndim must be either 1 or 2")
@staticmethod
def _smoothing_univariate(data, degree, regressor, huber_epsilon, lasso_alpha):
"""
Perform smoothing depending on the smoothing settings.
Parameters
----------
data : npt.NDArray[float64]
univariate data
degree : int
regressor : str
huber_epsilon : int
lasso_alpha : int
Returns
-------
predicted_data : npt.NDArray[float64]
data with all frames filled with predicted value
"""
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import HuberRegressor, Lasso, LinearRegression
from sklearn.pipeline import Pipeline
X = np.arange(data.shape[0])[(index := ~np.isnan(data))].reshape(-1, 1) # := requires Python 3.8 (Blender 2.93)
y = data[index]
if regressor == "HUBER":
return Pipeline([("poly", PolynomialFeatures(degree=degree)), \
("huber", HuberRegressor(epsilon=huber_epsilon))]) \
.fit(X, y) \
.predict(np.arange(data.shape[0]).reshape(-1, 1))
elif regressor == "LASSO":
return Pipeline([("poly", PolynomialFeatures(degree=degree)), \
("lasso", Lasso(alpha=lasso_alpha))]) \
.fit(X, y) \
.predict(np.arange(data.shape[0]).reshape(-1, 1))
elif regressor == "LINEAR":
return Pipeline([("poly", PolynomialFeatures(degree=degree)), \
("regressor", LinearRegression())]) \
.fit(X, y) \
.predict(np.arange(data.shape[0]).reshape(-1, 1))
else:
raise ValueError("regressor " + regressor + " not recognised")
@staticmethod
def _unlimit_rotation(semilimited_rotation):
"""
Unlimit the rotation.
Parameters
----------
semilimited_rotation : npt.NDArray[float64]
Returns
-------
rotation : npt.NDArray[float64]
"""
import numpy as np
diff = np.diff(semilimited_rotation)
for i in np.nonzero(diff > np.pi)[0]:
semilimited_rotation[i+1:] -= 2 * np.pi
for i in np.nonzero(diff <= -np.pi)[0]:
semilimited_rotation[i+1:] += 2 * np.pi
return semilimited_rotation
@staticmethod
def _limit_rotation(rotation):
"""
Limit the rotation.
Parameters
----------
rotation : npt.NDArray[float64]
Returns
-------
limited_rotation : npt.NDArray[float64]
"""
import numpy as np
return np.remainder(rotation, 2 * np.pi)
@staticmethod
def _generate_aae(position, scale, limited_rotation, power_pin, multiplier):
"""
Finalised and stringify the data.
Parameters
----------
position : npt.NDArray[float64]
scale : npt.NDArray[float64]
limited_rotation : npt.NDArray[float64]
power_pin : npt.NDArray[float64]
multiplier: float
Returns
-------
aae_position : list[str]
aae_scale : list[str]
aae_rotation : list[str]
aae_power_pin_0002 : list[str]
aae_power_pin_0003 : list[str]
aae_power_pin_0004 : list[str]
aae_power_pin_0005 : list[str]
"""
import numpy as np
position *= multiplier
scale *= 100.0
limited_rotation *= 180.0 / np.pi
limited_rotation[limited_rotation >= 359.9995] = 0.0
power_pin *= multiplier
power_pin += position
aae_position = []
aae_scale = []
aae_rotation = []
aae_power_pin_0002 = []
aae_power_pin_0003 = []
aae_power_pin_0004 = []
aae_power_pin_0005 = []
for frame in range(position.shape[0]):
if not np.isnan(position[frame][0]):
aae_position.append("\t{:d}\t{:.3f}\t{:.3f}\t{:.3f}".format(frame + 1, *position[frame], 0.0))
if not np.isnan(scale[frame][0]):
aae_scale.append("\t{:d}\t{:.3f}\t{:.3f}\t{:.3f}".format(frame + 1, *scale[frame], 100.0))
if not np.isnan(limited_rotation[frame]):
aae_rotation.append("\t{:d}\t{:.3f}".format(frame + 1, limited_rotation[frame]))
if not np.isnan(power_pin[0][frame][0]):
aae_power_pin_0002.append("\t{:d}\t{:.3f}\t{:.3f}".format(frame + 1, *power_pin[0][frame]))
aae_power_pin_0003.append("\t{:d}\t{:.3f}\t{:.3f}".format(frame + 1, *power_pin[1][frame]))
aae_power_pin_0004.append("\t{:d}\t{:.3f}\t{:.3f}".format(frame + 1, *power_pin[2][frame]))
aae_power_pin_0005.append("\t{:d}\t{:.3f}\t{:.3f}".format(frame + 1, *power_pin[3][frame]))
return aae_position, aae_scale, aae_rotation, aae_power_pin_0002, aae_power_pin_0003, aae_power_pin_0004, aae_power_pin_0005
@staticmethod
def _plot(position, scale, rotation, power_pin, smoothed_position, smoothed_scale, smoothed_rotation, smoothed_power_pin, smoothing_do_position, smoothing_do_scale, smoothing_do_rotation, smoothing_do_power_pin):
"""
Plot the data.
Parameters
----------
position : npt.NDArray[float64]
scale : npt.NDArray[float64]
rotation : npt.NDArray[float64]
power_pin : npt.NDArray[float64]
smoothed_position : npt.NDArray[float64]
smoothed_scale : npt.NDArray[float64]
smoothed_rotation : npt.NDArray[float64]
smoothed_power_pin : npt.NDArray[float64]
"""
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import PIL
import re
def plot_position(row, position, smoothed_position, label, do_smoothing):
def test_z_score(data):
# Iglewicz and Hoaglin's modified Z-score
return np.nonzero(0.6745 * (d := np.absolute(data - np.median(data))) / np.median(d) >= 3)[0]
row[0].invert_yaxis()
row[0].scatter(position[:, 0], position[:, 1], color="red", marker="x", s=1, label="_".join(re.split(" |_", label.lower())), zorder=2.001)
if do_smoothing:
row[0].plot(smoothed_position[:, 0], smoothed_position[:, 1], color="blue", label="_".join(["smoothed"] + re.split(" |_", label.lower())), zorder=2.002)
row[0].legend()
row[0].set_xlabel("X")
row[0].set_ylabel("Y")
row[1].scatter(np.arange(1, position.shape[0] + 1), position[:, 0], color="red", s=1, label="_".join(re.split(" |_", label.lower())), zorder=2.001)
if do_smoothing:
row[1].plot(np.arange(1, position.shape[0] + 1), smoothed_position[:, 0], color="blue", label="_".join(["smoothed"] + re.split(" |_", label.lower())), zorder=2.002)
row[1].legend()
row[1].set_xlabel("Frame")
row[1].set_ylabel(" ".join(list(map(lambda w : w.capitalize(), re.split(" |_", label)))) + " X")
if do_smoothing:
row[2].plot(np.arange(1, position.shape[0] + 1), (p := position[:, 0] - smoothed_position[:, 0]), color="red", label="_".join(re.split(" |_", label.lower())), zorder=2.002)
row[2].plot(np.arange(1, position.shape[0] + 1), smoothed_position[:, 0] - smoothed_position[:, 0], color="blue", label="_".join(["smoothed"] + re.split(" |_", label.lower())), zorder=2.001)
for i in test_z_score(p):
row[2].annotate(i + 1, (i + 1, p[i]))
row[2].legend()
row[2].set_xlabel("Frame")
row[2].set_ylabel("Residual of " + " ".join(list(map(lambda w : w.capitalize(), re.split(" |_", label)))) + " X")
else:
row[2].axis("off")
row[3].scatter(np.arange(1, position.shape[0] + 1), position[:, 1], color="red", s=1, label="_".join(re.split(" |_", label.lower())), zorder=2.001)
if do_smoothing:
row[3].plot(np.arange(1, position.shape[0] + 1), smoothed_position[:, 1], color="blue", label="_".join(["smoothed"] + re.split(" |_", label.lower())), zorder=2.002)
row[3].legend()
row[3].set_xlabel("Frame")
row[3].set_ylabel(" ".join(list(map(lambda w : w.capitalize(), re.split(" |_", label)))) + " Y")
if do_smoothing:
row[4].plot(np.arange(1, position.shape[0] + 1), (p := position[:, 1] - smoothed_position[:, 1]), color="red", label="_".join(re.split(" |_", label.lower())), zorder=2.002)
row[4].plot(np.arange(1, position.shape[0] + 1), smoothed_position[:, 1] - smoothed_position[:, 1], color="blue", label="_".join(["smoothed"] + re.split(" |_", label.lower())), zorder=2.001)
for i in test_z_score(p):
row[4].annotate(i + 1, (i + 1, p[i]))
row[4].legend()
row[4].set_xlabel("Frame")
row[4].set_ylabel("Residual of " + " ".join(list(map(lambda w : w.capitalize(), re.split(" |_", label)))) + " Y")
else:
row[4].axis("off")
def plot_univariate(row, rotation, smoothed_rotation, label, do_smoothing):
row[0].axis("off")
row[1].scatter(np.arange(1, rotation.shape[0] + 1), rotation, color="red", s=1, label="_".join(re.split(" |_", label.lower())), zorder=2.001)
if do_smoothing:
row[1].plot(np.arange(1, rotation.shape[0] + 1), smoothed_rotation, color="blue", label="_".join(["smoothed"] + re.split(" |_", label.lower())), zorder=2.002)
row[1].legend()
row[1].set_xlabel("Frame")
row[1].set_ylabel(label.title())
if do_smoothing:
row[2].plot(np.arange(1, rotation.shape[0] + 1), rotation - smoothed_rotation, color="red", label="_".join(re.split(" |_", label.lower())), zorder=2.002)
row[2].plot(np.arange(1, rotation.shape[0] + 1), smoothed_rotation - smoothed_rotation, color="blue", label="_".join(["smoothed"] + re.split(" |_", label.lower())), zorder=2.001)
row[2].legend()
row[2].set_xlabel("Frame")
row[2].set_ylabel("Residual of " + " ".join(list(map(lambda w : w.capitalize(), re.split(" |_", label)))))
else:
row[2].axis("off")
row[3].axis("off")
row[4].axis("off")
fig, axs = plt.subplots(ncols=5, nrows=7, figsize=(5 * 5.4, 7 * 4.05), dpi=250, layout="constrained")
plot_position(axs[0], position, smoothed_position, "position", smoothing_do_position)
plot_position(axs[1], scale, smoothed_scale, "scale", smoothing_do_scale)
plot_univariate(axs[2], rotation, smoothed_rotation, "rotation", smoothing_do_rotation)
plot_position(axs[3], power_pin[0], smoothed_power_pin[0], "power_pin_0002", smoothing_do_power_pin)
plot_position(axs[4], power_pin[1], smoothed_power_pin[1], "power_pin_0003", smoothing_do_power_pin)
plot_position(axs[5], power_pin[2], smoothed_power_pin[2], "power_pin_0004", smoothing_do_power_pin)
plot_position(axs[6], power_pin[3], smoothed_power_pin[3], "power_pin_0005", smoothing_do_power_pin)
fig.canvas.draw()
with PIL.Image.frombytes("RGB", fig.canvas.get_width_height(), fig.canvas.tostring_rgb()) as im:
im.show()
@staticmethod
def _generate_aae_non_numpy(clip, track):
"""
Generate aae without numpy.
Parameters
----------
clip : bpy.types.MovieClip
track : bpy.types.MovieTrackingTrack or bpy.types.MovieTrackingPlaneTrack
Returns
-------
aae_position : list[str]
aae_scale : list[str]
aae_rotation : list[str]
aae_power_pin_0002 : list[str]
aae_power_pin_0003 : list[str]
aae_power_pin_0004 : list[str]
aae_power_pin_0005 : list[str]
"""
aae_position = []
aae_scale = []
aae_rotation = []
aae_power_pin_0002 = []
aae_power_pin_0003 = []
aae_power_pin_0004 = []
aae_power_pin_0005 = []
scale_base = None
if track.__class__.__name__ == "MovieTrackingTrack":
for marker in track.markers:
if not 0 < marker.frame <= clip.frame_duration:
continue
if marker.mute:
continue
position, scale, rotation, power_pin_0002, power_pin_0003, power_pin_0004, power_pin_0005, \
scale_base \
= AAEExportExportAll._calculate_marker_track_per_frame_non_numpy( \
clip, marker, scale_base)
AAEExportExportAll._generate_aae_per_frame_non_numpy( \
marker, \
aae_position, aae_scale, aae_rotation, aae_power_pin_0002, aae_power_pin_0003, aae_power_pin_0004, aae_power_pin_0005, \
position, scale, rotation, power_pin_0002, power_pin_0003, power_pin_0004, power_pin_0005)
elif track.__class__.__name__ == "MovieTrackingPlaneTrack":
for marker in track.markers:
if not 0 < marker.frame <= clip.frame_duration:
continue
if marker.mute:
continue
position, scale, rotation, power_pin_0002, power_pin_0003, power_pin_0004, power_pin_0005, \
scale_base \
= AAEExportExportAll._calculate_plane_track_per_frame_non_numpy( \
clip, marker, scale_base)
AAEExportExportAll._generate_aae_per_frame_non_numpy( \
marker, \
aae_position, aae_scale, aae_rotation, aae_power_pin_0002, aae_power_pin_0003, aae_power_pin_0004, aae_power_pin_0005, \
position, scale, rotation, power_pin_0002, power_pin_0003, power_pin_0004, power_pin_0005)
else:
raise ValueError("track.__class__.__name__ \"" + track.__class__.__name__ + "\" not recognised")
return aae_position, aae_scale, aae_rotation, aae_power_pin_0002, aae_power_pin_0003, aae_power_pin_0004, aae_power_pin_0005
@staticmethod
def _calculate_marker_track_per_frame_non_numpy(clip, marker, scale_base):
"""
Generate data without numpy.
Parameters
----------
clip : bpy.types.MovieClip
marker : bpy.types.MovieTrackingMarker
scale_base : tuple[float] or None
Returns
-------
position : tuple[float]
scale : tuple[float]
rotate : float
power_pin_0002 : tuple[float]
power_pin_0003 : tuple[float]
power_pin_0004 : tuple[float]
power_pin_0005 : tuple[float]
scale_base : tuple[float]
"""
import math
position = (float(marker.co[0]) * clip.size[0],