Skip to content

enum

Classes:

  • BlurMatrix

    Enum for predefined 1D and 2D blur kernel generators.

  • BlurMatrixBase

    Represents a convolution kernel (matrix) for spatial or temporal filtering.

BlurMatrix

Bases: CustomEnum

Enum for predefined 1D and 2D blur kernel generators.

Provides commonly used blur kernels (e.g., mean, binomial, Gaussian) for convolution-based filtering.

Each kernel is returned as a BlurMatrixBase object.

Methods:

  • __call__

    Generate the blur kernel based on the enum variant.

  • custom

    Create a custom BlurMatrixBase kernel with explicit values and mode.

  • from_param

    Return the enum value from a parameter.

  • from_radius

    Generate a Gaussian blur kernel 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:

  • BINOMIAL

    Pascal triangle coefficients approximating Gaussian blur.

  • BOX_BLUR
  • BOX_BLUR_NO_CENTER
  • GAUSS

    Proper Gaussian kernel defined by sigma.

  • MEAN

    Standard mean/box blur kernel including the center pixel. Aliased as BOX_BLUR.

  • MEAN_NO_CENTER

    Mean kernel excluding the center pixel. Also aliased as BOX_BLUR_NO_CENTER.

BINOMIAL class-attribute instance-attribute

BINOMIAL = auto()

Pascal triangle coefficients approximating Gaussian blur.

BOX_BLUR class-attribute instance-attribute

BOX_BLUR = MEAN

BOX_BLUR_NO_CENTER class-attribute instance-attribute

BOX_BLUR_NO_CENTER = MEAN_NO_CENTER

GAUSS class-attribute instance-attribute

GAUSS = auto()

Proper Gaussian kernel defined by sigma.

MEAN class-attribute instance-attribute

MEAN = auto()

Standard mean/box blur kernel including the center pixel. Aliased as BOX_BLUR.

MEAN_NO_CENTER class-attribute instance-attribute

MEAN_NO_CENTER = auto()

Mean kernel excluding the center pixel. Also aliased as BOX_BLUR_NO_CENTER.

__call__

__call__(radius: int = 1, *, mode: ConvMode = SQUARE) -> BlurMatrixBase[int]
__call__(radius: int = 1, *, mode: ConvMode = SQUARE) -> BlurMatrixBase[int]
__call__(radius: int = 1, *, mode: ConvMode = HV) -> BlurMatrixBase[int]
__call__(
    radius: int | None = None,
    *,
    sigma: float = 0.5,
    mode: ConvMode = HV,
    **kwargs: Any,
) -> BlurMatrixBase[float]
__call__(radius: int | None = None, **kwargs: Any) -> BlurMatrixBase[Any]
__call__(radius: int | None = None, **kwargs: Any) -> Any

Generate the blur kernel based on the enum variant.

Parameters:

  • radius

    (int | None, default: None ) –

    Size of the kernel in each direction.

  • **kwargs

    (Any, default: {} ) –

    Additional keywords arguments:

    • sigma: [GAUSS only] Standard deviation of the Gaussian kernel.
    • mode: Convolution mode. Default depends on kernel.

Returns:

  • Any

    A BlurMatrixBase instance representing the kernel.

Source code in vsrgtools/enum.py
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
def __call__(self, radius: int | None = None, **kwargs: Any) -> Any:
    """
    Generate the blur kernel based on the enum variant.

    Args:
        radius: Size of the kernel in each direction.
        **kwargs: Additional keywords arguments:

               - sigma: [GAUSS only] Standard deviation of the Gaussian kernel.
               - mode: Convolution mode. Default depends on kernel.

    Returns:
        A `BlurMatrixBase` instance representing the kernel.
    """
    kernel: BlurMatrixBase[Any]

    match self:
        case BlurMatrix.MEAN_NO_CENTER:
            radius = fallback(radius, 1)
            mode = kwargs.pop("mode", ConvMode.SQUARE)

            matrix = [1 for _ in range(((2 * radius + 1) ** (2 if mode == ConvMode.SQUARE else 1)) - 1)]
            matrix.insert(len(matrix) // 2, 0)

            return self.custom(matrix, mode)

        case BlurMatrix.MEAN:
            radius = fallback(radius, 1)
            mode = kwargs.pop("mode", ConvMode.SQUARE)

            kernel = self.custom((1 for _ in range((2 * radius + 1))), mode)

        case BlurMatrix.BINOMIAL:
            radius = fallback(radius, 1)
            mode = kwargs.pop("mode", ConvMode.HV)

            kernel = self.custom([math.comb(2 * radius, i) for i in range(2 * radius + 1)], mode)

        case BlurMatrix.GAUSS:
            sigma = kwargs.pop("sigma", 0.5)
            mode = kwargs.pop("mode", ConvMode.HV)
            scale_value = kwargs.pop("scale_value", 1023)

            if mode == ConvMode.SQUARE:
                scale_value = math.sqrt(scale_value)

            if radius is None:
                radius = self.get_radius(sigma)

            if sigma > 0.0:
                doub_qsigma = 2 * sigma**2
                mat = [scale_value * math.exp(-(x**2) / doub_qsigma) for x in range(1, radius + 1)]
                mat = [*mat[::-1], scale_value, *mat]
            else:
                mat = [scale_value]

            kernel = self.custom(mat, mode)

        case _:
            raise CustomNotImplementedError("Unsupported blur matrix enum!", self, self)

    if mode == ConvMode.SQUARE:
        kernel = kernel.outer()

    return kernel

custom classmethod

Create a custom BlurMatrixBase kernel with explicit values and mode.

Parameters:

Returns:

Source code in vsrgtools/enum.py
438
439
440
441
442
443
444
445
446
447
448
449
450
@classmethod
def custom[Nb: float | int](cls, values: Iterable[Nb], mode: ConvMode = ConvMode.SQUARE) -> BlurMatrixBase[Nb]:
    """
    Create a custom BlurMatrixBase kernel with explicit values and mode.

    Args:
        values: The kernel coefficients.
        mode: Convolution mode to use.

    Returns:
        A BlurMatrixBase instance.
    """
    return BlurMatrixBase(values, mode=mode)

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

from_radius

from_radius(radius: int) -> BlurMatrixBase[float]

Generate a Gaussian blur kernel from an intuitive radius.

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

Parameters:

  • radius

    (int) –

    Blur radius.

Returns:

Source code in vsrgtools/enum.py
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
def from_radius(self: Literal[BlurMatrix.GAUSS], radius: int) -> BlurMatrixBase[float]:  # type: ignore[misc]
    """
    Generate a Gaussian blur kernel from an intuitive radius.

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

    Args:
        radius: Blur radius.

    Returns:
        Gaussian blur matrix.
    """
    assert self is BlurMatrix.GAUSS

    return BlurMatrix.GAUSS(None, sigma=self.get_sigma(radius))

get_radius

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/enum.py
424
425
426
427
428
429
430
431
432
433
434
435
436
def get_radius(self: Literal[BlurMatrix.GAUSS], sigma: float) -> int:  # type: ignore[misc]
    """
    Compute the radius required for a given sigma value.

    Args:
        sigma: Gaussian sigma value.

    Returns:
        Radius.
    """
    assert self is BlurMatrix.GAUSS

    return math.ceil(sigma * 6 + 1) // 2

get_sigma

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/enum.py
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
def get_sigma(self: Literal[BlurMatrix.GAUSS], radius: int) -> float:  # type: ignore[misc]
    """
    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
    """
    assert self is BlurMatrix.GAUSS

    return radius / 3

BlurMatrixBase

BlurMatrixBase(iterable: Iterable[Nb], /, mode: ConvMode = SQUARE)

Bases: list[Nb]

Represents a convolution kernel (matrix) for spatial or temporal filtering.

This class is typically constructed via the BlurMatrix enum, and encapsulates both the filter values and the intended convolution mode (e.g., horizontal, vertical, square, temporal).

When called, it applies the convolution to a clip using the appropriate method (std.Convolution, std.AverageFrames, or a custom ExprOp expression), depending on the kernel's properties and context.

Example
kernel = BlurMatrix.BINOMIAL(taps=2)
blurred = kernel(clip)

Parameters:

  • iterable

    (Iterable[Nb]) –

    Iterable of kernel coefficients.

  • mode

    (ConvMode, default: SQUARE ) –

    Convolution mode to use. Default is SQUARE.

Methods:

  • __call__

    Apply the blur kernel to the given clip via spatial or temporal convolution.

  • outer

    Convert a 1D kernel into a 2D square kernel by computing the outer product.

Attributes:

Source code in vsrgtools/enum.py
33
34
35
36
37
38
39
40
def __init__(self, iterable: Iterable[Nb], /, mode: ConvMode = ConvMode.SQUARE) -> None:
    """
    Args:
        iterable: Iterable of kernel coefficients.
        mode: Convolution mode to use. Default is SQUARE.
    """
    self.mode = mode
    super().__init__(iterable)

mode instance-attribute

mode = mode

__call__

__call__(
    clip: VideoNode | Iterable[VideoNode],
    planes: Planes = None,
    bias: float | None = None,
    divisor: float | None = None,
    saturate: bool = True,
    passes: int = 1,
    func: FuncExcept | None = None,
    expr_kwargs: dict[str, Any] | None = None,
    **kwargs: Any,
) -> VideoNode

Apply the blur kernel to the given clip via spatial or temporal convolution.

Chooses the appropriate backend (std.Convolution, std.AverageFrames, or ExprOp.convolution) depending on kernel size, mode, format, and other constraints.

Parameters:

  • clip

    (VideoNode | Iterable[VideoNode]) –

    Source clip.

  • planes

    (Planes, default: None ) –

    Planes to process. Defaults to all.

  • bias

    (float | None, default: None ) –

    Value added to result before clamping.

  • divisor

    (float | None, default: None ) –

    Divides the result of the convolution (before adding bias). Defaults to sum of kernel values.

  • saturate

    (bool, default: True ) –

    If True, negative values are clamped to zero. If False, absolute values are returned.

  • passes

    (int, default: 1 ) –

    Number of convolution passes to apply.

  • func

    (FuncExcept | None, default: None ) –

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

  • expr_kwargs

    (dict[str, Any] | None, default: None ) –

    Extra kwargs passed to ExprOp.convolution when used.

  • **kwargs

    (Any, default: {} ) –

    Any other args passed to the underlying VapourSynth function.

Returns:

  • VideoNode

    Processed (blurred) video clip.

Source code in vsrgtools/enum.py
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
def __call__(
    self,
    clip: vs.VideoNode | Iterable[vs.VideoNode],
    planes: Planes = None,
    bias: float | None = None,
    divisor: float | None = None,
    saturate: bool = True,
    passes: int = 1,
    func: FuncExcept | None = None,
    expr_kwargs: dict[str, Any] | None = None,
    **kwargs: Any,
) -> vs.VideoNode:
    """
    Apply the blur kernel to the given clip via spatial or temporal convolution.

    Chooses the appropriate backend (`std.Convolution`, `std.AverageFrames`, or `ExprOp.convolution`)
    depending on kernel size, mode, format, and other constraints.

    Args:
        clip: Source clip.
        planes: Planes to process. Defaults to all.
        bias: Value added to result before clamping.
        divisor: Divides the result of the convolution (before adding bias). Defaults to sum of kernel values.
        saturate: If True, negative values are clamped to zero. If False, absolute values are returned.
        passes: Number of convolution passes to apply.
        func: Function returned for custom error handling. This should only be set by VS package developers.
        expr_kwargs: Extra kwargs passed to ExprOp.convolution when used.
        **kwargs: Any other args passed to the underlying VapourSynth function.

    Returns:
        Processed (blurred) video clip.
    """
    func = func or self
    clip = to_arr(clip)
    expr_kwargs = expr_kwargs or {}

    if len(self) <= 1:
        return clip[0]

    process = self._spatial_conv if self.mode.is_spatial else self._temporal_conv
    return process(clip, planes, bias, divisor, saturate, passes, func, expr_kwargs, **kwargs)

outer

outer() -> Self

Convert a 1D kernel into a 2D square kernel by computing the outer product.

Returns:

  • Self

    New BlurMatrixBase instance with 2D kernel and same mode.

Source code in vsrgtools/enum.py
253
254
255
256
257
258
259
260
261
262
def outer(self) -> Self:
    """
    Convert a 1D kernel into a 2D square kernel by computing the outer product.

    Returns:
        New `BlurMatrixBase` instance with 2D kernel and same mode.
    """
    import numpy as np

    return self.__class__(list[Nb](np.outer(self, self).flatten()), self.mode)  # pyright: ignore[reportArgumentType]