Skip to content

vodesfunc.denoise

MVPresets

Source code in vodesfunc/denoise.py
class MVPresets:
    @classproperty
    def MaybeNotTerrible(self) -> MVToolsPreset:
        """
        This is just me throwing stuff at the wall to have some improvements without major slowdowns.
        """
        from vsdenoise import AnalyzeArgs, RecalculateArgs, SuperArgs, RFilterMode

        return MVToolsPreset(
            pel=1,
            search_clip=prefilter_to_full_range,
            super_args=SuperArgs(rfilter=RFilterMode.CUBIC),
            analyze_args=AnalyzeArgs(blksize=64, overlap_div=2, search=SearchMode.HEXAGON, pelsearch=2),
            recalculate_args=RecalculateArgs(blksize=32, overlap_div=2, search=SearchMode.HEXAGON, searchparam=1),
        )

    @classproperty
    def ActualOldWrapperMatch(self) -> MVToolsPreset:
        """
        Preset to match the old wrapper as well as possible.
        It is arguable if this is desirable.
        """
        from vsdenoise import AnalyzeArgs, RecalculateArgs, SuperArgs, RFilterMode

        return MVToolsPreset(
            pel=1,
            pad=16,
            search_clip=prefilter_to_full_range,
            super_args=SuperArgs(rfilter=RFilterMode.CUBIC),
            analyze_args=AnalyzeArgs(blksize=64, overlap_div=2, search=SearchMode.DIAMOND, pelsearch=2),
            recalculate_args=RecalculateArgs(blksize=32, overlap_div=2, search=SearchMode.DIAMOND, searchparam=0),
        )

MaybeNotTerrible

MaybeNotTerrible() -> MVToolsPreset

This is just me throwing stuff at the wall to have some improvements without major slowdowns.

Source code in vodesfunc/denoise.py
@classproperty
def MaybeNotTerrible(self) -> MVToolsPreset:
    """
    This is just me throwing stuff at the wall to have some improvements without major slowdowns.
    """
    from vsdenoise import AnalyzeArgs, RecalculateArgs, SuperArgs, RFilterMode

    return MVToolsPreset(
        pel=1,
        search_clip=prefilter_to_full_range,
        super_args=SuperArgs(rfilter=RFilterMode.CUBIC),
        analyze_args=AnalyzeArgs(blksize=64, overlap_div=2, search=SearchMode.HEXAGON, pelsearch=2),
        recalculate_args=RecalculateArgs(blksize=32, overlap_div=2, search=SearchMode.HEXAGON, searchparam=1),
    )

ActualOldWrapperMatch

ActualOldWrapperMatch() -> MVToolsPreset

Preset to match the old wrapper as well as possible. It is arguable if this is desirable.

Source code in vodesfunc/denoise.py
@classproperty
def ActualOldWrapperMatch(self) -> MVToolsPreset:
    """
    Preset to match the old wrapper as well as possible.
    It is arguable if this is desirable.
    """
    from vsdenoise import AnalyzeArgs, RecalculateArgs, SuperArgs, RFilterMode

    return MVToolsPreset(
        pel=1,
        pad=16,
        search_clip=prefilter_to_full_range,
        super_args=SuperArgs(rfilter=RFilterMode.CUBIC),
        analyze_args=AnalyzeArgs(blksize=64, overlap_div=2, search=SearchMode.DIAMOND, pelsearch=2),
        recalculate_args=RecalculateArgs(blksize=32, overlap_div=2, search=SearchMode.DIAMOND, searchparam=0),
    )

VMDegrain

VMDegrain(src: VideoNode, thSAD: int = 60, prefilter: VideoNode | Prefilter | int = 2, smooth: bool = True, block_size: int | None = None, refine: int = 2, tr: int = 2, preset: MVToolsPreset = MVPresets.MaybeNotTerrible, planes: Planes = 0, **kwargs: Any) -> tuple[vs.VideoNode, MVTools]

Just some convenience function for mvtools with a useable preset and temporal smoothing.

Check the MVTools Docs for the params that aren't listed below.

block_size, overlap and refine are using somewhat optimized defaults depending on the resolution if None.

Parameters:

Name Type Description Default
src VideoNode

Input to denoise

required
smooth bool

Run TTempsmooth on the denoised clip if True

True

Returns:

Type Description
tuple[VideoNode, MVTools]

Denoised clip

Source code in vodesfunc/denoise.py
def VMDegrain(
    src: vs.VideoNode,
    thSAD: int = 60,
    prefilter: vs.VideoNode | Prefilter | int = 2,
    smooth: bool = True,
    block_size: int | None = None,
    refine: int = 2,
    tr: int = 2,
    preset: MVToolsPreset = MVPresets.MaybeNotTerrible,
    planes: Planes = 0,
    **kwargs: Any,
) -> tuple[vs.VideoNode, MVTools]:
    """
    Just some convenience function for mvtools with a useable preset and temporal smoothing.\n
    Check the MVTools Docs for the params that aren't listed below.\n
    `block_size`, `overlap` and `refine` are using somewhat optimized defaults depending on the resolution if `None`.


    :param src:             Input to denoise
    :param smooth:          Run TTempsmooth on the denoised clip if True
    :return:                Denoised clip
    """
    if isinstance(prefilter, int):
        prefilter = Prefilter(prefilter)

    futil = FunctionUtil(src, VMDegrain, color_family=[vs.YUV, vs.GRAY], bitdepth=16)

    if not block_size:
        _, width, height = get_var_infos(src)
        if width <= 1024 and height <= 576:
            block_size = 32
        elif width <= 2048 and height <= 1536:
            block_size = 64
        else:
            block_size = 128

    from vsdenoise import mc_degrain

    # Dirty clean up for random args getting removed from on git.
    # (You should not be using git jetpack with vodesfunc but it is what it is)
    mc_degrain_sig = signature(mc_degrain)
    args = KwargsT(
        prefilter=prefilter,
        thsad=thSAD,
        thsad_recalc=thSAD,
        blksize=block_size,
        refine=refine,
        preset=preset,
        planes=planes,
        tr=tr,
    )
    args = args | kwargs

    clean_args = {k: v for k, v in args.items() if k in mc_degrain_sig.parameters}

    if len(args) != len(clean_args):
        args_string = ", ".join(list(k for k, _ in args.items() if k not in clean_args))
        print(f"VMDegrain: A couple of arguments are not passed to mc_degrain anymore! ({args_string})\nPlease do report this to the maintainer.")
    out, mv = mc_degrain(futil.work_clip, export_globals=True, **clean_args)

    if smooth:
        from vstools import sc_detect

        out = sc_detect(out, 0.12)  # zsmooth default, replacing misc.SCDetect
        out = core.zsmooth.TTempSmooth(out, maxr=1, thresh=1, mdiff=0, strength=1, scthresh=-1)

    return (futil.return_clip(out, src), mv)

schizo_denoise

schizo_denoise(src: VideoNode, sigma: float | Sequence[float] = [0.8, 0.3], thSAD: int = 60, radius: int | Sequence[int] = 2, nlm_a: int = 2, prefilter: VideoNode | Prefilter | int = 2, gpu: bool | Sequence[bool] = True, csharp: int | bool | Callable[[VideoNode, VideoNode, MVTools], VideoNode] = False, use_nlmeans: bool = True, **kwargs) -> vs.VideoNode

Convenience function for nlmeans (or bm3d) on chroma and mvtools + bm3d on luma. Mostly for personal scripts so please don't complain too much unless it's an actual issue.

Parameters:

Name Type Description Default
src VideoNode

Input to denoise

required
sigma float | Sequence[float]

Essentially strength for BM3D and NLMeans (or just BM3D, plane wise, if use_nlmeans=False).

Float or list of floats in this order [luma, chroma] or [y, u, v]

Do note that bm3dvk2 and vszip's BM3D do not necessarily have the same strength scaling.

[0.8, 0.3]
thSAD int

Not exactly strength but something like that, for mvtools.

60
radius int | Sequence[int]

Temporal Radius used for BM3D and NLMeans. Int or list of ints in this order [bm3d, nlm]

2
prefilter VideoNode | Prefilter | int

vsdenoise Prefilter or prefiltered clip to use for mvtools. Defaults to MINBLUR3

2
gpu bool | Sequence[bool]

Uses GPU plugins for BM3D and NLMeans respectively if available ([bm3d, nlm]).

BM3D uses bm3dvk2 (Vulkan) and falls back to vszip on CPU.

NLMeans prefers vszipcu over vszipcl and falls back to vszip on CPU.

True
csharp int | bool | Callable[[VideoNode, VideoNode, MVTools], VideoNode]

Apply contrasharpening after denoising.

True defaults to mc_clamp while False obviously disables it.

Integers are passed to the usual contrasharpening function.

The callable inputs are filtered, source and mvtools globals.

False
use_nlmeans bool

Use NLMeans for chroma denoising. If False, BM3D (with MVTools ref) is used for chroma as well.

True
kwargs

Any parameters you might wanna pass to bm3d or mvtools.

Note that this also takes tr or preset for mvtools which might be very useful.

{}

Returns:

Type Description
VideoNode

Denoised clip

Source code in vodesfunc/denoise.py
def schizo_denoise(
    src: vs.VideoNode,
    sigma: float | Sequence[float] = [0.8, 0.3],
    thSAD: int = 60,
    radius: int | Sequence[int] = 2,
    nlm_a: int = 2,
    prefilter: vs.VideoNode | Prefilter | int = 2,
    gpu: bool | Sequence[bool] = True,
    csharp: int | bool | Callable[[vs.VideoNode, vs.VideoNode, MVTools], vs.VideoNode] = False,
    use_nlmeans: bool = True,
    **kwargs,
) -> vs.VideoNode:
    """
    Convenience function for nlmeans (or bm3d) on chroma and mvtools + bm3d on luma.
    Mostly for personal scripts so please don't complain too much unless it's an actual issue.

    :param src:         Input to denoise
    :param sigma:       Essentially strength for BM3D and NLMeans (or just BM3D, plane wise, if use_nlmeans=False).\n
                        Float or list of floats in this order [luma, chroma] or [y, u, v]\n
                        Do note that `bm3dvk2` and vszip's BM3D do not necessarily have the same strength scaling.
    :param thSAD:       Not exactly strength but something like that, for mvtools.
    :param radius:      Temporal Radius used for BM3D and NLMeans.
                        Int or list of ints in this order [bm3d, nlm]
    :param prefilter:   vsdenoise Prefilter or prefiltered clip to use for mvtools.
                        Defaults to MINBLUR3
    :param gpu:         Uses GPU plugins for BM3D and NLMeans respectively if available (`[bm3d, nlm]`).\n
                        BM3D uses `bm3dvk2` (Vulkan) and falls back to `vszip` on CPU.\n
                        NLMeans prefers `vszipcu` over `vszipcl` and falls back to `vszip` on CPU.
    :param csharp:      Apply contrasharpening after denoising.\n
                        True defaults to [mc_clamp](https://jaded-encoding-thaumaturgy.github.io/vs-jetpack/api/vsdenoise/funcs#vsdenoise.funcs.mc_clamp) while False obviously disables it.\n
                        Integers are passed to the usual [contrasharpening](https://jaded-encoding-thaumaturgy.github.io/vs-jetpack/api/vsrgtools/contra#vsrgtools.contra.contrasharpening) function.\n
                        The callable inputs are filtered, source and mvtools globals.
    :param use_nlmeans: Use NLMeans for chroma denoising. If False, BM3D (with MVTools ref) is used for chroma as well.
    :param kwargs:      Any parameters you might wanna pass to bm3d or mvtools.\n
                        Note that this also takes `tr` or `preset` for mvtools which might be very useful.

    :return:            Denoised clip
    """
    if get_video_format(src).color_family != vs.YUV:
        raise ValueError("schizo_denoise: This function expects a full YUV clip.")

    radius = normalize_seq(radius, 2)
    sigma = normalize_seq(sigma, 3)
    gpu = normalize_seq(gpu, 2)

    if isinstance(prefilter, int):
        prefilter = Prefilter(prefilter)

    clip = depth(src, 16) if get_depth(src) < 16 else src

    nlm: vs.VideoNode | None = None
    if use_nlmeans:
        nlmargs: dict[str, Any] = dict(a=nlm_a, d=radius[1], channels="UV")
        if gpu[1] and (hasattr(core, "vszipcu") or hasattr(core, "vszipcl")):
            nlmfunc = core.vszipcu.NLMeans if hasattr(core, "vszipcu") else core.vszipcl.NLMeans
            nlmargs["num_streams"] = 2
        else:
            nlmfunc = core.vszip.NLMeans

        if sigma[1] == sigma[2]:
            nlm = nlmfunc(clip, h=sigma[1], **nlmargs) if sigma[1] > 0 else clip
        else:
            nlm = join(
                get_y(clip),
                get_u(nlmfunc(clip, h=sigma[1], **nlmargs) if sigma[1] > 0 else clip),
                get_v(nlmfunc(clip, h=sigma[2], **nlmargs) if sigma[2] > 0 else clip),
            )

    # 'Extract' possible bm3d args before passing kwargs to mvtools :)
    bm3dargs: dict[str, Any] = dict(
        radius=radius[0],
        block_step=kwargs.pop("block_step", 8),
        bm_range=kwargs.pop("bm_range", 9),
        ps_num=kwargs.pop("ps_num", 2),
        ps_range=kwargs.pop("ps_range", 4),
    )
    matrix = kwargs.pop("matrix", 0)

    mv, mv_globals = VMDegrain(clip, thSAD, prefilter, planes=0 if use_nlmeans else None, **kwargs)
    mv = depth(get_y(mv) if use_nlmeans else mv, 32)
    out = depth(get_y(clip) if use_nlmeans else clip, 32)

    if gpu[0] and hasattr(core, "bm3dvk2"):
        bm3dargs["matrix"] = matrix
        out = out.std.GPUUpload()
        mv = mv.std.GPUUpload()
        if use_nlmeans:
            out = core.bm3dvk2.BM3D(out, ref=mv, sigma=sigma[0], **bm3dargs)
        else:
            # bm3dvk2 doesn't support the chroma=False path of the other plugins
            # but I did like the results from per-plane bm3d over nlm in most cases (and it's still faster than vszipcu)
            out = join(
                [core.bm3dvk2.BM3D(clip, ref=ref, sigma=s, **bm3dargs) if s > 0 else clip for clip, ref, s in zip(split(out), split(mv), sigma)],
                clip.format.color_family,
            )
        out = out.std.GPUDownload()
    else:
        out = core.vszip.BM3D(out, ref=mv, sigma=sigma[0] if use_nlmeans else sigma, **bm3dargs)

    if nlm is not None:
        out = join(depth(out, nlm), nlm)
    out = depth(out, src)

    if callable(csharp):
        out = csharp(out, src, mv_globals)
    elif csharp is True:
        out = mc_clamp(out, src, mv_globals, tr=kwargs.get("tr", 2))
    elif csharp:
        out = contrasharpening(out, src, mode=csharp)

    return out.std.CopyFrameProps(src)