Skip to content

blur

Functions:

  • bilateral

    Applies a bilateral filter for edge-preserving and noise-reducing smoothing.

  • box_blur

    Applies a box blur to the input clip.

  • flux_smooth

    FluxSmoothT examines each pixel and compares it to the corresponding pixel in the previous and next frames.

  • gauss_blur

    Applies Gaussian blur to a clip, supporting spatial and temporal modes, and per-plane control.

  • guided_filter
  • median_blur

    Applies a median blur to the clip using spatial or temporal neighborhood.

  • min_blur

    Combines binomial (Gaussian-like) blur and median filtering for a balanced smoothing effect.

  • sbr

    A helper function for high-pass filtering a blur difference, inspired by an AviSynth script by Didée.

  • side_box_blur

logger module-attribute

logger = getLogger(__name__)

Bilateral

Bilateral(bilateral_func: Callable[P, R])

Class decorator that wraps the bilateral function and extends its functionality.

It is not meant to be used directly.

Classes:

  • Backend

    Enum specifying which backend implementation of the bilateral filter to use.

Methods:

Attributes:

Source code in vsrgtools/blur.py
566
567
568
def __init__(self, bilateral_func: Callable[P, R]) -> None:
    self._func = bilateral_func
    self._backend = Bilateral.Backend.CPU

backend property writable

backend: Backend

The default backend for bilateral

Backend

Bases: CustomStrEnum

Enum specifying which backend implementation of the bilateral filter to use.

Methods:

  • Bilateral

    Applies the bilateral filter using the plugin associated with the selected backend.

  • __call__

    Set this backend for the duration of the context manager.

  • from_param

    Return the enum value from a parameter.

  • resolve
  • value

Attributes:

  • AUTO

    Select the default backend of the bilateral singleton.

  • CPU

    Uses vszip.Bilateral — a fast, CPU-based implementation written in Zig.

  • CUDA

    Uses bilateralgpu.Bilateral — a CUDA-based GPU implementation.

  • CUDA_RTC

    Uses bilateralgpu_rtc.Bilateral — a CUDA-based GPU implementation with runtime shader compilation.

  • GPU

    Uses vszipcl.Bilateral — a fast OpenCL-based implementation written in Zig.

AUTO class-attribute instance-attribute

AUTO = 'auto'

Select the default backend of the bilateral singleton.

CPU class-attribute instance-attribute

CPU = 'vszip'

Uses vszip.Bilateral — a fast, CPU-based implementation written in Zig.

CUDA class-attribute instance-attribute

CUDA = 'bilateralgpu'

Uses bilateralgpu.Bilateral — a CUDA-based GPU implementation.

CUDA_RTC class-attribute instance-attribute

CUDA_RTC = 'bilateralgpu_rtc'

Uses bilateralgpu_rtc.Bilateral — a CUDA-based GPU implementation with runtime shader compilation.

GPU class-attribute instance-attribute

GPU = 'vszipcl'

Uses vszipcl.Bilateral — a fast OpenCL-based implementation written in Zig.

Bilateral

Bilateral(clip: VideoNode, *args: Any, **kwargs: Any) -> VideoNode

Applies the bilateral filter using the plugin associated with the selected backend.

Parameters:

  • clip
    (VideoNode) –

    Source clip.

  • *args
    (Any, default: () ) –

    Positional arguments passed to the selected plugin.

  • **kwargs
    (Any, default: {} ) –

    Keyword arguments passed to the selected plugin.

Returns:

  • VideoNode

    Bilaterally filtered clip.

Source code in vsrgtools/blur.py
616
617
618
619
620
621
622
623
624
625
626
627
628
def Bilateral(self, clip: vs.VideoNode, *args: Any, **kwargs: Any) -> vs.VideoNode:  # noqa: N802
    """
    Applies the bilateral filter using the plugin associated with the selected backend.

    Args:
        clip: Source clip.
        *args: Positional arguments passed to the selected plugin.
        **kwargs: Keyword arguments passed to the selected plugin.

    Returns:
        Bilaterally filtered clip.
    """
    return getattr(clip, self.value).Bilateral(*args, **kwargs)

__call__

__call__() -> Generator[None]

Set this backend for the duration of the context manager.

Source code in vsrgtools/blur.py
603
604
605
606
607
608
609
610
611
@contextmanager
def __call__(self) -> Generator[None]:
    """Set this backend for the duration of the context manager."""
    old = bilateral.backend
    try:
        bilateral.backend = self
        yield
    finally:
        bilateral.backend = old

from_param classmethod

from_param(value: Any, func_except: FuncExcept | None = None) -> Self

Return the enum value from a parameter.

Parameters:

  • value
    (Any) –

    Value to instantiate the enum class.

  • func_except
    (FuncExcept | None, default: None ) –

    Exception function.

Returns:

  • Self

    Enum value.

Raises:

Source code in jetpytools/enums/base.py
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
@classmethod
def from_param(cls, value: Any, func_except: FuncExcept | None = None) -> Self:
    """
    Return the enum value from a parameter.

    Args:
        value: Value to instantiate the enum class.
        func_except: Exception function.

    Returns:
        Enum value.

    Raises:
        NotFoundEnumValue: Variable not found in the given enum.
    """
    func_except = func_except or cls.from_param

    try:
        return cls(value)
    except (ValueError, TypeError):
        pass

    if isinstance(func_except, tuple):
        func_name, var_name = func_except
    else:
        func_name, var_name = func_except, repr(cls)

    raise NotFoundEnumValueError(
        'The given value for "{var_name}" argument must be a valid {enum_name}, not "{value}"!\n'
        "Valid values are: [{readable_enum}].",
        func_name,
        var_name=var_name,
        enum_name=cls,
        value=value,
        readable_enum=(f"{name} ({value!s})" for name, value in cls.__members__.items()),
        reason=value,
    ) from None

resolve

resolve() -> Backend
Source code in vsrgtools/blur.py
613
614
def resolve(self) -> Bilateral.Backend:
    return bilateral.backend if self is Bilateral.Backend.AUTO else self

value

value() -> str
Source code in jetpytools/enums/base.py
97
98
@enum_property
def value(self) -> str: ...

__call__

__call__(*args: P.args, **kwargs: P.kwargs) -> R
Source code in vsrgtools/blur.py
570
571
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R:
    return self._func(*args, **kwargs)

GaussBlur

GaussBlur(gauss_blur: Callable[P, R])

Class decorator that wraps the gauss_blur function and extends its functionality.

It is not meant to be used directly.

Classes:

  • Backend

    Enum representing available backends on which to run the plugin.

Methods:

  • __call__
  • from_radius

    Applies Gaussian blur to a clip from an intuitive radius.

  • get_radius

    Compute the radius required for a given sigma value.

  • get_sigma

    Generate a Gaussian sigma value from an intuitive radius.

Attributes:

Source code in vsrgtools/blur.py
145
146
147
def __init__(self, gauss_blur: Callable[P, R]) -> None:
    self._func = gauss_blur
    self._backend = GaussBlur.Backend.CPU

backend property writable

backend: Backend

The default backend for gauss_blur

Backend

Bases: CustomStrEnum

Enum representing available backends on which to run the plugin.

Methods:

Attributes:

  • AUTO

    Select the default backend of the gauss_blur singleton.

  • CPU

    Zimg-based Gaussian resizer.

  • GPU

    OpenCL CL implementation.

AUTO class-attribute instance-attribute

AUTO = 'auto'

Select the default backend of the gauss_blur singleton.

CPU class-attribute instance-attribute

CPU = 'zimg'

Zimg-based Gaussian resizer.

GPU class-attribute instance-attribute

GPU = 'vszipcl'

OpenCL CL implementation.

__call__

__call__() -> Generator[None]

Set this backend for the duration of the context manager.

Source code in vsrgtools/blur.py
166
167
168
169
170
171
172
173
174
@contextmanager
def __call__(self) -> Generator[None]:
    """Set this backend for the duration of the context manager."""
    old = gauss_blur.backend
    try:
        gauss_blur.backend = self
        yield
    finally:
        gauss_blur.backend = old

from_param classmethod

from_param(value: Any, func_except: FuncExcept | None = None) -> Self

Return the enum value from a parameter.

Parameters:

  • value
    (Any) –

    Value to instantiate the enum class.

  • func_except
    (FuncExcept | None, default: None ) –

    Exception function.

Returns:

  • Self

    Enum value.

Raises:

Source code in jetpytools/enums/base.py
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
@classmethod
def from_param(cls, value: Any, func_except: FuncExcept | None = None) -> Self:
    """
    Return the enum value from a parameter.

    Args:
        value: Value to instantiate the enum class.
        func_except: Exception function.

    Returns:
        Enum value.

    Raises:
        NotFoundEnumValue: Variable not found in the given enum.
    """
    func_except = func_except or cls.from_param

    try:
        return cls(value)
    except (ValueError, TypeError):
        pass

    if isinstance(func_except, tuple):
        func_name, var_name = func_except
    else:
        func_name, var_name = func_except, repr(cls)

    raise NotFoundEnumValueError(
        'The given value for "{var_name}" argument must be a valid {enum_name}, not "{value}"!\n'
        "Valid values are: [{readable_enum}].",
        func_name,
        var_name=var_name,
        enum_name=cls,
        value=value,
        readable_enum=(f"{name} ({value!s})" for name, value in cls.__members__.items()),
        reason=value,
    ) from None

resolve

resolve() -> Backend
Source code in vsrgtools/blur.py
176
177
def resolve(self) -> GaussBlur.Backend:
    return gauss_blur.backend if self is GaussBlur.Backend.AUTO else self

value

value() -> str
Source code in jetpytools/enums/base.py
97
98
@enum_property
def value(self) -> str: ...

__call__

__call__(*args: P.args, **kwargs: P.kwargs) -> R
Source code in vsrgtools/blur.py
149
150
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R:
    return self._func(*args, **kwargs)

from_radius staticmethod

from_radius(
    clip: VideoNode,
    radius: int | Sequence[int] = 1,
    mode: OneDimConvMode | TempConvMode = HV,
    planes: Planes = None,
    **kwargs: Any,
) -> VideoNode

Applies Gaussian blur to a clip from an intuitive radius.

Parameters:

  • clip

    (VideoNode) –

    Source clip.

  • radius

    (int | Sequence[int], default: 1 ) –

    Size of the kernel in each direction. Automatically determined if not specified.

  • mode

    (OneDimConvMode | TempConvMode, default: HV ) –

    Convolution mode (horizontal, vertical, both, or temporal). Defaults to HV.

  • planes

    (Planes, default: None ) –

    Planes to process. Defaults to all.

  • **kwargs

    (Any, default: {} ) –

    Additional arguments passed to the resizer or blur kernel. Specifying _fast=True enables fast approximation.

Returns:

  • VideoNode

    Blurred clip.

Source code in vsrgtools/blur.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
@staticmethod
def from_radius(
    clip: vs.VideoNode,
    radius: int | Sequence[int] = 1,
    mode: OneDimConvMode | TempConvMode = ConvMode.HV,
    planes: Planes = None,
    **kwargs: Any,
) -> vs.VideoNode:
    """
    Applies Gaussian blur to a clip from an intuitive radius.

    Args:
        clip: Source clip.
        radius: Size of the kernel in each direction. Automatically determined if not specified.
        mode: Convolution mode (horizontal, vertical, both, or temporal). Defaults to HV.
        planes: Planes to process. Defaults to all.
        **kwargs: Additional arguments passed to the resizer or blur kernel. Specifying `_fast=True` enables fast
            approximation.

    Returns:
        Blurred clip.
    """
    return gauss_blur(clip, [gauss_blur.get_sigma(r) for r in to_arr(radius)], None, mode, planes, **kwargs)

get_radius staticmethod

get_radius(sigma: float) -> int

Compute the radius required for a given sigma value.

Parameters:

  • sigma

    (float) –

    Gaussian sigma value.

Returns:

  • int

    Radius.

Source code in vsrgtools/blur.py
232
233
234
235
236
237
238
239
240
241
242
243
@staticmethod
def get_radius(sigma: float) -> int:
    """
    Compute the radius required for a given sigma value.

    Args:
        sigma: Gaussian sigma value.

    Returns:
        Radius.
    """
    return BlurMatrix.GAUSS.get_radius(sigma)

get_sigma staticmethod

get_sigma(radius: int) -> float

Generate a Gaussian sigma value from an intuitive radius.

This is a shortcut that converts a blur radius to a corresponding sigma value.

Parameters:

  • radius

    (int) –

    Blur radius.

Returns:

  • float

    Gaussian sigma value

Source code in vsrgtools/blur.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
@staticmethod
def get_sigma(radius: int) -> float:
    """
    Generate a Gaussian sigma value from an intuitive radius.

    This is a shortcut that converts a blur radius to a corresponding sigma value.

    Args:
        radius: Blur radius.

    Returns:
        Gaussian sigma value
    """
    return BlurMatrix.GAUSS.get_sigma(radius)

GuidedFilter

GuidedFilter(guided_filter_func: Callable[P, R])

Class decorator that wraps the guided_filter function and extends its functionality.

It is not meant to be used directly.

Classes:

Methods:

Source code in vsrgtools/blur.py
756
757
def __init__(self, guided_filter_func: Callable[P, R]) -> None:
    self._func = guided_filter_func

Mode

Bases: CustomIntEnum

Methods:

Attributes:

  • GRADIENT

    Gradient Domain Guided Image Filter

  • ORIGINAL

    Original Guided Filter

  • WEIGHTED

    Weighted Guided Image Filter

GRADIENT class-attribute instance-attribute

GRADIENT = 2

Gradient Domain Guided Image Filter

ORIGINAL class-attribute instance-attribute

ORIGINAL = 0

Original Guided Filter

WEIGHTED class-attribute instance-attribute

WEIGHTED = 1

Weighted Guided Image Filter

from_param classmethod

from_param(value: Any, func_except: FuncExcept | None = None) -> Self

Return the enum value from a parameter.

Parameters:

  • value
    (Any) –

    Value to instantiate the enum class.

  • func_except
    (FuncExcept | None, default: None ) –

    Exception function.

Returns:

  • Self

    Enum value.

Raises:

Source code in jetpytools/enums/base.py
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
@classmethod
def from_param(cls, value: Any, func_except: FuncExcept | None = None) -> Self:
    """
    Return the enum value from a parameter.

    Args:
        value: Value to instantiate the enum class.
        func_except: Exception function.

    Returns:
        Enum value.

    Raises:
        NotFoundEnumValue: Variable not found in the given enum.
    """
    func_except = func_except or cls.from_param

    try:
        return cls(value)
    except (ValueError, TypeError):
        pass

    if isinstance(func_except, tuple):
        func_name, var_name = func_except
    else:
        func_name, var_name = func_except, repr(cls)

    raise NotFoundEnumValueError(
        'The given value for "{var_name}" argument must be a valid {enum_name}, not "{value}"!\n'
        "Valid values are: [{readable_enum}].",
        func_name,
        var_name=var_name,
        enum_name=cls,
        value=value,
        readable_enum=(f"{name} ({value!s})" for name, value in cls.__members__.items()),
        reason=value,
    ) from None

value

value() -> int
Source code in jetpytools/enums/base.py
86
87
@enum_property
def value(self) -> int: ...

__call__

__call__(*args: P.args, **kwargs: P.kwargs) -> R
Source code in vsrgtools/blur.py
759
760
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R:
    return self._func(*args, **kwargs)

bilateral

bilateral(
    clip: VideoNode,
    ref: VideoNode | None = None,
    sigmaS: float | Sequence[float] | None = None,
    sigmaR: float | Sequence[float] | None = None,
    planes: Planes = None,
    backend: Backend = AUTO,
    **kwargs: Any,
) -> VideoNode

Applies a bilateral filter for edge-preserving and noise-reducing smoothing.

This filter replaces each pixel with a weighted average of nearby pixels based on both spatial distance and pixel intensity similarity. It can be used for joint (cross) bilateral filtering when a reference clip is given.

Example
blurred = bilateral(clip, ref, 3.0, 0.02, backend=bilateral.Backend.CPU)

For more details, see:

Parameters:

  • clip

    (VideoNode) –

    Source clip.

  • ref

    (VideoNode | None, default: None ) –

    Optional reference clip for joint bilateral filtering.

  • sigmaS

    (float | Sequence[float] | None, default: None ) –

    Spatial sigma (controls the extent of spatial smoothing). Can be a float or per-plane list.

  • sigmaR

    (float | Sequence[float] | None, default: None ) –

    Range sigma (controls sensitivity to intensity differences). Can be a float or per-plane list.

  • planes

    (Planes, default: None ) –

    Planes to process. Defaults to all.

  • backend

    (Backend, default: AUTO ) –

    The backend to use for processing. Set bilateral.backend = bilateral.Backend.GPU or use the context manager with bilateral.Backend.GPU(): ... to make the GPU the default backend for all subsequent explicit and implicit calls.

  • **kwargs

    (Any, default: {} ) –

    Additional arguments forwarded to the backend-specific implementation.

Returns:

  • VideoNode

    Bilaterally filtered clip.

Source code in vsrgtools/blur.py
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
@Bilateral
def bilateral(
    clip: vs.VideoNode,
    ref: vs.VideoNode | None = None,
    sigmaS: float | Sequence[float] | None = None,  # noqa: N803
    sigmaR: float | Sequence[float] | None = None,  # noqa: N803
    planes: Planes = None,
    backend: Bilateral.Backend = Bilateral.Backend.AUTO,
    **kwargs: Any,
) -> vs.VideoNode:
    """
    Applies a bilateral filter for edge-preserving and noise-reducing smoothing.

    This filter replaces each pixel with a weighted average of nearby pixels based on both spatial distance
    and pixel intensity similarity.
    It can be used for joint (cross) bilateral filtering when a reference clip is given.

    Example:
        ```py
        blurred = bilateral(clip, ref, 3.0, 0.02, backend=bilateral.Backend.CPU)
        ```

    For more details, see:

      - <https://github.com/dnjulek/vapoursynth-zip/wiki/Bilateral>
      - <https://github.com/dnjulek/vapoursynth-zipcl/wiki/Bilateral>
      - <https://github.com/WolframRhodium/VapourSynth-BilateralGPU>

    Args:
        clip: Source clip.
        ref: Optional reference clip for joint bilateral filtering.
        sigmaS: Spatial sigma (controls the extent of spatial smoothing). Can be a float or per-plane list.
        sigmaR: Range sigma (controls sensitivity to intensity differences). Can be a float or per-plane list.
        planes: Planes to process. Defaults to all.
        backend: The backend to use for processing.
            Set `bilateral.backend = bilateral.Backend.GPU`
            or use the context manager `with bilateral.Backend.GPU(): ...`
            to make the GPU the default backend for all subsequent explicit and implicit calls.
        **kwargs: Additional arguments forwarded to the backend-specific implementation.

    Returns:
        Bilaterally filtered clip.
    """

    backend = backend.resolve()
    logger.debug("bilateral(): Selecting backend %r", backend)

    bilateral_args: dict[str, Any] = {"ref": ref}

    if backend == Bilateral.Backend.CPU:
        bilateral_args |= {"sigmaS": sigmaS, "sigmaR": sigmaR, "planes": normalize_planes(clip, planes)}
    else:
        sigmaS = normalize_param_planes(clip, sigmaS, planes, 0) if sigmaS is not None else sigmaS
        sigmaR = normalize_param_planes(clip, sigmaR, planes, 0) if sigmaR is not None else sigmaR
        bilateral_args |= {"sigma_spatial": sigmaS, "sigma_color": sigmaR}

        if backend == Bilateral.Backend.GPU:
            bilateral_args["num_streams"] = 2

    return backend.Bilateral(clip, **bilateral_args | kwargs)

box_blur

box_blur(
    clip: VideoNode,
    radius: int | Sequence[int] = 1,
    passes: int = 1,
    mode: OneDimConvMode | TempConvMode = HV,
    planes: Planes = None,
    **kwargs: Any,
) -> VideoNode

Applies a box blur to the input clip.

Parameters:

  • clip

    (VideoNode) –

    Source clip.

  • radius

    (int | Sequence[int], default: 1 ) –

    Blur radius (spatial or temporal) Can be a int or a list for per-plane control. Defaults to 1

  • passes

    (int, default: 1 ) –

    Number of times the blur is applied. Defaults to 1

  • mode

    (OneDimConvMode | TempConvMode, default: HV ) –

    Convolution mode (horizontal, vertical, both, or temporal). Defaults to HV.

  • planes

    (Planes, default: None ) –

    Planes to process. Defaults to all.

Raises:

  • CustomValueError

    If square convolution mode is specified, which is unsupported.

Returns:

  • VideoNode

    Blurred clip.

Source code in vsrgtools/blur.py
 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
def box_blur(
    clip: vs.VideoNode,
    radius: int | Sequence[int] = 1,
    passes: int = 1,
    mode: OneDimConvMode | TempConvMode = ConvMode.HV,
    planes: Planes = None,
    **kwargs: Any,
) -> vs.VideoNode:
    """
    Applies a box blur to the input clip.

    Args:
        clip: Source clip.
        radius: Blur radius (spatial or temporal) Can be a int or a list for per-plane control. Defaults to 1
        passes: Number of times the blur is applied. Defaults to 1
        mode: Convolution mode (horizontal, vertical, both, or temporal). Defaults to HV.
        planes: Planes to process. Defaults to all.

    Raises:
        CustomValueError: If square convolution mode is specified, which is unsupported.

    Returns:
        Blurred clip.
    """
    if isinstance(radius, Sequence):
        return normalize_radius(clip, box_blur, radius, planes, passes=passes, mode=mode, **kwargs)

    if not radius:
        return clip

    if mode == ConvMode.TEMPORAL:
        return BlurMatrix.MEAN(radius, mode=mode)(clip, planes, passes=passes, **kwargs)

    if not TYPE_CHECKING and mode == ConvMode.SQUARE:
        raise CustomValueError("Invalid mode specified", box_blur, mode)

    box_args = (
        planes,
        radius,
        0 if mode == ConvMode.VERTICAL else passes,
        radius,
        0 if mode == ConvMode.HORIZONTAL else passes,
    )

    return clip.vszip.BoxBlur(*box_args)

flux_smooth

flux_smooth(
    clip: VideoNode,
    temporal_threshold: float | Sequence[float] = 7.0,
    spatial_threshold: float | Sequence[float] | None = None,
    planes: Planes = None,
    scalep: bool = True,
) -> VideoNode

FluxSmoothT examines each pixel and compares it to the corresponding pixel in the previous and next frames. Smoothing occurs if both the previous frame's value and the next frame's value are greater, or if both are less than the value in the current frame.

Smoothing is done by averaging the pixel from the current frame with the pixels from the previous and/or next frames, if they are within temporal_threshold.

FluxSmoothST does the same as FluxSmoothT, except the pixel's eight neighbours from the current frame are also included in the average, if they are within spatial_threshold.

The first and last rows and the first and last columns are not processed by FluxSmoothST.

Parameters:

  • clip

    (VideoNode) –

    Clip to process.

  • temporal_threshold

    (float | Sequence[float], default: 7.0 ) –

    Temporal neighbour pixels within this threshold from the current pixel are included in the average. Can be specified as an array, with values corresponding to each plane of the input clip. A negative value (such as -1) indicates that the plane should not be processed and will be copied from the input clip.

  • spatial_threshold

    (float | Sequence[float] | None, default: None ) –

    Spatial neighbour pixels within this threshold from the current pixel are included in the average. A negative value (such as -1) indicates that the plane should not be processed and will be copied from the input clip.

  • planes

    (Planes, default: None ) –

    Which planes to process. Default to all.

  • scalep

    (bool, default: True ) –

    Parameter scaling. If set to true, all threshold values will be automatically scaled from 8-bit range (0-255) to the corresponding range of the input clip's bit depth.

Returns:

  • VideoNode

    Smoothed clip.

Source code in vsrgtools/blur.py
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
def flux_smooth(
    clip: vs.VideoNode,
    temporal_threshold: float | Sequence[float] = 7.0,
    spatial_threshold: float | Sequence[float] | None = None,
    planes: Planes = None,
    scalep: bool = True,
) -> vs.VideoNode:
    """
    FluxSmoothT examines each pixel and compares it to the corresponding pixel in the previous and next frames.
    Smoothing occurs if both the previous frame's value and the next frame's value are greater,
    or if both are less than the value in the current frame.

    Smoothing is done by averaging the pixel from the current frame with the pixels from the previous
    and/or next frames, if they are within temporal_threshold.

    FluxSmoothST does the same as FluxSmoothT, except the pixel's eight neighbours from the current frame
    are also included in the average, if they are within spatial_threshold.

    The first and last rows and the first and last columns are not processed by FluxSmoothST.

    Args:
        clip: Clip to process.
        temporal_threshold: Temporal neighbour pixels within this threshold from the current pixel are included in the
            average. Can be specified as an array, with values corresponding to each plane of the input clip. A negative
            value (such as -1) indicates that the plane should not be processed and will be copied from the input clip.
        spatial_threshold: Spatial neighbour pixels within this threshold from the current pixel are included in the
            average. A negative value (such as -1) indicates that the plane should not be processed and will be copied
            from the input clip.
        planes: Which planes to process. Default to all.
        scalep: Parameter scaling. If set to true, all threshold values will be automatically scaled from 8-bit range
            (0-255) to the corresponding range of the input clip's bit depth.

    Returns:
        Smoothed clip.
    """
    if spatial_threshold:
        return core.zsmooth.FluxSmoothST(clip, temporal_threshold, spatial_threshold, planes, scalep)

    return core.zsmooth.FluxSmoothT(clip, temporal_threshold, planes, scalep)

gauss_blur

gauss_blur(
    clip: VideoNode,
    sigma: float | Sequence[float] = 0.5,
    radius: int | None = None,
    mode: OneDimConvMode | TempConvMode = HV,
    planes: Planes = None,
    backend: Backend = AUTO,
    **kwargs: Any,
) -> VideoNode

Applies Gaussian blur to a clip, supporting spatial and temporal modes, and per-plane control.

Parameters:

  • clip

    (VideoNode) –

    Source clip.

  • sigma

    (float | Sequence[float], default: 0.5 ) –

    Standard deviation of the Gaussian kernel. Can be a float or a list for per-plane control.

  • radius

    (int | None, default: None ) –

    Size of the kernel in each direction. Automatically determined if not specified.

  • mode

    (OneDimConvMode | TempConvMode, default: HV ) –

    Convolution mode (horizontal, vertical, both, or temporal). Defaults to HV.

  • planes

    (Planes, default: None ) –

    Planes to process. Defaults to all.

  • backend

    (Backend, default: AUTO ) –

    The backend to use for processing. Set gauss_blur.backend = gauss_blur.Backend.GPU or use the context manager with gauss_blur.Backend.GPU(): ... to make the GPU the default backend for all subsequent explicit and implicit calls.

  • **kwargs

    (Any, default: {} ) –

    Additional arguments passed to the resizer or blur kernel. Specifying _fast=True enables fast bilinear approximation.

Raises:

Returns:

  • VideoNode

    Blurred clip.

Source code in vsrgtools/blur.py
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
@GaussBlur
def gauss_blur(
    clip: vs.VideoNode,
    sigma: float | Sequence[float] = 0.5,
    radius: int | None = None,
    mode: OneDimConvMode | TempConvMode = ConvMode.HV,
    planes: Planes = None,
    backend: GaussBlur.Backend = GaussBlur.Backend.AUTO,
    **kwargs: Any,
) -> vs.VideoNode:
    """
    Applies Gaussian blur to a clip, supporting spatial and temporal modes, and per-plane control.

    Args:
        clip: Source clip.
        sigma: Standard deviation of the Gaussian kernel. Can be a float or a list for per-plane control.
        radius: Size of the kernel in each direction. Automatically determined if not specified.
        mode: Convolution mode (horizontal, vertical, both, or temporal). Defaults to HV.
        planes: Planes to process. Defaults to all.
        backend: The backend to use for processing.
            Set `gauss_blur.backend = gauss_blur.Backend.GPU`
            or use the context manager `with gauss_blur.Backend.GPU(): ...`
            to make the GPU the default backend for all subsequent explicit and implicit calls.
        **kwargs: Additional arguments passed to the resizer or blur kernel.
            Specifying `_fast=True` enables fast bilinear approximation.

    Raises:
        CustomValueError: If `mode` is `ConvMode.SQUARE`, which is not supported.
        CustomNotImplementedError: If the GPU backend is selected and `mode` is not `ConvMode.HV`.

    Returns:
        Blurred clip.
    """
    if not TYPE_CHECKING and mode == ConvMode.SQUARE:
        raise CustomValueError("Invalid mode specified", gauss_blur, mode)

    fast = kwargs.pop("_fast", False)
    backend = backend.resolve()
    logger.debug("gauss_blur(): Selecting backend %r", backend)

    if backend.resolve() == gauss_blur.Backend.GPU:
        if mode != ConvMode.HV:
            raise CustomNotImplementedError(f"GPU backend doesn't support the mode {mode}", gauss_blur)

        return core.vszipcl.GaussBlur(clip, normalize_param_planes(clip, sigma, planes, 0), **kwargs)

    if isinstance(sigma, Sequence):
        return normalize_radius(clip, gauss_blur, {"sigma": sigma}, planes, radius=radius, mode=mode)

    planes = normalize_planes(clip, planes)

    sigma_constant = 0.9 if fast and not mode.is_temporal else sigma

    if radius is None:
        radius = gauss_blur.get_radius(sigma_constant)

    if not mode.is_temporal:

        def _resize2_blur(plane: vs.VideoNode, sigma: float, taps: int) -> vs.VideoNode:
            resize_kwargs = dict[str, Any]()

            # Downscale approximation can be used by specifying _fast=True
            # Has a big speed gain when taps is large
            if fast:
                wdown, hdown = plane.width, plane.height

                if ConvMode.VERTICAL in mode:
                    hdown = round(max(round(hdown / sigma), 2) / 2) * 2

                if ConvMode.HORIZONTAL in mode:
                    wdown = round(max(round(wdown / sigma), 2) / 2) * 2

                resize_kwargs.update(width=plane.width, height=plane.height)

                plane = core.resize.Bilinear(plane, wdown, hdown)
                sigma = sigma_constant
            else:
                resize_kwargs.update({f"force_{k}": k in mode for k in "hv"})

            return Gaussian(sigma, taps).scale(plane, **resize_kwargs | kwargs)

        if not {*range(clip.format.num_planes)} - {*planes}:
            return _resize2_blur(clip, sigma, radius)

        return join([_resize2_blur(p, sigma, radius) if i in planes else p for i, p in enumerate(split(clip))])

    kernel = BlurMatrix.GAUSS(radius, sigma=sigma, mode=mode, scale_value=1023)

    return kernel(clip, planes, **kwargs)

guided_filter

guided_filter(
    clip: VideoNode,
    guidance: VideoNode | None = None,
    radius: int | Sequence[int] | None = None,
    thr: float | Sequence[float] = 1 / 3,
    mode: Mode = GRADIENT,
    use_gauss: bool = False,
    planes: Planes = None,
    down_ratio: int = 0,
    downscaler: ScalerLike = Point,
    upscaler: ScalerLike = Bilinear,
) -> VideoNode
Source code in vsrgtools/blur.py
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
@GuidedFilter
def guided_filter(
    clip: vs.VideoNode,
    guidance: vs.VideoNode | None = None,
    radius: int | Sequence[int] | None = None,
    thr: float | Sequence[float] = 1 / 3,
    mode: GuidedFilter.Mode = GuidedFilter.Mode.GRADIENT,
    use_gauss: bool = False,
    planes: Planes = None,
    down_ratio: int = 0,
    downscaler: ScalerLike = Point,
    upscaler: ScalerLike = Bilinear,
) -> vs.VideoNode:
    UnsupportedSampleTypeError.check(clip, vs.FLOAT, guided_filter)

    planes = normalize_planes(clip, planes)

    downscaler = Scaler.ensure_obj(downscaler, guided_filter)
    upscaler = Scaler.ensure_obj(upscaler, guided_filter)

    width, height = clip.width, clip.height

    thr = normalize_seq(thr, clip.format.num_planes)

    size = normalize_seq(
        [220, 225, 225] if Range.from_video(clip, func=guided_filter).is_full else 256, clip.format.num_planes
    )

    thr = [t / s for t, s in zip(thr, size)]

    if radius is None:
        radius = [
            round(max((w - 1280) / 160 + 12, (h - 720) / 90 + 12))
            for w, h in [get_plane_sizes(clip, i) for i in range(clip.format.num_planes)]
        ]

    p = clip
    if guidance:
        check_ref_clip(guidance, clip)
        guidance_clip = g = guidance
    else:
        guidance_clip = g = clip

    radius = normalize_seq(radius, clip.format.num_planes)

    if down_ratio:
        down_w, down_h = cround(width / down_ratio), cround(height / down_ratio)

        p = downscaler.scale(p, down_w, down_h)
        g = downscaler.scale(g, down_w, down_h) if guidance is not None else p

        radius = [cround(rad / down_ratio) for rad in radius]

    blur_filter = (
        partial(gauss_blur, sigma=[rad / 2 * sqrt(2) for rad in radius], planes=planes)
        if use_gauss
        else partial(box_blur, radius=[rad + 1 for rad in radius], planes=planes)
    )

    blur_filter_corr = (
        partial(gauss_blur, sigma=1 / 2 * sqrt(2), planes=planes)
        if use_gauss
        else partial(box_blur, radius=2, planes=planes)
    )

    mean_p = blur_filter(p)
    mean_I = blur_filter(g) if guidance is not None else mean_p

    I_square = norm_expr(g, "x dup *", planes, func=guided_filter)
    corr_I = blur_filter(I_square)
    corr_Ip = blur_filter(norm_expr([g, p], "x y *", planes, func=guided_filter)) if guidance is not None else corr_I

    var_I = norm_expr([corr_I, mean_I], "x y dup * -", planes, func=guided_filter)
    cov_Ip = (
        norm_expr([corr_Ip, mean_I, mean_p], "x y z * -", planes, func=guided_filter) if guidance is not None else var_I
    )

    if mode is GuidedFilter.Mode.ORIGINAL:
        a = norm_expr([cov_Ip, var_I], "x y {thr} + /", planes, thr=thr, func=guided_filter)
    else:
        if set(radius) == {1}:
            var_I_1 = var_I
        else:
            mean_I_1 = blur_filter_corr(g)
            corr_I_1 = blur_filter_corr(I_square)
            var_I_1 = norm_expr([corr_I_1, mean_I_1], "x y dup * -", planes, func=guided_filter)

        if mode is GuidedFilter.Mode.WEIGHTED:
            weight_in = var_I_1
        else:
            weight_in = norm_expr([var_I, var_I_1], "x y * sqrt", planes, func=guided_filter)

        denominator = norm_expr([weight_in], "1 x {eps} + /", planes, eps=1e-06, func=guided_filter)

        denominator = denominator.std.PlaneStats(None, 0)

        weight = norm_expr([weight_in, denominator], "x 1e-06 + y.PlaneStatsAverage *", planes, func=guided_filter)

        if mode is GuidedFilter.Mode.WEIGHTED:
            a = norm_expr([cov_Ip, var_I, weight], "x y {thr} z / + /", planes, thr=thr, func=guided_filter)
        else:
            weight_in = weight_in.std.PlaneStats(None, 0)

            a = norm_expr(
                [cov_Ip, weight_in, weight, var_I],
                "x {thr} 1 1 1 -4 y.PlaneStatsMin y.PlaneStatsAverage 1e-6 - - / "
                "y y.PlaneStatsAverage - * exp + / - * z / + a {thr} z / + /",
                planes,
                thr=thr,
            )

    b = norm_expr([mean_p, a, mean_I], "x y z * -", planes, func=guided_filter)

    mean_a, mean_b = blur_filter(a), blur_filter(b)

    if down_ratio:
        mean_a = upscaler.scale(mean_a, width, height)
        mean_b = upscaler.scale(mean_b, width, height)

    return norm_expr([mean_a, guidance_clip, mean_b], "x y * z +", planes, func=guided_filter)

median_blur

median_blur(
    clip: VideoNode,
    radius: int | Sequence[int] = 1,
    mode: SpatialConvMode = SQUARE,
    planes: Planes = None,
    *,
    func: FuncExcept | None = None,
) -> VideoNode
median_blur(
    clip: VideoNode,
    radius: int | Sequence[int] = 1,
    mode: Literal[SQUARE] = ...,
    planes: Planes = None,
    smart: Literal[True] = ...,
    threshold: float | Sequence[float] | None = None,
    scalep: bool = True,
    *,
    func: FuncExcept | None = None,
) -> VideoNode
median_blur(
    clip: VideoNode,
    radius: int = 1,
    mode: Literal[TEMPORAL] = ...,
    planes: Planes = None,
    *,
    scenechange: bool = False,
    func: FuncExcept | None = None,
) -> VideoNode
median_blur(
    clip: VideoNode,
    radius: int | Sequence[int] = 1,
    mode: ConvMode = SQUARE,
    planes: Planes = None,
    smart: bool = False,
    threshold: float | Sequence[float] | None = None,
    scalep: bool = True,
    scenechange: bool = False,
    func: FuncExcept | None = None,
) -> VideoNode
median_blur(
    clip: VideoNode,
    radius: int | Sequence[int] = 1,
    mode: ConvMode = SQUARE,
    planes: Planes = None,
    smart: bool = False,
    threshold: float | Sequence[float] | None = None,
    scalep: bool = True,
    scenechange: bool = False,
    func: FuncExcept | None = None,
) -> VideoNode

Applies a median blur to the clip using spatial or temporal neighborhood.

  • In temporal mode, each pixel is replaced by the median across multiple frames.
  • In spatial modes, each pixel is replaced with the median of its 2D neighborhood.

Parameters:

  • clip

    (VideoNode) –

    Source clip.

  • radius

    (int | Sequence[int], default: 1 ) –

    Blur radius per plane (list) or uniform radius (int). Only int is allowed in temporal mode.

  • mode

    (ConvMode, default: SQUARE ) –

    Convolution mode. Defaults to SQUARE.

  • planes

    (Planes, default: None ) –

    Planes to process. Defaults to all.

  • smart

    (bool, default: False ) –

    Enable Smart Median by zsmooth, thresholded based on a modified form of variance.

  • threshold

    (float | Sequence[float] | None, default: None ) –

    The variance threshold when smart=True. Pixels with a variance under the threshold are smoothed, and over the threshold are returned as is.

  • scalep

    (bool, default: True ) –

    Parameter scaling when smart=True. If True, all threshold values will be automatically scaled from 8-bit range (0-255) to the corresponding range of the input clip's bit depth.

  • scenechange

    (bool, default: False ) –

    If True, avoid averaging frames over scene changes. The user must first invoke sc_detect.

  • func

    (FuncExcept | None, default: None ) –

    Function returned for custom error handling. This should only be set by VS package developers.

Raises:

  • CustomValueError

    If a list is passed for radius in temporal mode, which is unsupported or if smart=True and mode != ConvMode.SQUARE.

Returns:

  • VideoNode

    Median-blurred video clip.

Source code in vsrgtools/blur.py
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
def median_blur(
    clip: vs.VideoNode,
    radius: int | Sequence[int] = 1,
    mode: ConvMode = ConvMode.SQUARE,
    planes: Planes = None,
    smart: bool = False,
    threshold: float | Sequence[float] | None = None,
    scalep: bool = True,
    scenechange: bool = False,
    func: FuncExcept | None = None,
) -> vs.VideoNode:
    """
    Applies a median blur to the clip using spatial or temporal neighborhood.

    - In temporal mode, each pixel is replaced by the median across multiple frames.
    - In spatial modes, each pixel is replaced with the median of its 2D neighborhood.

    Args:
        clip: Source clip.
        radius: Blur radius per plane (list) or uniform radius (int). Only int is allowed in temporal mode.
        mode: Convolution mode. Defaults to SQUARE.
        planes: Planes to process. Defaults to all.
        smart: Enable [Smart Median by zsmooth](https://github.com/adworacz/zsmooth?tab=readme-ov-file#smart-median),
            thresholded based on a modified form of variance.
        threshold: The variance threshold when ``smart=True``. Pixels with a variance under the threshold are smoothed,
            and over the threshold are returned as is.
        scalep: Parameter scaling when ``smart=True``. If True, all threshold values will be automatically scaled
            from 8-bit range (0-255) to the corresponding range of the input clip's bit depth.
        scenechange: If True, avoid averaging frames over scene changes.
            The user must first invoke [sc_detect][vstools.sc_detect].
        func: Function returned for custom error handling. This should only be set by VS package developers.

    Raises:
        CustomValueError: If a list is passed for radius in temporal mode, which is unsupported
            or if smart=True and mode != ConvMode.SQUARE.

    Returns:
        Median-blurred video clip.
    """
    func = func or median_blur

    if mode == ConvMode.TEMPORAL:
        if not isinstance(radius, int):
            raise CustomValueError("A list of radius isn't supported for ConvMode.TEMPORAL!", func, radius)

        return core.zsmooth.TemporalMedian(clip, radius, planes, scenechange)

    radius = normalize_seq(radius, clip.format.num_planes)

    if smart:
        if mode == ConvMode.SQUARE:
            return core.zsmooth.SmartMedian(clip, radius, threshold, scalep, planes)

        raise CustomValueError("When using SmartMedian, mode should be ConvMode.SQUARE!", func, mode)

    if mode == ConvMode.SQUARE and max(radius) <= 3:
        return core.zsmooth.Median(clip, radius, planes)

    if mode == ConvMode.VERTICAL and max(radius) <= 1:
        return vertical_cleaner(clip, radius, planes)

    return MeanMode.MEDIAN.single(clip, radius, mode, planes=planes, func=func)

min_blur

min_blur(
    clip: VideoNode,
    radius: int | Sequence[int] = 1,
    mode: tuple[ConvMode, ConvMode] = (HV, SQUARE),
    planes: Planes = None,
    **kwargs: Any,
) -> VideoNode

Combines binomial (Gaussian-like) blur and median filtering for a balanced smoothing effect.

This filter blends the input clip with both a binomial blur and a median blur to achieve a "best of both worlds" result — combining the edge-preserving nature of median filtering with the smoothness of Gaussian blur. The effect is somewhat reminiscent of a bilateral filter.

Original concept: http://avisynth.nl/index.php/MinBlur

Parameters:

  • clip

    (VideoNode) –

    Source clip.

  • radius

    (int | Sequence[int], default: 1 ) –

    Radius of blur to apply. Can be a single int or a list for per-plane control.

  • mode

    (tuple[ConvMode, ConvMode], default: (HV, SQUARE) ) –

    A tuple of two convolution modes:

    • First element: mode for binomial blur.
    • Second element: mode for median blur. Defaults to (HV, SQUARE).
  • planes

    (Planes, default: None ) –

    Planes to process. Defaults to all.

  • **kwargs

    (Any, default: {} ) –

    Additional arguments passed to the binomial blur.

Returns:

  • VideoNode

    Clip with MinBlur applied.

Source code in vsrgtools/blur.py
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
def min_blur(
    clip: vs.VideoNode,
    radius: int | Sequence[int] = 1,
    mode: tuple[ConvMode, ConvMode] = (ConvMode.HV, ConvMode.SQUARE),
    planes: Planes = None,
    **kwargs: Any,
) -> vs.VideoNode:
    """
    Combines binomial (Gaussian-like) blur and median filtering for a balanced smoothing effect.

    This filter blends the input clip with both a binomial blur and a median blur to achieve
    a "best of both worlds" result — combining the edge-preserving nature of median filtering
    with the smoothness of Gaussian blur. The effect is somewhat reminiscent of a bilateral filter.

    Original concept: <http://avisynth.nl/index.php/MinBlur>

    Args:
        clip: Source clip.
        radius: Radius of blur to apply. Can be a single int or a list for per-plane control.
        mode: A tuple of two convolution modes:

               - First element: mode for binomial blur.
               - Second element: mode for median blur.
            Defaults to (HV, SQUARE).

        planes: Planes to process. Defaults to all.
        **kwargs: Additional arguments passed to the binomial blur.

    Returns:
        Clip with MinBlur applied.
    """
    planes = normalize_planes(clip, planes)

    if isinstance(radius, Sequence):
        return normalize_radius(clip, min_blur, radius, planes)

    mode_blur, mode_median = normalize_seq(mode, 2)

    blurred = BlurMatrix.BINOMIAL(radius, mode=mode_blur)(clip, planes=planes, **kwargs)
    median = median_blur(clip, radius, mode_median, planes=planes)

    return MeanMode.MEDIAN([clip, blurred, median], planes=planes)

sbr

sbr(
    clip: VideoNode,
    radius: int | Sequence[int] = 1,
    mode: ConvMode = HV,
    blur: BlurMatrix
    | Sequence[float]
    | VideoNode
    | VSFunctionNoArgs = BINOMIAL,
    blur_diff: BlurMatrix | Sequence[float] | VSFunctionNoArgs = BINOMIAL,
    planes: Planes = None,
    *,
    func: FuncExcept | None = None,
    **kwargs: Any,
) -> VideoNode

A helper function for high-pass filtering a blur difference, inspired by an AviSynth script by Didée.

https://forum.doom9.org/showthread.php?p=1584186#post1584186

Parameters:

  • clip

    (VideoNode) –

    Source clip.

  • radius

    (int | Sequence[int], default: 1 ) –

    Specifies the size of the blur kernels if blur or blur_diff is a BlurMatrix enum. Default to 1.

  • mode

    (ConvMode, default: HV ) –

    Specifies the convolution mode. Defaults to horizontal + vertical.

  • blur

    (BlurMatrix | Sequence[float] | VideoNode | VSFunctionNoArgs, default: BINOMIAL ) –

    Blur kernel to apply to the original clip. Defaults to binomial.

  • blur_diff

    (BlurMatrix | Sequence[float] | VSFunctionNoArgs, default: BINOMIAL ) –

    Blur kernel to apply to the difference clip. Defaults to binomial.

  • planes

    (Planes, default: None ) –

    Which planes to process. Defaults to all.

  • func

    (FuncExcept | None, default: None ) –

    Function returned for custom error handling. This should only be set by VS package developers.

  • **kwargs

    (Any, default: {} ) –

    Additional arguments passed to blur kernel call.

Returns:

  • VideoNode

    Sbr'd clip.

Source code in vsrgtools/blur.py
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
def sbr(
    clip: vs.VideoNode,
    radius: int | Sequence[int] = 1,
    mode: ConvMode = ConvMode.HV,
    blur: BlurMatrix | Sequence[float] | vs.VideoNode | VSFunctionNoArgs = BlurMatrix.BINOMIAL,
    blur_diff: BlurMatrix | Sequence[float] | VSFunctionNoArgs = BlurMatrix.BINOMIAL,
    planes: Planes = None,
    *,
    func: FuncExcept | None = None,
    **kwargs: Any,
) -> vs.VideoNode:
    """
    A helper function for high-pass filtering a blur difference, inspired by an AviSynth script by Didée.

    <https://forum.doom9.org/showthread.php?p=1584186#post1584186>

    Args:
        clip: Source clip.
        radius: Specifies the size of the blur kernels if `blur` or `blur_diff` is a BlurMatrix enum. Default to 1.
        mode: Specifies the convolution mode. Defaults to horizontal + vertical.
        blur: Blur kernel to apply to the original clip. Defaults to binomial.
        blur_diff: Blur kernel to apply to the difference clip. Defaults to binomial.
        planes: Which planes to process. Defaults to all.
        func: Function returned for custom error handling. This should only be set by VS package developers.
        **kwargs: Additional arguments passed to blur kernel call.

    Returns:
        Sbr'd clip.
    """
    func = func or sbr

    if isinstance(radius, Sequence):
        return normalize_radius(clip, sbr, list(radius), planes)

    def _apply_blur(
        clip: vs.VideoNode, blur: BlurMatrix | Sequence[float] | vs.VideoNode | VSFunctionNoArgs
    ) -> vs.VideoNode:
        if isinstance(blur, Sequence):
            return BlurMatrix.custom(blur, mode)(clip, planes, **kwargs)

        if isinstance(blur, BlurMatrix):
            return blur(radius, mode=mode)(clip, planes, **kwargs)

        blurred = blur(clip) if callable(blur) else blur

        return blurred

    planes = normalize_planes(clip, planes)

    blurred = _apply_blur(clip, blur)

    diff = clip.std.MakeDiff(blurred, planes=planes)
    blurred_diff = _apply_blur(diff, blur_diff)

    return norm_expr(
        [clip, diff, blurred_diff],
        "y z - D1! y neutral - D2! D1@ D2@ xor x x D1@ abs D2@ abs < D1@ D2@ ? - ?",
        planes=planes,
        func=func,
    )

side_box_blur

side_box_blur(
    clip: VideoNode, radius: int = 1, planes: Planes = None
) -> VideoNode
Source code in vsrgtools/blur.py
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
def side_box_blur(clip: vs.VideoNode, radius: int = 1, planes: Planes = None) -> vs.VideoNode:
    half_kernel = [(1 if i <= 0 else 0) for i in range(-radius, radius + 1)]

    vrt_filters = [
        partial(core.std.Convolution, matrix=half_kernel, planes=planes, mode=ConvMode.VERTICAL),
        partial(core.std.Convolution, matrix=half_kernel[::-1], planes=planes, mode=ConvMode.VERTICAL),
        partial(box_blur, radius=radius, mode=ConvMode.VERTICAL, planes=planes),
    ]

    hrz_filters = [
        partial(core.std.Convolution, matrix=half_kernel, planes=planes, mode=ConvMode.HORIZONTAL),
        partial(core.std.Convolution, matrix=half_kernel[::-1], planes=planes, mode=ConvMode.HORIZONTAL),
        partial(box_blur, radius=radius, mode=ConvMode.HORIZONTAL, planes=planes),
    ]

    vrt_intermediates = (vrt_flt(clip) for vrt_flt in vrt_filters)
    intermediates = (
        hrz_flt(vrt_intermediate)
        for i, vrt_intermediate in enumerate(vrt_intermediates)
        for j, hrz_flt in enumerate(hrz_filters)
        if not i == j == 2
    )

    return reduce(
        lambda x, y: norm_expr([x, y, clip], "x z - abs y z - abs < x y ?", planes, func=side_box_blur), intermediates
    )