-
Notifications
You must be signed in to change notification settings - Fork 4
/
havsfunc.py
6491 lines (5517 loc) · 286 KB
/
havsfunc.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
"""
Holy's ported AviSynth functions for VapourSynth.
Main functions:
daa
daa3mod
mcdaa3
santiag
FixChromaBleedingMod
Deblock_QED
DeHalo_alpha
EdgeCleaner
FineDehalo, FineDehalo2
YAHR
HQDeringmod
QTGMC
smartfademod
srestore
dec_txt60mc
ivtc_txt30mc
ivtc_txt60mc
logoNR
Vinverse
Vinverse2
LUTDeCrawl
LUTDeRainbow
Stab
GrainStabilizeMC
MCTemporalDenoise
SMDegrain
STPresso
bbmod
GrainFactory3
InterFrame
FixColumnBrightness, FixRowBrightness
FixColumnBrightnessProtect, FixRowBrightnessProtect
FixColumnBrightnessProtect2, FixRowBrightnessProtect2
SmoothLevels
FastLineDarkenMOD
Toon
LSFmod
Utility functions:
AverageFrames
AvsPrewitt
ChangeFPS
Gauss
mt_clamp
KNLMeansCL
Overlay
Padding
SCDetect
Weave
ContraSharpening
MinBlur
sbr, sbrV
DitherLumaRebuild
mt_expand_multi, mt_inpand_multi
mt_inflate_multi, mt_deflate_multi
"""
from __future__ import annotations
import importlib
import math
from functools import partial
from typing import Any, Mapping, Optional, Sequence, Union
import mvsfunc as mvf
import vapoursynth as vs
from vsutil import Dither, depth, fallback, get_depth, get_y, join, plane, scale_value
core = vs.core
def daa(
c: vs.VideoNode,
nsize: Optional[int] = None,
nns: Optional[int] = None,
qual: Optional[int] = None,
pscrn: Optional[int] = None,
int16_prescreener: Optional[bool] = None,
int16_predictor: Optional[bool] = None,
exp: Optional[int] = None,
opencl: bool = False,
device: Optional[int] = None,
) -> vs.VideoNode:
'''
Anti-aliasing with contra-sharpening by Didée.
It averages two independent interpolations, where each interpolation set works between odd-distanced pixels.
This on its own provides sufficient amount of blurring. Enough blurring that the script uses a contra-sharpening step to counteract the blurring.
'''
if not isinstance(c, vs.VideoNode):
raise vs.Error('daa: this is not a clip')
if opencl:
nnedi3 = partial(core.nnedi3cl.NNEDI3CL, nsize=nsize, nns=nns, qual=qual, pscrn=pscrn, device=device)
else:
nnedi3 = partial(
core.znedi3.nnedi3, nsize=nsize, nns=nns, qual=qual, pscrn=pscrn, int16_prescreener=int16_prescreener, int16_predictor=int16_predictor, exp=exp
)
nn = nnedi3(c, field=3)
dbl = core.std.Merge(nn[::2], nn[1::2])
dblD = core.std.MakeDiff(c, dbl)
shrpD = core.std.MakeDiff(dbl, dbl.std.Convolution(matrix=[1, 1, 1, 1, 1, 1, 1, 1, 1] if c.width > 1100 else [1, 2, 1, 2, 4, 2, 1, 2, 1]))
DD = core.rgvs.Repair(shrpD, dblD, mode=13)
return core.std.MergeDiff(dbl, DD)
def daa3mod(
c1: vs.VideoNode,
nsize: Optional[int] = None,
nns: Optional[int] = None,
qual: Optional[int] = None,
pscrn: Optional[int] = None,
int16_prescreener: Optional[bool] = None,
int16_predictor: Optional[bool] = None,
exp: Optional[int] = None,
opencl: bool = False,
device: Optional[int] = None,
) -> vs.VideoNode:
if not isinstance(c1, vs.VideoNode):
raise vs.Error('daa3mod: this is not a clip')
c = c1.resize.Spline36(c1.width, c1.height * 3 // 2)
return daa(c, nsize, nns, qual, pscrn, int16_prescreener, int16_predictor, exp, opencl, device).resize.Spline36(c1.width, c1.height)
def mcdaa3(
input: vs.VideoNode,
nsize: Optional[int] = None,
nns: Optional[int] = None,
qual: Optional[int] = None,
pscrn: Optional[int] = None,
int16_prescreener: Optional[bool] = None,
int16_predictor: Optional[bool] = None,
exp: Optional[int] = None,
opencl: bool = False,
device: Optional[int] = None,
) -> vs.VideoNode:
if not isinstance(input, vs.VideoNode):
raise vs.Error('mcdaa3: this is not a clip')
if hasattr(core, 'neo_fft3d'):
sup = input.hqdn3d.Hqdn3d().neo_fft3d.FFT3D().mv.Super(sharp=1)
else:
sup = input.hqdn3d.Hqdn3d().fft3dfilter.FFT3DFilter().mv.Super(sharp=1)
fv1 = sup.mv.Analyse(isb=False, delta=1, truemotion=False, dct=2)
fv2 = sup.mv.Analyse(isb=True, delta=1, truemotion=True, dct=2)
csaa = daa3mod(input, nsize, nns, qual, pscrn, int16_prescreener, int16_predictor, exp, opencl, device)
momask1 = input.mv.Mask(fv1, ml=2, kind=1)
momask2 = input.mv.Mask(fv2, ml=3, kind=1)
momask = core.std.Merge(momask1, momask2)
return core.std.MaskedMerge(input, csaa, momask)
def santiag(
c: vs.VideoNode,
strh: int = 1,
strv: int = 1,
type: str = 'nnedi3',
nsize: Optional[int] = None,
nns: Optional[int] = None,
qual: Optional[int] = None,
pscrn: Optional[int] = None,
int16_prescreener: Optional[bool] = None,
int16_predictor: Optional[bool] = None,
exp: Optional[int] = None,
aa: Optional[int] = None,
alpha: Optional[float] = None,
beta: Optional[float] = None,
gamma: Optional[float] = None,
nrad: Optional[int] = None,
mdis: Optional[int] = None,
vcheck: Optional[int] = None,
fw: Optional[int] = None,
fh: Optional[int] = None,
halfres: bool = False,
typeh: Optional[str] = None,
typev: Optional[str] = None,
opencl: bool = False,
device: Optional[int] = None,
) -> vs.VideoNode:
'''
santiag v1.6
Simple antialiasing
type = "nnedi3", "eedi2", "eedi3" or "sangnom"
'''
def santiag_dir(c: vs.VideoNode, strength: int, type: str, fw: Optional[int] = None, fh: Optional[int] = None) -> vs.VideoNode:
fw = fallback(fw, c.width)
fh = fallback(fh, c.height)
c = santiag_stronger(c, strength, type)
return c.resize.Spline36(fw, fh, src_top=0 if halfres else 0.5)
def santiag_stronger(c: vs.VideoNode, strength: int, type: str) -> vs.VideoNode:
if opencl:
nnedi3 = partial(core.nnedi3cl.NNEDI3CL, nsize=nsize, nns=nns, qual=qual, pscrn=pscrn, device=device)
if hasattr(core, 'EEDI3CL'):
eedi3 = partial(core.eedi3m.EEDI3CL, alpha=alpha, beta=beta, gamma=gamma, nrad=nrad, mdis=mdis, vcheck=vcheck, device=device)
else:
eedi3 = partial(core.eedi3m.EEDI3, alpha=alpha, beta=beta, gamma=gamma, nrad=nrad, mdis=mdis, vcheck=vcheck)
else:
nnedi3 = partial(
core.znedi3.nnedi3, nsize=nsize, nns=nns, qual=qual, pscrn=pscrn, int16_prescreener=int16_prescreener, int16_predictor=int16_predictor, exp=exp
)
if hasattr(core, 'EEDI3CL'):
eedi3 = partial(core.eedi3m.EEDI3CL, alpha=alpha, beta=beta, gamma=gamma, nrad=nrad, mdis=mdis, vcheck=vcheck, device=device)
else:
eedi3 = partial(core.eedi3m.EEDI3, alpha=alpha, beta=beta, gamma=gamma, nrad=nrad, mdis=mdis, vcheck=vcheck)
strength = max(strength, 0)
field = strength % 2
dh = strength <= 0 and not halfres
if strength > 0:
c = santiag_stronger(c, strength - 1, type)
w = c.width
h = c.height
if type == 'nnedi3':
return nnedi3(c, field=field, dh=dh)
elif type == 'eedi2':
if not dh:
c = c.resize.Point(w, h // 2, src_top=1 - field)
return c.eedi2.EEDI2(field=field)
elif type == 'eedi3':
sclip = nnedi3(c, field=field, dh=dh)
return eedi3(c, field=field, dh=dh, sclip=sclip)
elif type == 'sangnom':
if dh:
c = c.resize.Spline36(w, h * 2, src_top=-0.25)
return c.sangnom.SangNom(order=field + 1, aa=aa)
else:
raise vs.Error('santiag: unexpected value for type')
if not isinstance(c, vs.VideoNode):
raise vs.Error('santiag: this is not a clip')
type = type.lower()
typeh = type if typeh is None else typeh.lower()
typev = type if typev is None else typev.lower()
w = c.width
h = c.height
fwh = fw if strv < 0 else w
fhh = fh if strv < 0 else h
if strh >= 0:
c = santiag_dir(c, strh, typeh, fwh, fhh)
if strv >= 0:
c = santiag_dir(c.std.Transpose(), strv, typev, fh, fw).std.Transpose()
fw = fallback(fw, w)
fh = fallback(fh, h)
if strh < 0 and strv < 0:
c = c.resize.Spline36(fw, fh)
return c
def FixChromaBleedingMod(input: vs.VideoNode, cx: int = 4, cy: int = 4, thr: float = 4.0, strength: float = 0.8, blur: bool = False) -> vs.VideoNode:
'''
FixChromaBleedingMod v1.36
A script to reduce color bleeding, over-saturation, and color shifting mainly in red and blue areas.
Parameters:
input: Clip to process.
cx: Horizontal chroma shift. Positive value shifts chroma to the left, negative value shifts chroma to the right.
cy: Vertical chroma shift. Positive value shifts chroma upwards, negative value shifts chroma downwards.
thr: Masking threshold, higher values treat more areas as color bleed.
strength: Saturation strength in clip to be merged with the original chroma.
Values below 1.0 reduce the saturation, a value of 1.0 leaves the saturation intact.
blur: Set to true to blur the mask clip.
'''
from adjust import Tweak
if not isinstance(input, vs.VideoNode):
raise vs.Error('FixChromaBleedingMod: this is not a clip')
if input.format.color_family != vs.YUV or input.format.sample_type != vs.INTEGER:
raise vs.Error('FixChromaBleedingMod: only YUV format with integer sample type is supported')
# prepare to work on the V channel and filter noise
vch = plane(Tweak(input, sat=thr), 2)
if blur:
area = vch.std.Convolution(matrix=[1, 2, 1, 2, 4, 2, 1, 2, 1])
else:
area = vch
bits = get_depth(input)
i16 = scale_value(16, 8, bits)
i25 = scale_value(25, 8, bits)
i231 = scale_value(231, 8, bits)
i235 = scale_value(235, 8, bits)
i240 = scale_value(240, 8, bits)
# select and normalize both extremes of the scale
red = area.std.Levels(min_in=i235, max_in=i235, min_out=i235, max_out=i16)
blue = area.std.Levels(min_in=i16, max_in=i16, min_out=i16, max_out=i235)
# merge both masks
mask = core.std.Merge(red, blue)
if not blur:
mask = mask.std.Convolution(matrix=[1, 2, 1, 2, 4, 2, 1, 2, 1])
mask = mask.std.Levels(min_in=i231, max_in=i231, min_out=i235, max_out=i16)
# expand to cover beyond the bleeding areas and shift to compensate the resizing
mask = mask.std.Convolution(matrix=[0, 0, 0, 1, 0, 0, 0, 0, 0], divisor=1, saturate=False).std.Convolution(
matrix=[1, 1, 1, 1, 1, 1, 0, 0, 0], divisor=8, saturate=False
)
# binarize (also a trick to expand)
mask = mask.std.Levels(min_in=i25, max_in=i25, min_out=i16, max_out=i240).std.Inflate()
# prepare a version of the image that has its chroma shifted and less saturated
input_c = Tweak(input.resize.Spline16(src_left=cx, src_top=cy), sat=strength)
# combine both images using the mask
fu = core.std.MaskedMerge(plane(input, 1), plane(input_c, 1), mask)
fv = core.std.MaskedMerge(plane(input, 2), plane(input_c, 2), mask)
return join([input, fu, fv])
def Deblock_QED(
clp: vs.VideoNode, quant1: int = 24, quant2: int = 26, aOff1: int = 1, bOff1: int = 2, aOff2: int = 1, bOff2: int = 2, uv: int = 3
) -> vs.VideoNode:
'''
A postprocessed Deblock: Uses full frequencies of Deblock's changes on block borders, but DCT-lowpassed changes on block interiours.
Parameters:
clp: Clip to process.
quant1: Strength of block edge deblocking.
quant2: Strength of block internal deblocking.
aOff1: Halfway "sensitivity" and halfway a strength modifier for borders.
bOff1: "Sensitivity to detect blocking" for borders.
aOff2: Halfway "sensitivity" and halfway a strength modifier for block interiors.
bOff2: "Sensitivity to detect blocking" for block interiors.
uv:
3 = use proposed method for chroma deblocking
2 = no chroma deblocking at all (fastest method)
1 = directly use chroma debl. from the normal Deblock()
-1 = directly use chroma debl. from the strong Deblock()
'''
if not isinstance(clp, vs.VideoNode):
raise vs.Error('Deblock_QED: this is not a clip')
is_gray = clp.format.color_family == vs.GRAY
planes = [0, 1, 2] if uv > 2 and not is_gray else 0
if clp.format.sample_type == vs.INTEGER:
bits = get_depth(clp)
neutral = 1 << (bits - 1)
peak = (1 << bits) - 1
else:
neutral = 0.0
peak = 1.0
# add borders if clp is not mod 8
w = clp.width
h = clp.height
padX = 8 - w % 8 if w & 7 else 0
padY = 8 - h % 8 if h & 7 else 0
if padX or padY:
clp = clp.resize.Point(w + padX, h + padY, src_width=w + padX, src_height=h + padY)
# block
block = clp.std.BlankClip(width=6, height=6, format=clp.format.replace(color_family=vs.GRAY, subsampling_w=0, subsampling_h=0), length=1, color=0)
block = block.std.AddBorders(1, 1, 1, 1, color=peak)
block = core.std.StackHorizontal([block for _ in range(clp.width // 8)])
block = core.std.StackVertical([block for _ in range(clp.height // 8)])
if not is_gray:
blockc = block.std.CropAbs(width=clp.width >> clp.format.subsampling_w, height=clp.height >> clp.format.subsampling_h)
block = core.std.ShufflePlanes([block, blockc], planes=[0, 0, 0], colorfamily=clp.format.color_family)
block = block.std.Loop(times=clp.num_frames)
# create normal deblocking (for block borders) and strong deblocking (for block interiour)
normal = clp.deblock.Deblock(quant=quant1, aoffset=aOff1, boffset=bOff1, planes=[0, 1, 2] if uv != 2 and not is_gray else 0)
strong = clp.deblock.Deblock(quant=quant2, aoffset=aOff2, boffset=bOff2, planes=[0, 1, 2] if uv != 2 and not is_gray else 0)
# build difference maps of both
normalD = core.std.MakeDiff(clp, normal, planes=planes)
strongD = core.std.MakeDiff(clp, strong, planes=planes)
# separate border values of the difference maps, and set the interiours to '128'
expr = f'y {peak} = x {neutral} ?'
normalD2 = core.std.Expr([normalD, block], expr=expr if uv > 2 or is_gray else [expr, ''])
strongD2 = core.std.Expr([strongD, block], expr=expr if uv > 2 or is_gray else [expr, ''])
# interpolate the border values over the whole block: DCTFilter can do it. (Kiss to Tom Barry!)
# (Note: this is not fully accurate, but a reasonable approximation.)
# add borders if clp is not mod 16
sw = strongD2.width
sh = strongD2.height
remX = 16 - sw % 16 if sw & 15 else 0
remY = 16 - sh % 16 if sh & 15 else 0
if remX or remY:
strongD2 = strongD2.resize.Point(sw + remX, sh + remY, src_width=sw + remX, src_height=sh + remY)
expr = f'x {neutral} - 1.01 * {neutral} +'
strongD3 = (
strongD2.std.Expr(expr=expr if uv > 2 or is_gray else [expr, ''])
.dctf.DCTFilter(factors=[1, 1, 0, 0, 0, 0, 0, 0], planes=planes)
.std.Crop(right=remX, bottom=remY)
)
# apply compensation from "normal" deblocking to the borders of the full-block-compensations calculated from "strong" deblocking ...
expr = f'y {neutral} = x y ?'
strongD4 = core.std.Expr([strongD3, normalD2], expr=expr if uv > 2 or is_gray else [expr, ''])
# ... and apply it.
deblocked = core.std.MakeDiff(clp, strongD4, planes=planes)
# simple decisions how to treat chroma
if not is_gray:
if uv < 0:
deblocked = core.std.ShufflePlanes([deblocked, strong], planes=[0, 1, 2], colorfamily=clp.format.color_family)
elif uv < 2:
deblocked = core.std.ShufflePlanes([deblocked, normal], planes=[0, 1, 2], colorfamily=clp.format.color_family)
# remove mod 8 borders
return deblocked.std.Crop(right=padX, bottom=padY)
def DeHalo_alpha(
clp: vs.VideoNode,
rx: float = 2.0,
ry: float = 2.0,
darkstr: float = 1.0,
brightstr: float = 1.0,
lowsens: float = 50.0,
highsens: float = 50.0,
ss: float = 1.5,
) -> vs.VideoNode:
'''
Reduce halo artifacts that can occur when sharpening.
Parameters:
clp: Clip to process.
rx, ry: As usual, the radii for halo removal. This function is rather sensitive to the radius settings.
Set it as low as possible! If radius is set too high, it will start missing small spots.
darkstr, brightstr: The strength factors for processing dark and bright halos. Default 1.0 both for symmetrical processing.
On Comic/Anime, darkstr=0.4~0.8 sometimes might be better ... sometimes. In General, the function seems to preserve dark lines rather good.
lowsens, highsens: Sensitivity settings, not that easy to describe them exactly ...
In a sense, they define a window between how weak an achieved effect has to be to get fully accepted,
and how strong an achieved effect has to be to get fully discarded.
ss: Supersampling factor, to avoid creation of aliasing.
'''
if not isinstance(clp, vs.VideoNode):
raise vs.Error('DeHalo_alpha: this is not a clip')
if clp.format.color_family == vs.RGB:
raise vs.Error('DeHalo_alpha: RGB format is not supported')
bits = get_depth(clp)
if clp.format.color_family != vs.GRAY:
clp_orig = clp
clp = get_y(clp)
else:
clp_orig = None
ox = clp.width
oy = clp.height
halos = clp.resize.Bicubic(m4(ox / rx), m4(oy / ry), filter_param_a=1 / 3, filter_param_b=1 / 3).resize.Bicubic(ox, oy, filter_param_a=1, filter_param_b=0)
are = core.std.Expr([clp.std.Maximum(), clp.std.Minimum()], expr='x y -')
ugly = core.std.Expr([halos.std.Maximum(), halos.std.Minimum()], expr='x y -')
so = core.std.Expr(
[ugly, are],
expr=f'y x - y 0.000001 + / {scale_value(255, 8, bits)} * {scale_value(lowsens, 8, bits)} - y {scale_value(256, 8, bits)} + {scale_value(512, 8, bits)} / {highsens / 100} + *',
)
if clp.format.sample_type == vs.FLOAT:
so = so.std.Limiter()
lets = core.std.MaskedMerge(halos, clp, so)
if ss <= 1:
remove = core.rgvs.Repair(clp, lets, mode=1)
else:
remove = core.std.Expr(
[
core.std.Expr(
[
clp.resize.Lanczos(m4(ox * ss), m4(oy * ss)),
lets.std.Maximum().resize.Bicubic(m4(ox * ss), m4(oy * ss), filter_param_a=1 / 3, filter_param_b=1 / 3),
],
expr='x y min',
),
lets.std.Minimum().resize.Bicubic(m4(ox * ss), m4(oy * ss), filter_param_a=1 / 3, filter_param_b=1 / 3),
],
expr='x y max',
).resize.Lanczos(ox, oy)
them = core.std.Expr([clp, remove], expr=f'x y < x x y - {darkstr} * - x x y - {brightstr} * - ?')
if clp_orig is not None:
them = core.std.ShufflePlanes([them, clp_orig], planes=[0, 1, 2], colorfamily=clp_orig.format.color_family)
return them
def EdgeCleaner(c: vs.VideoNode, strength: int = 10, rep: bool = True, rmode: int = 17, smode: int = 0, hot: bool = False) -> vs.VideoNode:
'''
EdgeCleaner v1.04
A simple edge cleaning and weak dehaloing function.
Parameters:
c: Clip to process.
strength: Specifies edge denoising strength.
rep: Activates Repair for the aWarpSharped clip.
rmode: Specifies the Repair mode.
1 is very mild and good for halos,
16 and 18 are good for edge structure preserval on strong settings but keep more halos and edge noise,
17 is similar to 16 but keeps much less haloing, other modes are not recommended.
smode: Specifies what method will be used for finding small particles, ie stars. 0 is disabled, 1 uses RemoveGrain.
hot: Specifies whether removal of hot pixels should take place.
'''
if not isinstance(c, vs.VideoNode):
raise vs.Error('EdgeCleaner: this is not a clip')
if c.format.color_family == vs.RGB:
raise vs.Error('EdgeCleaner: RGB format is not supported')
bits = get_depth(c)
peak = (1 << bits) - 1
if c.format.color_family != vs.GRAY:
c_orig = c
c = get_y(c)
else:
c_orig = None
if smode > 0:
strength += 4
main = Padding(c, 6, 6, 6, 6).warp.AWarpSharp2(blur=1, depth=cround(strength / 2)).std.Crop(6, 6, 6, 6)
if rep:
main = core.rgvs.Repair(main, c, mode=rmode)
mask = (
AvsPrewitt(c)
.std.Expr(expr=f'x {scale_value(4, 8, bits)} < 0 x {scale_value(32, 8, bits)} > {peak} x ? ?')
.std.InvertMask()
.std.Convolution(matrix=[1, 1, 1, 1, 1, 1, 1, 1, 1])
)
final = core.std.MaskedMerge(c, main, mask)
if hot:
final = core.rgvs.Repair(final, c, mode=2)
if smode > 0:
clean = c.rgvs.RemoveGrain(mode=17)
diff = core.std.MakeDiff(c, clean)
mask = AvsPrewitt(diff.std.Levels(min_in=scale_value(40, 8, bits), max_in=scale_value(168, 8, bits), gamma=0.35).rgvs.RemoveGrain(mode=7)).std.Expr(
expr=f'x {scale_value(4, 8, bits)} < 0 x {scale_value(16, 8, bits)} > {peak} x ? ?'
)
final = core.std.MaskedMerge(final, c, mask)
if c_orig is not None:
final = core.std.ShufflePlanes([final, c_orig], planes=[0, 1, 2], colorfamily=c_orig.format.color_family)
return final
def FineDehalo(
src: vs.VideoNode,
rx: float = 2.0,
ry: Optional[float] = None,
thmi: int = 80,
thma: int = 128,
thlimi: int = 50,
thlima: int = 100,
darkstr: float = 1.0,
brightstr: float = 1.0,
showmask: int = 0,
contra: float = 0.0,
excl: bool = True,
edgeproc: float = 0.0,
mask: Optional[vs.VideoNode] = None,
) -> vs.VideoNode:
'''
Halo removal script that uses DeHalo_alpha with a few masks and optional contra-sharpening to try remove halos without removing important details.
Parameters:
src: Clip to process.
rx, ry: The radii for halo removal in DeHalo_alpha.
thmi, thma: Minimum and maximum threshold for sharp edges; keep only the sharpest edges (line edges).
To see the effects of these settings take a look at the strong mask (showmask=4).
thlimi, thlima: Minimum and maximum limiting threshold; includes more edges than previously, but ignores simple details.
darkstr, brightstr: The strength factors for processing dark and bright halos in DeHalo_alpha.
showmask: Shows mask; useful for adjusting settings.
0 = none
1 = outside mask
2 = shrink mask
3 = edge mask
4 = strong mask
contra: Contra-sharpening.
excl: Activates an additional step (exclusion zones) to make sure that the main edges are really excluded.
mask: Basic edge mask to apply the threshold instead of applying to the mask created by AvsPrewitt.
'''
if not isinstance(src, vs.VideoNode):
raise vs.Error('FineDehalo: this is not a clip')
if src.format.color_family == vs.RGB:
raise vs.Error('FineDehalo: RGB format is not supported')
if mask is not None:
if not isinstance(mask, vs.VideoNode):
raise vs.Error('FineDehalo: mask is not a clip')
if mask.format.color_family != vs.GRAY:
raise vs.Error('FineDehalo: mask must be Gray format')
is_float = src.format.sample_type == vs.FLOAT
bits = get_depth(src)
if src.format.color_family != vs.GRAY:
src_orig = src
src = get_y(src)
else:
src_orig = None
ry = fallback(ry, rx)
rx_i = cround(rx)
ry_i = cround(ry)
# Dehaloing #
dehaloed = DeHalo_alpha(src, rx=rx, ry=ry, darkstr=darkstr, brightstr=brightstr)
# Contrasharpening
if contra > 0:
dehaloed = FineDehalo_contrasharp(dehaloed, src, contra)
# Main edges #
# Basic edge detection, thresholding will be applied later
edges = fallback(mask, AvsPrewitt(src))
# Keeps only the sharpest edges (line edges)
strong = edges.std.Expr(expr=f'x {scale_value(thmi, 8, bits)} - {thma - thmi} / 255 *')
if is_float:
strong = strong.std.Limiter()
# Extends them to include the potential halos
large = mt_expand_multi(strong, sw=rx_i, sh=ry_i)
# Exclusion zones #
# When two edges are close from each other (both edges of a single line or multiple parallel color bands),
# the halo removal oversmoothes them or makes seriously bleed the bands, producing annoying artifacts.
# Therefore we have to produce a mask to exclude these zones from the halo removal.
# Includes more edges than previously, but ignores simple details
light = edges.std.Expr(expr=f'x {scale_value(thlimi, 8, bits)} - {thlima - thlimi} / 255 *')
if is_float:
light = light.std.Limiter()
# To build the exclusion zone, we make grow the edge mask, then shrink it to its original shape.
# During the growing stage, close adjacent edge masks will join and merge, forming a solid area, which will remain solid even after the shrinking stage.
# Mask growing
shrink = mt_expand_multi(light, mode='ellipse', sw=rx_i, sh=ry_i)
# At this point, because the mask was made of a shades of grey, we may end up with large areas of dark grey after shrinking.
# To avoid this, we amplify and saturate the mask here (actually we could even binarize it).
shrink = shrink.std.Expr(expr='x 4 *')
if is_float:
shrink = shrink.std.Limiter()
# Mask shrinking
shrink = mt_inpand_multi(shrink, mode='ellipse', sw=rx_i, sh=ry_i)
# This mask is almost binary, which will produce distinct discontinuities once applied. Then we have to smooth it.
shrink = shrink.std.Convolution(matrix=[1, 1, 1, 1, 1, 1, 1, 1, 1]).std.Convolution(matrix=[1, 1, 1, 1, 1, 1, 1, 1, 1])
# Final mask building #
# Previous mask may be a bit weak on the pure edge side, so we ensure that the main edges are really excluded.
# We do not want them to be smoothed by the halo removal.
if excl:
shr_med = core.std.Expr([strong, shrink], expr='x y max')
else:
shr_med = strong
# Subtracts masks and amplifies the difference to be sure we get 255 on the areas to be processed
outside = core.std.Expr([large, shr_med], expr='x y - 2 *')
if is_float:
outside = outside.std.Limiter()
# If edge processing is required, adds the edgemask
if edgeproc > 0:
outside = core.std.Expr([outside, strong], expr=f'x y {edgeproc * 0.66} * +')
if is_float:
outside = outside.std.Limiter()
# Smooth again and amplify to grow the mask a bit, otherwise the halo parts sticking to the edges could be missed
outside = outside.std.Convolution(matrix=[1, 1, 1, 1, 1, 1, 1, 1, 1]).std.Expr(expr='x 2 *')
if is_float:
outside = outside.std.Limiter()
# Masking #
if showmask <= 0:
last = core.std.MaskedMerge(src, dehaloed, outside)
if src_orig is not None:
if showmask <= 0:
return core.std.ShufflePlanes([last, src_orig], planes=[0, 1, 2], colorfamily=src_orig.format.color_family)
elif showmask == 1:
return outside.resize.Bicubic(format=src_orig.format)
elif showmask == 2:
return shrink.resize.Bicubic(format=src_orig.format)
elif showmask == 3:
return edges.resize.Bicubic(format=src_orig.format)
else:
return strong.resize.Bicubic(format=src_orig.format)
else:
if showmask <= 0:
return last
elif showmask == 1:
return outside
elif showmask == 2:
return shrink
elif showmask == 3:
return edges
else:
return strong
def FineDehalo_contrasharp(dehaloed: vs.VideoNode, src: vs.VideoNode, level: float) -> vs.VideoNode:
'''level == 1.0 : normal contrasharp'''
if not (isinstance(dehaloed, vs.VideoNode) and isinstance(src, vs.VideoNode)):
raise vs.Error('FineDehalo_contrasharp: this is not a clip')
if dehaloed.format.color_family == vs.RGB:
raise vs.Error('FineDehalo_contrasharp: RGB format is not supported')
if dehaloed.format.id != src.format.id:
raise vs.Error('FineDehalo_contrasharp: clips must have the same format')
neutral = 1 << (get_depth(dehaloed) - 1) if dehaloed.format.sample_type == vs.INTEGER else 0.0
if dehaloed.format.color_family != vs.GRAY:
dehaloed_orig = dehaloed
dehaloed = get_y(dehaloed)
src = get_y(src)
else:
dehaloed_orig = None
bb = dehaloed.std.Convolution(matrix=[1, 2, 1, 2, 4, 2, 1, 2, 1])
bb2 = core.rgvs.Repair(bb, core.rgvs.Repair(bb, bb.ctmf.CTMF(radius=2), mode=1), mode=1)
xd = core.std.MakeDiff(bb, bb2)
xd = xd.std.Expr(expr=f'x {neutral} - 2.49 * {level} * {neutral} +')
xdd = core.std.Expr(
[xd, core.std.MakeDiff(src, dehaloed)], expr=f'x {neutral} - y {neutral} - * 0 < {neutral} x {neutral} - abs y {neutral} - abs < x y ? ?'
)
last = core.std.MergeDiff(dehaloed, xdd)
if dehaloed_orig is not None:
last = core.std.ShufflePlanes([last, dehaloed_orig], planes=[0, 1, 2], colorfamily=dehaloed_orig.format.color_family)
return last
def FineDehalo2(
src: vs.VideoNode, hconv: Sequence[int] = [-1, -2, 0, 0, 40, 0, 0, -2, -1], vconv: Sequence[int] = [-2, -1, 0, 0, 40, 0, 0, -1, -2], showmask: bool = False
) -> vs.VideoNode:
'''
Try to remove 2nd order halos.
Parameters:
src: Clip to process.
hconv, vconv: Horizontal and vertical convolutions.
showmask: Shows mask.
'''
def grow_mask(mask: vs.VideoNode, coordinates: Sequence[int]) -> vs.VideoNode:
mask = mask.std.Maximum(coordinates=coordinates).std.Minimum(coordinates=coordinates)
mask_1 = mask.std.Maximum(coordinates=coordinates)
mask_2 = mask_1.std.Maximum(coordinates=coordinates).std.Maximum(coordinates=coordinates)
mask = core.std.Expr([mask_2, mask_1], expr='x y -')
return mask.std.Convolution(matrix=[1, 2, 1, 2, 4, 2, 1, 2, 1]).std.Expr(expr='x 1.8 *')
if not isinstance(src, vs.VideoNode):
raise vs.Error('FineDehalo2: this is not a clip')
if src.format.color_family == vs.RGB:
raise vs.Error('FineDehalo2: RGB format is not supported')
is_float = src.format.sample_type == vs.FLOAT
if src.format.color_family != vs.GRAY:
src_orig = src
src = get_y(src)
else:
src_orig = None
fix_h = src.std.Convolution(matrix=vconv, mode='v')
fix_v = src.std.Convolution(matrix=hconv, mode='h')
mask_h = src.std.Convolution(matrix=[1, 2, 1, 0, 0, 0, -1, -2, -1], divisor=4, saturate=False)
mask_v = src.std.Convolution(matrix=[1, 0, -1, 2, 0, -2, 1, 0, -1], divisor=4, saturate=False)
temp_h = core.std.Expr([mask_h, mask_v], expr='x 3 * y -')
temp_v = core.std.Expr([mask_v, mask_h], expr='x 3 * y -')
if is_float:
temp_h = temp_h.std.Limiter()
temp_v = temp_v.std.Limiter()
mask_h = grow_mask(temp_h, [0, 1, 0, 0, 0, 0, 1, 0])
mask_v = grow_mask(temp_v, [0, 0, 0, 1, 1, 0, 0, 0])
if is_float:
mask_h = mask_h.std.Limiter()
mask_v = mask_v.std.Limiter()
if not showmask:
last = core.std.MaskedMerge(src, fix_h, mask_h)
last = core.std.MaskedMerge(last, fix_v, mask_v)
else:
last = core.std.Expr([mask_h, mask_v], expr='x y max')
if src_orig is not None:
if not showmask:
last = core.std.ShufflePlanes([last, src_orig], planes=[0, 1, 2], colorfamily=src_orig.format.color_family)
else:
last = last.resize.Bicubic(format=src_orig.format)
return last
def YAHR(clp: vs.VideoNode, blur: int = 2, depth: int = 32) -> vs.VideoNode:
'''
Y'et A'nother H'alo R'educing script
Parameters:
clp: Clip to process.
blur: "blur" parameter of AWarpSharp2.
depth: "depth" parameter of AWarpSharp2.
'''
if not isinstance(clp, vs.VideoNode):
raise vs.Error('YAHR: this is not a clip')
if clp.format.color_family == vs.RGB:
raise vs.Error('YAHR: RGB format is not supported')
if clp.format.color_family != vs.GRAY:
clp_orig = clp
clp = get_y(clp)
else:
clp_orig = None
b1 = MinBlur(clp, 2).std.Convolution(matrix=[1, 2, 1, 2, 4, 2, 1, 2, 1])
b1D = core.std.MakeDiff(clp, b1)
w1 = Padding(clp, 6, 6, 6, 6).warp.AWarpSharp2(blur=blur, depth=depth).std.Crop(6, 6, 6, 6)
w1b1 = MinBlur(w1, 2).std.Convolution(matrix=[1, 2, 1, 2, 4, 2, 1, 2, 1])
w1b1D = core.std.MakeDiff(w1, w1b1)
DD = core.rgvs.Repair(b1D, w1b1D, mode=13)
DD2 = core.std.MakeDiff(b1D, DD)
last = core.std.MakeDiff(clp, DD2)
if clp_orig is not None:
last = core.std.ShufflePlanes([last, clp_orig], planes=[0, 1, 2], colorfamily=clp_orig.format.color_family)
return last
def HQDeringmod(
input: vs.VideoNode,
smoothed: Optional[vs.VideoNode] = None,
ringmask: Optional[vs.VideoNode] = None,
mrad: int = 1,
msmooth: int = 1,
incedge: bool = False,
mthr: int = 60,
minp: int = 1,
nrmode: Optional[int] = None,
sigma: float = 128.0,
sigma2: Optional[float] = None,
sbsize: Optional[int] = None,
sosize: Optional[int] = None,
sharp: int = 1,
drrep: Optional[int] = None,
thr: float = 12.0,
elast: float = 2.0,
darkthr: Optional[float] = None,
planes: Union[int, Sequence[int]] = 0,
show: bool = False,
cuda: bool = False,
) -> vs.VideoNode:
'''
HQDering mod v1.8
Applies deringing by using a smart smoother near edges (where ringing occurs) only.
Parameters:
input: Clip to process.
mrad: Expanding of edge mask, higher value means more aggressive processing.
msmooth: Inflate of edge mask, smooth boundaries of mask.
incedge: Whether to include edge in ring mask, by default ring mask only include area near edges.
mthr: Threshold of prewitt edge mask, lower value means more aggressive processing.
But for strong ringing, lower value will treat some ringing as edge, which protects this ringing from being processed.
minp: Inpanding of prewitt edge mask, higher value means more aggressive processing.
nrmode: Kernel of deringing.
0 = DFTTest
1 = MinBlur(r=1)
2 = MinBlur(r=2)
3 = MinBlur(r=3)
sigma: Sigma for medium frequecies in DFTTest.
sigma2: Sigma for low & high frequecies in DFTTest.
sbsize: Length of the sides of the spatial window in DFTTest.
sosize: Spatial overlap amount in DFTTest.
sharp: Whether to use contra-sharpening to resharp deringed clip, 1-3 represents radius, 0 means no sharpening.
drrep: Use repair for details retention, recommended values are 24/23/13/12/1.
thr: The same meaning with "thr" in LimitFilter.
elast: The same meaning with "elast" in LimitFilter.
darkthr: Threshold for darker area near edges, by default equals to thr/4. Set it lower if you think de-ringing destroys too much lines, etc.
When "darkthr" is not equal to "thr", "thr" limits darkening while "darkthr" limits brightening.
planes: Specifies which planes will be processed. Any unprocessed planes will be simply copied.
show: Whether to output mask clip instead of filtered clip.
cuda: Whether to enable CUDA functionality (for dfttest2).
'''
from mvsfunc import LimitFilter
if not isinstance(input, vs.VideoNode):
raise vs.Error('HQDeringmod: this is not a clip')
if input.format.color_family == vs.RGB:
raise vs.Error('HQDeringmod: RGB format is not supported')
if smoothed is not None:
if not isinstance(smoothed, vs.VideoNode):
raise vs.Error('HQDeringmod: smoothed is not a clip')
if smoothed.format.id != input.format.id:
raise vs.Error("HQDeringmod: smoothed must have the same format as input")
if ringmask is not None and not isinstance(ringmask, vs.VideoNode):
raise vs.Error("HQDeringmod: ringmask is not a clip")
is_gray = input.format.color_family == vs.GRAY
bits = get_depth(input)
neutral = 1 << (bits - 1)
peak = (1 << bits) - 1
plane_range = range(input.format.num_planes)
if isinstance(planes, int):
planes = [planes]
HD = input.width > 1024 or input.height > 576
nrmode = fallback(nrmode, 2 if HD else 1)
sigma2 = fallback(sigma2, sigma / 16)
sbsize = fallback(sbsize, 8 if HD else 6)