forked from WolframRhodium/muvsfunc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
muvsfunc.py
5880 lines (4355 loc) · 247 KB
/
muvsfunc.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
'''
Functions:
LDMerge
Compare (2)
ExInpand
InDeflate
MultiRemoveGrain
GradFun3
AnimeMask (2)
PolygonExInpand
Luma
ediaa
nnedi3aa
maa
SharpAAMcmod
TEdge
Sort
Soothe_mod
TemporalSoften
FixTelecinedFades
TCannyHelper
MergeChroma
firniture
BoxFilter
SmoothGrad
DeFilter
scale
ColorBarsHD
SeeSaw
abcxyz
Sharpen
Blur
BlindDeHalo3
dfttestMC
TurnLeft
TurnRight
BalanceBorders
DisplayHistogram
GuidedFilter (Color)
GMSD
SSIM
SSIM_downsample
LocalStatisticsMatching
LocalStatistics
TextSub16
TMinBlur
mdering
BMAFilter
LLSURE
YAHRmod
RandomInterleave
super_resolution
MDSI
MaskedLimitFilter
@multi_scale
avg_decimate
YAHRmask
Cdeblend
S_BoxFilter
VFRSplice
MSR
getnative
'''
import functools
import itertools
import math
import operator
from collections import abc
import numbers
import typing
from typing import Any, Callable, Dict, Iterable, List, Optional
from typing import Sequence, Tuple, TypeVar, Union
import vapoursynth as vs
from vapoursynth import core
import havsfunc as haf
import mvsfunc as mvf
_has_lexpr: bool = (
hasattr(core, "akarin") and
b'x.property' in core.akarin.Version()["expr_features"]
)
_has_lexpr_lutspa: bool = (
hasattr(core, "akarin") and
b'X' in core.akarin.Version()["expr_features"]
)
# Type aliases
PlanesType = Optional[Union[int, Sequence[int]]]
VSFuncType = Union[vs.Func, Callable[..., vs.VideoNode]]
# Function alias
nnedi3: Optional[Callable[..., vs.VideoNode]] = core.nnedi3.nnedi3 if hasattr(core, "nnedi3") else None
def LDMerge(flt_h: vs.VideoNode, flt_v: vs.VideoNode, src: vs.VideoNode, mrad: int = 0,
show: bool = False, planes: PlanesType = None,
convknl: int = 1, conv_div: Optional[int] = None, calc_mode: int = 0,
power: float = 1.0
) -> vs.VideoNode:
"""Merges two filtered clips based on the gradient direction map from a source clip.
Args:
flt_h, flt_v: Two filtered clips.
src: Source clip. Must be the same format as the filtered clips.
mrad: (int) Expanding of gradient direction map. Default is 0.
show: (bool) Whether to output gradient direction map. Default is False.
planes: (int []) Whether to process the corresponding plane. By default, every plane will be processed.
The unprocessed planes will be copied from the first clip, "flt_h".
convknl: (0 or 1) Convolution kernel used to generate gradient direction map.
0: Seconde order center difference in one direction and average in perpendicular direction
1: First order center difference in one direction and weighted average in perpendicular direction.
Default is 1.
conv_div: (int) Divisor in convolution filter. Default is the max value in convolution kernel.
calc_mode: (0 or 1) Method used to calculate the gradient direction map. Default is 0.
power: (float) Power coefficient in "calc_mode=0".
Example:
# Fast anti-aliasing
horizontal = core.std.Convolution(clip, matrix=[1, 4, 0, 4, 1], planes=[0], mode='h')
vertical = core.std.Convolution(clip, matrix=[1, 4, 0, 4, 1], planes=[0], mode='v')
blur_src = core.tcanny.TCanny(clip, mode=-1, planes=[0]) # Eliminate noise
antialiasing = muf.LDMerge(horizontal, vertical, blur_src, mrad=1, planes=[0])
"""
funcName = 'LDMerge'
if not isinstance(src, vs.VideoNode):
raise TypeError(funcName + ': \"src\" must be a clip!')
if not isinstance(flt_h, vs.VideoNode):
raise TypeError(funcName + ': \"flt_h\" must be a clip!')
if src.format.id != flt_h.format.id:
raise TypeError(funcName + ': \"flt_h\" must be of the same format as \"src\"!')
if src.width != flt_h.width or src.height != flt_h.height:
raise TypeError(funcName + ': \"flt_h\" must be of the same size as \"src\"!')
if not isinstance(flt_v, vs.VideoNode):
raise TypeError(funcName + ': \"flt_v\" must be a clip!')
if src.format.id != flt_v.format.id:
raise TypeError(funcName + ': \"flt_v\" must be of the same format as \"src\"!')
if src.width != flt_v.width or src.height != flt_v.height:
raise TypeError(funcName + ': \"flt_v\" must be of the same size as \"src\"!')
if not isinstance(mrad, int):
raise TypeError(funcName + '\"mrad\" must be an int!')
if not isinstance(show, int):
raise TypeError(funcName + '\"show\" must be an int!')
if show not in list(range(0, 4)):
raise ValueError(funcName + '\"show\" must be in [0, 1, 2, 3]!')
if planes is None:
planes = list(range(flt_h.format.num_planes))
elif isinstance(planes, int):
planes = [planes]
bits = flt_h.format.bits_per_sample
if convknl == 0:
convknl_h = [-1, -1, -1, 2, 2, 2, -1, -1, -1]
convknl_v = [-1, 2, -1, -1, 2, -1, -1, 2, -1]
else: # convknl == 1
convknl_h = [-17, -61, -17, 0, 0, 0, 17, 61, 17]
convknl_v = [-17, 0, 17, -61, 0, 61, -17, 0, 17]
if conv_div is None:
conv_div = max(convknl_h)
hmap = core.std.Convolution(src, matrix=convknl_h, saturate=False, planes=planes, divisor=conv_div)
vmap = core.std.Convolution(src, matrix=convknl_v, saturate=False, planes=planes, divisor=conv_div)
if mrad > 0:
hmap = haf.mt_expand_multi(hmap, sw=0, sh=mrad, planes=planes)
vmap = haf.mt_expand_multi(vmap, sw=mrad, sh=0, planes=planes)
elif mrad < 0:
hmap = haf.mt_inpand_multi(hmap, sw=0, sh=-mrad, planes=planes)
vmap = haf.mt_inpand_multi(vmap, sw=-mrad, sh=0, planes=planes)
if calc_mode == 0:
ldexpr = '{peak} 1 x 0.0001 + y 0.0001 + / {power} pow + /'.format(peak=(1 << bits) - 1, power=power)
else:
ldexpr = 'y 0.0001 + x 0.0001 + dup * y 0.0001 + dup * + sqrt / {peak} *'.format(peak=(1 << bits) - 1)
ldmap = core.std.Expr([hmap, vmap], [(ldexpr if i in planes else '') for i in range(src.format.num_planes)])
if show == 0:
return core.std.MaskedMerge(flt_h, flt_v, ldmap, planes=planes)
elif show == 1:
return ldmap
elif show == 2:
return hmap
elif show == 3:
return vmap
else:
raise ValueError
def Compare(src: vs.VideoNode, flt: vs.VideoNode, power: float = 1.5,
chroma: bool = False, mode: int = 2
) -> vs.VideoNode:
"""Visualizes the difference between the source clip and filtered clip.
Args:
src: Source clip.
flt: Filtered clip.
power: (float) The variable in the processing function which controls the "strength" to increase difference. Default is 1.5.
chroma: (bool) Whether to process chroma. Default is False.
mode: (1 or 2) Different processing function. 1: non-linear; 2: linear.
"""
funcName = 'Compare'
if not isinstance(src, vs.VideoNode):
raise TypeError(funcName + ': \"src\" must be a clip!')
if src.format.color_family not in [vs.GRAY, vs.YUV]:
raise TypeError(funcName + ': \"src\" must be a YUV clip!')
if not isinstance(flt, vs.VideoNode):
raise TypeError(funcName + ': \"flt\" must be a clip!')
if mode not in [1, 2]:
raise TypeError(funcName + ': \"mode\" must be in [1, 2]!')
Compare2(src, flt, props_list=['width', 'height', 'format.name'])
isGray = src.format.color_family == vs.GRAY
bits = src.format.bits_per_sample
sample = src.format.sample_type
expr = {}
expr[1] = 'y x - abs 1 + {power} pow 1 -'.format(power=power)
expr[2] = 'y x - {scale} * {neutral} +'.format(scale=32768 / (65536 ** (1 / power) - 1), neutral=32768)
chroma = chroma or isGray
if bits != 16:
src = mvf.Depth(src, 16, sample=vs.INTEGER)
flt = mvf.Depth(flt, 16, sample=vs.INTEGER)
diff = core.std.Expr([src, flt], [expr[mode]] if chroma else [expr[mode], '{neutral}'.format(neutral=32768)])
diff = mvf.Depth(diff, depth=bits, sample=sample, fulls=True, fulld=True, dither="none", ampo=0, ampn=0)
else:
diff = core.std.Expr([src, flt], [expr[mode]] if chroma else [expr[mode], '{neutral}'.format(neutral=32768)])
return diff
def Compare2(clip1: vs.VideoNode, clip2: vs.VideoNode,
props_list: Optional[Sequence[str]] = None
) -> None:
"""Compares the formats of two clips.
TypeError will be raised when one of the format of two clips are not identical.
Otherwise, None is returned.
Args:
clip1, clip2: Input.
props_list: (list of strings) A list containing the format to be compared.
If it is none, all the formats will be compared.
Default is None.
"""
funcName = 'Compare2'
if not isinstance(clip1, vs.VideoNode):
raise TypeError(funcName + ': \"clip1\" must be a clip!')
if not isinstance(clip2, vs.VideoNode):
raise TypeError(funcName + ': \"clip2\" must be a clip!')
if props_list is None:
props_list = ['width', 'height', 'num_frames', 'fps', 'format.name']
info = ''
for prop in props_list:
clip1_prop = eval('clip1.{prop}'.format(prop=prop))
clip2_prop = eval('clip2.{prop}'.format(prop=prop))
if clip1_prop != clip2_prop:
info += '{prop}: {clip1_prop} != {clip2_prop}\n'.format(prop=prop, clip1_prop=clip1_prop, clip2_prop=clip2_prop)
if info != '':
info = '\n\n{}'.format(info)
raise TypeError(info)
def ExInpand(input: vs.VideoNode, mrad: Union[int, Sequence[int], Sequence[Sequence[int]]] = 0,
mode: Union[int, str, Sequence[Union[int, str]]] = 'rectangle',
planes: PlanesType = None
) -> vs.VideoNode:
"""A filter to simplify the calls of std.Maximum()/std.Minimum() and their concatenation.
Args:
input: Source clip.
mrad: (int []) How many times to use std.Maximum()/std.Minimum(). Default is 0.
Positive value indicates to use std.Maximum().
Negative value indicates to use std.Minimum().
Values can be put into a list, or a list of lists.
Example:
mrad=[2, -1] is equvalant to clip.std.Maximum().std.Maximum().std.Minimum()
mrad=[[2, 1], [2, -1]] is equivalant to
haf.mt_expand_multi(clip, sw=2, sh=1).std.Maximum().std.Maximum().std.Minimum()
mode: (0:"rectangle", 1:"losange" or 2:"ellipse", int [] or str []). Default is "rectangle"
The shape of the kernel.
planes: (int []) Whether to process the corresponding plane. By default, every plane will be processed.
The unprocessed planes will be copied from "input".
"""
funcName = 'ExInpand'
if not isinstance(input, vs.VideoNode):
raise TypeError(funcName + ': \"input\" must be a clip!')
if planes is None:
planes = list(range(input.format.num_planes))
elif isinstance(planes, int):
planes = [planes]
if isinstance(mrad, int):
mrad = [mrad]
elif not isinstance(mrad, abc.Sequence):
raise TypeError(funcName + ': \"mrad\" must be an int, a list of ints or lists of two ints!')
if isinstance(mode, (str, int)):
mode = [mode]
elif not isinstance(mode, abc.Sequence):
raise TypeError(funcName + ': \"mode\" must be an int, a string, a list of ints, strings or unions of ints and strings!')
# internel function
def ExInpand_process(input: vs.VideoNode, mode: Union[int, str],
planes: Union[int, Sequence[int]],
mrad: Union[int, Tuple[int, int]]) -> vs.VideoNode:
if isinstance(mode, int):
mode = ['rectangle', 'losange', 'ellipse'][mode]
elif isinstance(mode, str):
mode = mode.lower()
if mode not in ['rectangle', 'losange', 'ellipse']:
raise ValueError(funcName + ': \"mode\" must be an int in [0, 2] or a specific string in [\"rectangle\", \"losange\", \"ellipse\"]!')
else:
raise TypeError(funcName + ': \"mode\" must be an int in [0, 2] or a specific string in [\"rectangle\", \"losange\", \"ellipse\"]!')
if isinstance(mrad, int):
sw = sh = mrad
else:
sw, sh = mrad
if sw * sh < 0:
raise TypeError(funcName + ': \"mrad\" at a time must be both positive or negative!')
if sw > 0 or sh > 0:
return haf.mt_expand_multi(input, mode=mode, planes=planes, sw=sw, sh=sh)
else:
return haf.mt_inpand_multi(input, mode=mode, planes=planes, sw=-sw, sh=-sh)
# process
for i in range(len(mrad)):
if isinstance(mrad[i], abc.Sequence):
for n in mrad[i]: # type: ignore
if not isinstance(n, int):
raise TypeError(funcName + ': \"mrad\" must be an int, a list of ints or lists of two ints!')
if len(mrad[i]) == 1: # type: ignore
_mrad = (mrad[i][0], mrad[i][0]) # type: ignore
elif len(mrad[i]) == 2: # type: ignore
_mrad = tuple(mrad[i]) # type: ignore
else:
raise TypeError(funcName + ': \"mrad\" must be an int, a list of ints or lists of two ints!')
elif isinstance(mrad[i], int):
_mrad = mrad[i] # type: ignore
else:
raise TypeError(funcName + ': \"mrad\" must be an int, a list of ints or lists of two ints!')
clip = ExInpand_process(input, mode=mode[min(i, len(mode) - 1)], mrad=_mrad, planes=planes)
return clip
def InDeflate(input: vs.VideoNode, msmooth: Union[int, Sequence[int]] = 0,
planes: PlanesType = None
) -> vs.VideoNode:
"""A filter to simplify the calls of std.Inflate()/std.Deflate() and their concatenation.
Args:
input: Source clip.
msmooth: (int []) How many times to use std.Inflate()/std.Deflate(). Default is 0.
The behaviour is the same as "mode" in ExInpand().
planes: (int []) Whether to process the corresponding plane. By default, every plane will be processed.
The unprocessed planes will be copied from "input".
"""
funcName = 'InDeFlate'
if not isinstance(input, vs.VideoNode):
raise TypeError(funcName + ': \"input\" must be a clip!')
if planes is None:
planes = list(range(input.format.num_planes))
elif isinstance(planes, int):
planes = [planes]
if isinstance(msmooth, int):
msmoooth = [msmooth]
# internel function
def InDeflate_process(input: vs.VideoNode, radius: int,
planes: PlanesType = None
) -> vs.VideoNode:
if radius > 0:
return haf.mt_inflate_multi(input, planes=planes, radius=radius)
else:
return haf.mt_deflate_multi(input, planes=planes, radius=-radius)
# process
if isinstance(msmooth, list):
for m in msmooth:
if not isinstance(m, int):
raise TypeError(funcName + ': \"msmooth\" must be an int or a list of ints!')
else:
clip = InDeflate_process(input, radius=m, planes=planes)
else:
raise TypeError(funcName + ': \"msmooth\" must be an int or a list of ints!')
return clip
def MultiRemoveGrain(input: vs.VideoNode, mode: Union[int, Sequence[int]] = 0,
loop: int = 1
) -> vs.VideoNode:
"""A filter to simplify the calls of rgvs.RemoveGrain().
Args:
input: Source clip.
mode: (int []) "mode" in rgvs.RemoveGrain().
Can be a list, the logic is similar to "mode" in ExInpand().
Example: mode=[4, 11, 11] is equivalant to clip.rgvs.RemoveGrain(4).rgvs.RemoveGrain(11).rgvs.RemoveGrain(11)
Default is 0.
loop: (int) How many times the "mode" loops.
"""
funcName = 'MultiRemoveGrain'
if not isinstance(input, vs.VideoNode):
raise TypeError(funcName + ': \"input\" must be a clip!')
if isinstance(mode, int):
mode = [mode]
if not isinstance(loop, int):
raise TypeError(funcName + ': \"loop\" must be an int!')
if loop < 0:
raise ValueError(funcName + ': \"loop\" must be positive value!')
if isinstance(mode, list):
for i in range(loop):
for m in mode:
clip = core.rgvs.RemoveGrain(input, mode=m)
else:
raise TypeError(funcName + ': \"mode\" must be an int, a list of ints or a list of a list of ints!')
return clip
def GradFun3(src: vs.VideoNode, thr: float = 0.35, radius: Optional[int] = None,
elast: float = 3.0, mask: int = 2, mode: Optional[int] = None,
ampo: Optional[float] = None, ampn: Optional[float] = None,
pat: Optional[int] = None, dyn: Optional[int] = None, lsb: bool = False,
staticnoise: Optional[int] = None, smode: int = 1,
thr_det: Optional[float] = None, debug: bool = False,
thrc: Optional[float] = None, radiusc: Optional[int] = None,
elastc: Optional[float] = None, planes: PlanesType = None,
ref: Optional[vs.VideoNode] = None
) -> vs.VideoNode:
"""GradFun3 by Firesledge v0.1.1
Port by Muonium 2016/6/18
Port from Dither_tools v1.27.2 (http://avisynth.nl/index.php/Dither_tools)
Internal precision is always 16 bits.
Read the document of Avisynth version for more details.
Notes:
1. In this function I try to keep the original look of GradFun3 in Avisynth.
It should be better to use Frechdachs's GradFun3 in his fvsfunc.py
(https://github.com/Irrational-Encoding-Wizardry/fvsfunc) which is more novel and powerful.
Removed parameters:
"dthr", "wmin", "thr_edg", "subspl", "lsb_in"
Parameters "y", "u", "v" are changed into "planes"
"""
funcName = 'GradFun3'
if not isinstance(src, vs.VideoNode):
raise TypeError(funcName + ': \"src\" must be a clip!')
if src.format.color_family not in [vs.YUV, vs.GRAY]:
raise TypeError(funcName + ': \"src\" must be YUV or GRAY color family!')
if not isinstance(thr, (float, int)):
raise TypeError(funcName + ': \"thr\" must be an int or a float!')
if smode not in [0, 1, 2, 3]:
raise ValueError(funcName + ': \"smode\" must be in [0, 1, 2, 3]!')
if radius is None:
radius = (16 if src.width > 1024 or src.height > 576 else 12) if (smode == 1 or smode == 2) else 9
elif isinstance(radius, int):
if radius <= 0:
raise ValueError(funcName + ': \"radius\" must be strictly positive.')
else:
raise TypeError(funcName + ': \"radius\" must be an int!')
if isinstance(elast, (int, float)):
if elast < 1:
raise ValueError(funcName + ': Valid range of \"elast\" is [1, +inf)!')
else:
raise TypeError(funcName + ': \"elast\" must be an int or a float!')
if not isinstance(mask, int):
raise TypeError(funcName + ': \"mask\" must be an int!')
if thr_det is None:
thr_det = 2 + round(max(thr - 0.35, 0) / 0.3)
elif isinstance(thr_det, (int, float)):
if thr_det <= 0.0:
raise ValueError(funcName + '" \"thr_det\" must be strictly positive!')
else:
raise TypeError(funcName + ': \"mask\" must be an int or a float!')
if not isinstance(debug, bool) and debug not in [0, 1]:
raise TypeError(funcName + ': \"debug\" must be a bool!')
if thrc is None:
thrc = thr
if radiusc is None:
radiusc = radius
elif isinstance(radiusc, int):
if radiusc <= 0:
raise ValueError(funcName + '\"radiusc\" must be strictly positive.')
else:
raise TypeError(funcName + '\"radiusc\" must be an int!')
if elastc is None:
elastc = elast
elif isinstance(elastc, (int, float)):
if elastc < 1:
raise ValueError(funcName + ':valid range of \"elastc\" is [1, +inf)!')
else:
raise TypeError(funcName + ': \"elastc\" must be an int or a float!')
if planes is None:
planes = list(range(src.format.num_planes))
elif isinstance(planes, int):
planes = [planes]
if ref is None:
ref = src
elif not isinstance(ref, vs.VideoNode):
raise TypeError(funcName + ': \"ref\" must be a clip!')
elif ref.format.color_family not in [vs.YUV, vs.GRAY]:
raise TypeError(funcName + ': \"ref\" must be YUV or GRAY color family!')
elif src.width != ref.width or src.height != ref.height:
raise TypeError(funcName + ': \"ref\" must be of the same size as \"src\"!')
bits = src.format.bits_per_sample
src_16 = core.fmtc.bitdepth(src, bits=16, planes=planes) if bits < 16 else src
src_8 = core.fmtc.bitdepth(src, bits=8, dmode=1, planes=[0]) if bits != 8 else src
if src is ref:
ref_16 = src_16
else:
ref_16 = core.fmtc.bitdepth(ref, bits=16, planes=planes) if ref.format.bits_per_sample < 16 else ref
# Main debanding
"""
chroma_flag: Whether we need to process Y and UV separately. It's True when:
Y is processed;
at least one from UV is processed;
Y and UV use different parameters.
"""
chroma_flag = (thrc != thr or radiusc != radius or
elastc != elast) and 0 in planes and (1 in planes or 2 in planes)
if chroma_flag:
planes2 = [0]
else:
planes2 = list(planes)
if not planes2:
raise ValueError(funcName + ': no plane is processed!')
flt_y = _GF3_smooth(src_16, ref_16, smode, radius, thr, elast, planes2)
if chroma_flag:
planes2 = [i for i in planes if i > 0]
flt_c = _GF3_smooth(src_16, ref_16, smode, radiusc, thrc, elastc, planes2)
flt = core.std.ShufflePlanes([flt_y, flt_c], list(range(src.format.num_planes)), src.format.color_family)
else:
flt = flt_y
# Edge/detail mask
td_lo = max(thr_det * 0.75, 1.0)
td_hi = max(thr_det, 1.0)
mexpr = 'x {tl} - {th} {tl} - / 255 *'.format(tl=td_lo - 0.0001, th=td_hi + 0.0001)
if mask > 0:
dmask = mvf.GetPlane(src_8, 0)
dmask = _Build_gf3_range_mask(dmask)
dmask = core.std.Expr([dmask], [mexpr])
dmask = core.rgvs.RemoveGrain(dmask, [22])
if mask > 1:
dmask = core.std.Convolution(dmask, matrix=[1, 2, 1, 2, 4, 2, 1, 2, 1])
if mask > 2:
dmask = core.std.Convolution(dmask, matrix=[1]*9)
dmask = core.fmtc.bitdepth(dmask, bits=16, fulls=True, fulld=True)
res_16 = core.std.MaskedMerge(flt, src_16, dmask, planes=planes, first_plane=True)
else:
res_16 = flt
# Dithering
result = res_16 if lsb or bits >= 16 else core.fmtc.bitdepth(res_16, bits=bits, planes=planes, dmode=mode,
ampo=ampo, ampn=ampn, dyn=dyn,
staticnoise=staticnoise, patsize=pat)
if debug:
last = dmask
if not lsb:
last = core.fmtc.bitdepth(last, bits=8, fulls=True, fulld=True)
else:
last = result
return last
def _GF3_smooth(src_16: vs.VideoNode, ref_16: vs.VideoNode, smode: int, radius: int,
thr: float, elast: float, planes: PlanesType
) -> vs.VideoNode:
funcName = "_GF3_smooth"
if smode == 0:
return _GF3_smoothgrad_multistage(src_16, ref_16, radius, thr, elast, planes)
elif smode == 1:
return _GF3_dfttest(src_16, ref_16, radius, thr, elast, planes)
elif smode == 2:
return _GF3_bilateral_multistage(src_16, ref_16, radius, thr, elast, planes)
elif smode == 3:
return _GF3_smoothgrad_multistage_3(src_16, radius, thr, elast, planes)
else:
raise ValueError(funcName + ': wrong smode value!')
def _GF3_smoothgrad_multistage(src: vs.VideoNode, ref: vs.VideoNode, radius: int,
thr: float, elast: float, planes: PlanesType
) -> vs.VideoNode:
ela_2 = max(elast * 0.83, 1.0)
ela_3 = max(elast * 0.67, 1.0)
r2 = radius * 2 // 3
r3 = radius * 3 // 3
r4 = radius * 4 // 4
last = src
last = SmoothGrad(last, radius=r2, thr=thr, elast=elast, ref=ref, planes=planes) if r2 >= 1 else last
last = SmoothGrad(last, radius=r3, thr=thr * 0.7, elast=ela_2, ref=ref, planes=planes) if r3 >= 1 else last
last = SmoothGrad(last, radius=r4, thr=thr * 0.46, elast=ela_3, ref=ref, planes=planes) if r4 >= 1 else last
return last
def _GF3_smoothgrad_multistage_3(src: vs.VideoNode, radius: int, thr: float,
elast: float, planes: PlanesType
) -> vs.VideoNode:
ref = SmoothGrad(src, radius=radius // 3, thr=thr * 0.8, elast=elast)
last = BoxFilter(src, radius=radius, planes=planes)
last = BoxFilter(last, radius=radius, planes=planes)
last = mvf.LimitFilter(last, src, thr=thr * 0.6, elast=elast, ref=ref, planes=planes)
return last
def _GF3_dfttest(src: vs.VideoNode, ref: vs.VideoNode, radius: int,
thr: float, elast: float, planes: PlanesType
) -> vs.VideoNode:
hrad = max(radius * 3 // 4, 1)
last = core.dfttest.DFTTest(src, sigma=hrad * thr * thr * 32, sbsize=hrad * 4,
sosize=hrad * 3, tbsize=1, planes=planes)
last = mvf.LimitFilter(last, ref, thr=thr, elast=elast, planes=planes)
return last
def _GF3_bilateral_multistage(src: vs.VideoNode, ref: vs.VideoNode, radius: int,
thr: float, elast: float, planes: PlanesType
) -> vs.VideoNode:
last = core.bilateral.Bilateral(src, ref=ref, sigmaS=radius / 2, sigmaR=thr / 255, planes=planes, algorithm=0)
last = mvf.LimitFilter(last, src, thr=thr, elast=elast, planes=planes)
return last
def _Build_gf3_range_mask(src: vs.VideoNode, radius: int = 1) -> vs.VideoNode:
last = src
if radius > 1:
ma = haf.mt_expand_multi(last, mode='ellipse', planes=[0], sw=radius, sh=radius)
mi = haf.mt_inpand_multi(last, mode='ellipse', planes=[0], sw=radius, sh=radius)
last = core.std.Expr([ma, mi], ['x y -'])
else:
bits = src.format.bits_per_sample
black = 0
white = (1 << bits) - 1
maxi = core.std.Maximum(last, [0])
mini = core.std.Minimum(last, [0])
exp = "x y -"
exp2 = "x {thY1} < {black} x ? {thY2} > {white} x ?".format(thY1=0, thY2=255, black=black, white=white)
last = core.std.Expr([maxi,mini], [exp])
last = core.std.Expr([last], [exp2])
return last
def AnimeMask(input: vs.VideoNode, shift: float = 0, expr: Optional[str] = None,
mode: int = 1, **resample_args: Any
) -> vs.VideoNode:
"""Generates edge/ringing mask for anime based on gradient operator.
For Anime's ringing mask, it's recommended to set "shift" between 0.5 and 1.0.
Args:
input: Source clip. Only the First plane will be processed.
shift: (float, -1.5 ~ 1.5) The distance of translation. Default is 0.
expr: (string) Subsequent processing in std.Expr(). Default is "".
mode: (-1 or 1) Type of the kernel, which simply inverts the pixel values and "shift".
Typically, -1 is for edge, 1 is for ringing. Default is 1.
resample_args: (dict) Additional parameters passed to core.resize in the form of dict.
"""
funcName = 'AnimeMask'
if not isinstance(input, vs.VideoNode):
raise TypeError(funcName + ': \"input\" must be a clip!')
if input.format.color_family != vs.GRAY:
input = mvf.GetPlane(input, 0)
if mode not in [-1, 1]:
raise ValueError(funcName + ': \'mode\' have not a correct value! [-1 or 1]')
if mode == -1:
input = core.std.Invert(input)
shift = -shift
full_args = dict(range_s="full", range_in_s="full")
mask1 = core.std.Convolution(input, [0, 0, 0, 0, 2, -1, 0, -1, 0], saturate=True).resize.Bicubic(src_left=shift,
src_top=shift, **full_args, **resample_args) # type: ignore
mask2 = core.std.Convolution(input, [0, -1, 0, -1, 2, 0, 0, 0, 0], saturate=True).resize.Bicubic(src_left=-shift,
src_top=-shift, **full_args, **resample_args) # type: ignore
mask3 = core.std.Convolution(input, [0, -1, 0, 0, 2, -1, 0, 0, 0], saturate=True).resize.Bicubic(src_left=shift,
src_top=-shift, **full_args, **resample_args) # type: ignore
mask4 = core.std.Convolution(input, [0, 0, 0, -1, 2, 0, 0, -1, 0], saturate=True).resize.Bicubic(src_left=-shift,
src_top=shift, **full_args, **resample_args) # type: ignore
calc_expr = 'x x * y y * + z z * + a a * + sqrt '
if isinstance(expr, str):
calc_expr += expr
mask = core.std.Expr([mask1, mask2, mask3, mask4], [calc_expr])
return mask
def AnimeMask2(input: vs.VideoNode, r: float = 1.2, expr: Optional[str] = None,
mode: int = 1
) -> vs.VideoNode:
"""Yet another filter to generate edge/ringing mask for anime.
More specifically, it's an approximatation of the difference of gaussians filter based on resampling.
Args:
input: Source clip. Only the First plane will be processed.
r: (float, positive) Radius of resampling coefficient. Default is 1.2.
expr: (string) Subsequent processing in std.Expr(). Default is "".
mode: (-1 or 1) Type of the kernel. Typically, -1 is for edge, 1 is for ringing. Default is 1.
"""
funcName = 'AnimeMask2'
if not isinstance(input, vs.VideoNode):
raise TypeError(funcName + ': \"input\" must be a clip!')
if input.format.color_family != vs.GRAY:
input = mvf.GetPlane(input, 0)
w = input.width
h = input.height
if mode not in [-1, 1]:
raise ValueError(funcName + ': \'mode\' have not a correct value! [-1 or 1]')
smooth = core.resize.Bicubic(input, haf.m4(w / r), haf.m4(h / r), filter_param_a=1/3, filter_param_b=1/3).resize.Bicubic(w, h, filter_param_a=1, filter_param_b=0)
smoother = core.resize.Bicubic(input, haf.m4(w / r), haf.m4(h / r), filter_param_a=1/3, filter_param_b=1/3).resize.Bicubic(w, h, filter_param_a=1.5, filter_param_b=-0.25)
calc_expr = 'x y - ' if mode == 1 else 'y x - '
if isinstance(expr, str):
calc_expr += expr
mask = core.std.Expr([smooth, smoother], [calc_expr])
return mask
def PolygonExInpand(input: vs.VideoNode, shift: float = 0, shape: int = 0, mixmode: int = 0,
noncentral: bool = False, step: float = 1, amp: float = 1,
**resample_args: Any
) -> vs.VideoNode:
"""Processes mask based on resampling.
Args:
input: Source clip. Only the First plane will be processed.
shift: (float) Distance of expanding/inpanding. Default is 0.
shape: (int, 0:losange, 1:square, 2:octagon) The shape of expand/inpand kernel. Default is 0.
mixmode: (int, 0:max, 1:arithmetic mean, 2:quadratic mean)
Method used to calculate the mix of different mask. Default is 0.
noncentral: (bool) Whether to calculate the center pixel in mix process.
step: (float) Step of expanding/inpanding. Default is 1.
amp: (float) Linear multiple to strengthen the final mask. Default is 1.
resample_args: (dict) Additional parameters passed to core.resize in the form of dict.
"""
funcName = 'PolygonExInpand'
if not isinstance(input, vs.VideoNode):
raise TypeError(funcName + ': \"input\" must be a clip!')
if shape not in list(range(3)):
raise ValueError(funcName + ': \'shape\' have not a correct value! [0, 1 or 2]')
if mixmode not in list(range(3)):
raise ValueError(funcName + ': \'mixmode\' have not a correct value! [0, 1 or 2]')
if step <= 0:
raise ValueError(funcName + ': \'step\' must be positive!')
invert = False
if shift < 0:
invert = True
input = core.std.Invert(input)
shift = -shift
elif shift == 0.:
return input
mask5 = input
while shift > 0:
step = min(step, shift)
shift = shift - step
ortho = step
inv_ortho = -step
dia = math.sqrt(step / 2)
inv_dia = -math.sqrt(step / 2)
# shift
if shape == 0 or shape == 2:
mask2 = core.resize.Bilinear(mask5, src_left=0, src_top=ortho, **resample_args)
mask4 = core.resize.Bilinear(mask5, src_left=ortho, src_top=0, **resample_args)
mask6 = core.resize.Bilinear(mask5, src_left=inv_ortho, src_top=0, **resample_args)
mask8 = core.resize.Bilinear(mask5, src_left=0, src_top=inv_ortho, **resample_args)
if shape == 1 or shape == 2:
mask1 = core.resize.Bilinear(mask5, src_left=dia, src_top=dia, **resample_args)
mask3 = core.resize.Bilinear(mask5, src_left=inv_dia, src_top=dia, **resample_args)
mask7 = core.resize.Bilinear(mask5, src_left=dia, src_top=inv_dia, **resample_args)
mask9 = core.resize.Bilinear(mask5, src_left=inv_dia, src_top=inv_dia, **resample_args)
# mix
if noncentral:
expr_list = [
'x y max z max a max',
'x y + z + a + 4 /',
'x x * y y * + z z * + a a * + 4 / sqrt',
'x y max z max a max b max c max d max e max',
'x y + z + a + b + c + d + e + 8 /',
'x x * y y * + z z * + a a * + b b * + c c * + d d * + e e * + 8 / sqrt',
]
if shape == 0 or shape == 1:
expr = expr_list[mixmode] + ' {amp} *'.format(amp=amp)
mask5 = core.std.Expr([mask2, mask4, mask6, mask8] if shape == 0 else [mask1, mask3, mask7, mask9], [expr])
else: # shape == 2
expr = expr_list[mixmode + 3] + ' {amp} *'.format(amp=amp)
mask5 = core.std.Expr([mask1, mask2, mask3, mask4, mask6, mask7, mask8, mask9], [expr])
else: # noncentral == False
expr_list = [
'x y max z max a max b max',
'x y + z + a + b + 5 /',
'x x * y y * + z z * + a a * + b b * + 5 / sqrt',
'x y max z max a max b max c max d max e max f max',
'x y + z + a + b + c + d + e + f + 9 /',
'x x * y y * + z z * + a a * + b b * + c c * + d d * + e e * + f f * + 9 / sqrt',
]
if (shape == 0) or (shape == 1):
expr = expr_list[mixmode] + ' {amp} *'.format(amp=amp)
mask5 = core.std.Expr([mask2, mask4, mask5, mask6, mask8] if shape == 0 else
[mask1, mask3, mask5, mask7, mask9], [expr])
else: # shape == 2
expr = expr_list[mixmode + 3] + ' {amp} *'.format(amp=amp)
mask5 = core.std.Expr([mask1, mask2, mask3, mask4, mask5, mask6, mask7, mask8, mask9], [expr])
return core.std.Invert(mask5) if invert else mask5
def Luma(input: vs.VideoNode, plane: int = 0, power: int = 4) -> vs.VideoNode:
"""std.Lut() implementation of Luma() in Histogram() filter.
Args:
input: Source clip. Only one plane will be processed.
plane: (int) Which plane to be processed. Default is 0.
power: (int) Coefficient in processing. Default is 4.
"""
funcName = 'Luma'
if not isinstance(input, vs.VideoNode):
raise TypeError(funcName + ': \"input\" must be a clip!')
if (input.format.sample_type != vs.INTEGER):
raise TypeError(funcName + ': \"input\" must be of integer format!')
bits = input.format.bits_per_sample
peak = (1 << bits) - 1
clip = mvf.GetPlane(input, plane)
def calc_luma(x: int) -> int:
p = x << power
return (peak - (p & peak)) if (p & (peak + 1)) else (p & peak)
return core.std.Lut(clip, function=calc_luma)
def ediaa(a: vs.VideoNode) -> vs.VideoNode:
"""Suggested by Mystery Keeper in "Denoise of tv-anime" thread
Read the document of Avisynth version for more details.
"""
funcName = 'ediaa'