vs-colorfix 2.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. vs_colorfix/__init__.py +2 -0
  2. vs_colorfix/average_color_fix.py +146 -0
  3. vs_colorfix/models/waveletcolorfix_w10_c1_fp16.onnx +0 -0
  4. vs_colorfix/models/waveletcolorfix_w10_c1_fp32.onnx +0 -0
  5. vs_colorfix/models/waveletcolorfix_w10_c3_fp16.onnx +0 -0
  6. vs_colorfix/models/waveletcolorfix_w10_c3_fp32.onnx +0 -0
  7. vs_colorfix/models/waveletcolorfix_w1_c1_fp16.onnx +0 -0
  8. vs_colorfix/models/waveletcolorfix_w1_c1_fp32.onnx +0 -0
  9. vs_colorfix/models/waveletcolorfix_w1_c3_fp16.onnx +0 -0
  10. vs_colorfix/models/waveletcolorfix_w1_c3_fp32.onnx +0 -0
  11. vs_colorfix/models/waveletcolorfix_w2_c1_fp16.onnx +0 -0
  12. vs_colorfix/models/waveletcolorfix_w2_c1_fp32.onnx +0 -0
  13. vs_colorfix/models/waveletcolorfix_w2_c3_fp16.onnx +0 -0
  14. vs_colorfix/models/waveletcolorfix_w2_c3_fp32.onnx +0 -0
  15. vs_colorfix/models/waveletcolorfix_w3_c1_fp16.onnx +0 -0
  16. vs_colorfix/models/waveletcolorfix_w3_c1_fp32.onnx +0 -0
  17. vs_colorfix/models/waveletcolorfix_w3_c3_fp16.onnx +0 -0
  18. vs_colorfix/models/waveletcolorfix_w3_c3_fp32.onnx +0 -0
  19. vs_colorfix/models/waveletcolorfix_w4_c1_fp16.onnx +0 -0
  20. vs_colorfix/models/waveletcolorfix_w4_c1_fp32.onnx +0 -0
  21. vs_colorfix/models/waveletcolorfix_w4_c3_fp16.onnx +0 -0
  22. vs_colorfix/models/waveletcolorfix_w4_c3_fp32.onnx +0 -0
  23. vs_colorfix/models/waveletcolorfix_w5_c1_fp16.onnx +0 -0
  24. vs_colorfix/models/waveletcolorfix_w5_c1_fp32.onnx +0 -0
  25. vs_colorfix/models/waveletcolorfix_w5_c3_fp16.onnx +0 -0
  26. vs_colorfix/models/waveletcolorfix_w5_c3_fp32.onnx +0 -0
  27. vs_colorfix/models/waveletcolorfix_w6_c1_fp16.onnx +0 -0
  28. vs_colorfix/models/waveletcolorfix_w6_c1_fp32.onnx +0 -0
  29. vs_colorfix/models/waveletcolorfix_w6_c3_fp16.onnx +0 -0
  30. vs_colorfix/models/waveletcolorfix_w6_c3_fp32.onnx +0 -0
  31. vs_colorfix/models/waveletcolorfix_w7_c1_fp16.onnx +0 -0
  32. vs_colorfix/models/waveletcolorfix_w7_c1_fp32.onnx +0 -0
  33. vs_colorfix/models/waveletcolorfix_w7_c3_fp16.onnx +0 -0
  34. vs_colorfix/models/waveletcolorfix_w7_c3_fp32.onnx +0 -0
  35. vs_colorfix/models/waveletcolorfix_w8_c1_fp16.onnx +0 -0
  36. vs_colorfix/models/waveletcolorfix_w8_c1_fp32.onnx +0 -0
  37. vs_colorfix/models/waveletcolorfix_w8_c3_fp16.onnx +0 -0
  38. vs_colorfix/models/waveletcolorfix_w8_c3_fp32.onnx +0 -0
  39. vs_colorfix/models/waveletcolorfix_w9_c1_fp16.onnx +0 -0
  40. vs_colorfix/models/waveletcolorfix_w9_c1_fp32.onnx +0 -0
  41. vs_colorfix/models/waveletcolorfix_w9_c3_fp16.onnx +0 -0
  42. vs_colorfix/models/waveletcolorfix_w9_c3_fp32.onnx +0 -0
  43. vs_colorfix/wavelet_color_fix.py +466 -0
  44. vs_colorfix-2.1.0.dist-info/METADATA +217 -0
  45. vs_colorfix-2.1.0.dist-info/RECORD +47 -0
  46. vs_colorfix-2.1.0.dist-info/WHEEL +4 -0
  47. vs_colorfix-2.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,2 @@
1
+ from .wavelet_color_fix import wavelet_color_fix as wavelet
2
+ from .average_color_fix import average_color_fix as average
@@ -0,0 +1,146 @@
1
+
2
+ # Script by pifroggi https://github.com/pifroggi/vs_colorfix
3
+ # or tepete and pifroggi on Discord
4
+
5
+ # Average Color Fix idea from chaiNNer https://github.com/chaiNNer-org/chaiNNer
6
+
7
+ import vapoursynth as vs
8
+ import warnings
9
+
10
+ core = vs.core
11
+
12
+
13
+ def _expression(clips, expr, format=None):
14
+ # optional plugin for slight speed boost
15
+ if hasattr(core, "akarin"):
16
+ return core.akarin.Expr(clips, expr, format=format)
17
+ else:
18
+ return core.std.Expr(clips, expr, format=format)
19
+
20
+
21
+ def _box_blur(clip, planes=None, hradius=1, hpasses=1, vradius=1, vpasses=1):
22
+ # optional plugin for slight speed boost
23
+ if hasattr(core, "vszip"):
24
+ return core.vszip.BoxBlur(clip, planes=planes, hradius=hradius, hpasses=hpasses, vradius=vradius, vpasses=vpasses)
25
+ else:
26
+ return core.std.BoxBlur(clip, planes=planes, hradius=hradius, hpasses=hpasses, vradius=vradius, vpasses=vpasses)
27
+
28
+
29
+ def _make_diff(clipa, clipb, planes=None):
30
+ # makes makediff work on 16-bit float
31
+ if clipa.format.sample_type == vs.FLOAT and clipa.format.bits_per_sample == 16 and vs.__version__.release_major < 78:
32
+ return _expression([clipa, clipb], expr=["x y -" if i in planes else "" for i in range(clipa.format.num_planes)])
33
+ else:
34
+ return core.std.MakeDiff(clipa, clipb, planes=planes)
35
+
36
+
37
+ def _merge_diff(clipa, clipb, planes=None):
38
+ # makes mergediff work on 16-bit float
39
+ if clipa.format.sample_type == vs.FLOAT and clipa.format.bits_per_sample == 16 and vs.__version__.release_major < 78:
40
+ return _expression([clipa, clipb], expr=["x y +" if i in planes else "" for i in range(clipa.format.num_planes)])
41
+ else:
42
+ return core.std.MergeDiff(clipa, clipb, planes=planes)
43
+
44
+
45
+ def average_color_fix(clip, ref, radius=10, planes=None, fast=False):
46
+ """Fixes color shift based on a reference clip. A very fast way to transfer the colors from one clip to another. For large color differences, `wavelet()` is more accurate.
47
+
48
+ Args:
49
+ clip: Clip where the color fix will be applied to.
50
+ ref: Reference clip where the colors are taken from. Should match the base clip somewhat. Compression, grain, or lower resolution are all okay.
51
+ radius: Higher means a more global color match and wider bloom/bleed. Lower means a more local color match and smaller bloom/bleed.
52
+ Too low and the reference clip will become visible. Test values 5 and 30 and this will become more clear.
53
+ planes: Which planes to color fix. Any unmentioned planes will simply be copied. None means all planes will be color fixed.
54
+ fast: Does the averaging via a downscale instead of a blur, which is much faster, but will produce faint blocky artifacts.
55
+ I found it useful for radius > 60 where artifacts are often no longer noticable, or to fix something like a prefilter clip.
56
+ """
57
+
58
+ if not isinstance(clip, vs.VideoNode):
59
+ raise TypeError("vs_colorfix.average: Clip must be a vapoursynth clip.")
60
+ if not isinstance(ref, vs.VideoNode):
61
+ raise TypeError("vs_colorfix.average: Ref must be a vapoursynth clip.")
62
+ if clip.format.id == vs.PresetVideoFormat.NONE or clip.width == 0 or clip.height == 0:
63
+ raise TypeError("vs_colorfix.average: Clip must have constant format and dimensions.")
64
+ if ref.format.id == vs.PresetVideoFormat.NONE or ref.width == 0 or ref.height == 0:
65
+ raise TypeError("vs_colorfix.average: Ref must have constant format and dimensions.")
66
+ if clip.format.sample_type == vs.FLOAT and clip.format.bits_per_sample == 16 and vs.__version__.release_major < 78 and not hasattr(core, "vszip"):
67
+ raise ValueError("vs_colorfix.average: 16-bit float formats require vapoursynth version 78 or newer, or the plugin 'vszip' version 15.0.0 or newer.")
68
+ if clip.format.id != ref.format.id:
69
+ raise ValueError("vs_colorfix.average: Clip and ref must have the same format. 16-bit input is recommended to avoid banding.")
70
+ if not isinstance(fast, bool):
71
+ raise TypeError("vs_colorfix.average: Fast must be either True or False.")
72
+ if not isinstance(radius, int) or isinstance(radius, bool):
73
+ raise TypeError("vs_colorfix.average: Radius must be an integer.")
74
+ if not fast and not (1 <= radius <= 10000):
75
+ raise ValueError("vs_colorfix.average: Radius must be in the range 1-10000.")
76
+ fast_max_radius = (min(clip.width, clip.height) - 1) // 2
77
+ if fast and not (1 <= radius <= fast_max_radius):
78
+ raise ValueError(f"vs_colorfix.average: Radius must be between 1 and {fast_max_radius} for the current input dimensions when fast=True.")
79
+ if clip.format.bits_per_sample <= 8 or ref.format.bits_per_sample <= 8:
80
+ warnings.warn("vs_colorfix.average: Input clips have a low bit depth, which will cause banding. 16-bit input is recommended.", UserWarning, stacklevel=2)
81
+
82
+ num_planes = clip.format.num_planes
83
+ if planes is None:
84
+ planes = list(range(num_planes))
85
+ if isinstance(planes, int):
86
+ planes = [planes]
87
+ if num_planes == 1:
88
+ planes = [0]
89
+ planes = set(planes)
90
+ if not planes <= set(range(num_planes)):
91
+ raise ValueError("vs_colorfix.average: Invalid plane index specified.")
92
+
93
+ # downscale both clips, calculate difference (faster but faint blocky artifacts)
94
+ if fast:
95
+ radius = radius * 2 + 1
96
+ processed_clips = [None] * num_planes
97
+ if 0 in planes:
98
+ clip_plane = core.std.ShufflePlanes(clip, planes=0, colorfamily=vs.GRAY)
99
+ ref_plane = core.std.ShufflePlanes(ref, planes=0, colorfamily=vs.GRAY)
100
+ downscaled_clip_plane = core.resize.Bilinear(clip_plane, width=clip.width // radius, height=clip.height // radius)
101
+ downscaled_ref_plane = core.resize.Bilinear(ref_plane, width=clip.width // radius, height=clip.height // radius)
102
+ diff_plane = _make_diff(downscaled_ref_plane, downscaled_clip_plane, planes=[0])
103
+ processed_clips[0] = core.resize.Bilinear(diff_plane, width=clip.width, height=clip.height)
104
+ else:
105
+ processed_clips[0] = core.std.ShufflePlanes(clip, planes=0, colorfamily=vs.GRAY)
106
+ if 1 in planes:
107
+ clip_plane = core.std.ShufflePlanes(clip, planes=1, colorfamily=vs.GRAY)
108
+ ref_plane = core.std.ShufflePlanes(ref, planes=1, colorfamily=vs.GRAY)
109
+ downscaled_clip_plane = core.resize.Bilinear(clip_plane, width=clip.width // radius, height=clip.height // radius)
110
+ downscaled_ref_plane = core.resize.Bilinear(ref_plane, width=clip.width // radius, height=clip.height // radius)
111
+ diff_plane = _make_diff(downscaled_ref_plane, downscaled_clip_plane, planes=[0])
112
+ processed_clips[1] = core.resize.Bilinear(diff_plane, width=clip_plane.width, height=clip_plane.height)
113
+ elif num_planes > 1:
114
+ processed_clips[1] = core.std.ShufflePlanes(clip, planes=1, colorfamily=vs.GRAY)
115
+ if 2 in planes:
116
+ clip_plane = core.std.ShufflePlanes(clip, planes=2, colorfamily=vs.GRAY)
117
+ ref_plane = core.std.ShufflePlanes(ref, planes=2, colorfamily=vs.GRAY)
118
+ downscaled_clip_plane = core.resize.Bilinear(clip_plane, width=clip.width // radius, height=clip.height // radius)
119
+ downscaled_ref_plane = core.resize.Bilinear(ref_plane, width=clip.width // radius, height=clip.height // radius)
120
+ diff_plane = _make_diff(downscaled_ref_plane, downscaled_clip_plane, planes=[0])
121
+ processed_clips[2] = core.resize.Bilinear(diff_plane, width=clip_plane.width, height=clip_plane.height)
122
+ elif num_planes > 2:
123
+ processed_clips[2] = core.std.ShufflePlanes(clip, planes=2, colorfamily=vs.GRAY)
124
+ diff_clip = core.std.ShufflePlanes(clips=processed_clips, planes=[0] * num_planes, colorfamily=clip.format.color_family)
125
+
126
+ # blur both clips, calculate difference (better quality but slower)
127
+ else:
128
+ if ref.width != clip.width or ref.height != clip.height:
129
+ ref = core.resize.Bilinear(ref, width=clip.width, height=clip.height)
130
+ chroma_hradius = radius // (1 << clip.format.subsampling_w) if clip.format.subsampling_w else radius
131
+ chroma_vradius = radius // (1 << clip.format.subsampling_h) if clip.format.subsampling_h else radius
132
+ blurred_clip = clip
133
+ blurred_ref = ref
134
+ if 0 in planes:
135
+ blurred_clip = _box_blur(blurred_clip, hradius=radius, hpasses=4, vradius=radius, vpasses=4, planes=[0])
136
+ blurred_ref = _box_blur(blurred_ref, hradius=radius, hpasses=4, vradius=radius, vpasses=4, planes=[0])
137
+ if 1 in planes:
138
+ blurred_clip = _box_blur(blurred_clip, hradius=chroma_hradius, hpasses=4, vradius=chroma_vradius, vpasses=4, planes=[1])
139
+ blurred_ref = _box_blur(blurred_ref, hradius=chroma_hradius, hpasses=4, vradius=chroma_vradius, vpasses=4, planes=[1])
140
+ if 2 in planes:
141
+ blurred_clip = _box_blur(blurred_clip, hradius=chroma_hradius, hpasses=4, vradius=chroma_vradius, vpasses=4, planes=[2])
142
+ blurred_ref = _box_blur(blurred_ref, hradius=chroma_hradius, hpasses=4, vradius=chroma_vradius, vpasses=4, planes=[2])
143
+ diff_clip = _make_diff(blurred_ref, blurred_clip, planes=planes)
144
+
145
+ # add difference to the original
146
+ return _merge_diff(clip, diff_clip, planes=planes)
@@ -0,0 +1,466 @@
1
+
2
+ # Script by pifroggi https://github.com/pifroggi/vs_colorfix
3
+ # or tepete and pifroggi on Discord
4
+
5
+ # Wavelet Color Fix idea from sd-webui-stablesr https://github.com/pkuliyi2015/sd-webui-stablesr/blob/master/srmodule/colorfix.py
6
+
7
+ import os
8
+ import re
9
+ import sys
10
+ import shutil
11
+ import logging
12
+ import warnings
13
+ import subprocess
14
+ import vapoursynth as vs
15
+ from pathlib import Path
16
+ from .average_color_fix import _expression
17
+
18
+ core = vs.core
19
+
20
+
21
+ def _plane_wavelets(clip_format, wavelets):
22
+ # compensate wavelet count for subsampled planes
23
+ plane_wavelets = [wavelets] * clip_format.num_planes
24
+
25
+ if clip_format.color_family == vs.YUV and clip_format.num_planes > 1:
26
+ subsampling_shift = max(clip_format.subsampling_w, clip_format.subsampling_h)
27
+ if subsampling_shift > 0:
28
+ chroma_wavelets = max(1, wavelets - subsampling_shift)
29
+ for p in range(1, clip_format.num_planes):
30
+ plane_wavelets[p] = chroma_wavelets
31
+
32
+ return plane_wavelets
33
+
34
+
35
+ def _inference_groups(clips, planes, plane_wavelets):
36
+ # group planes by wavelet count and size so interleaved inference only combines compatible planes
37
+ groups = {}
38
+ for p in sorted(planes):
39
+ plane_clip = clips[p]
40
+ key = (plane_wavelets[p], plane_clip.width, plane_clip.height)
41
+ if key not in groups:
42
+ groups[key] = []
43
+ groups[key].append(p)
44
+
45
+ return [(key[0], grouped_planes) for key, grouped_planes in groups.items()]
46
+
47
+
48
+ def _get_builder(plugin_path, trt_version, cuda_major):
49
+ # finds compatible tensorrt engine builders
50
+ exe_name = "trtexec.exe" if os.name == "nt" else "trtexec"
51
+ builders = []
52
+ errors = []
53
+
54
+ # check for python tensorrt
55
+ try:
56
+ import tensorrt
57
+ package_version = list(map(int, tensorrt.__version__.split(".")[:3]))
58
+ if package_version == trt_version:
59
+ builders.append(["python", tensorrt])
60
+ else:
61
+ errors.append(f"Python TensorRT: Wrong version {'.'.join(map(str, package_version))}")
62
+ except ImportError:
63
+ errors.append("Python TensorRT: Not found.")
64
+ except Exception:
65
+ errors.append("Python TensorRT: Found but failed to check version.")
66
+
67
+ # check for bundled trtexec
68
+ bundled_trtexec = Path(plugin_path) / "vsmlrt-cuda" / exe_name
69
+ if bundled_trtexec.is_file() and os.access(str(bundled_trtexec), os.X_OK):
70
+ builders.append(["trtexec", bundled_trtexec])
71
+ else:
72
+ errors.append(f"Bundled trtexec: Not found.")
73
+
74
+ # check for system trtexec
75
+ system_trtexec = shutil.which("trtexec")
76
+ if system_trtexec is not None:
77
+ try:
78
+ trtexec_path = Path(system_trtexec)
79
+ help_output = subprocess.run([str(trtexec_path), "--help"], check=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="locale", errors="replace")
80
+ help_output = f"{help_output.stdout}\n{help_output.stderr}"
81
+
82
+ trtexec_version = None
83
+ trtexec_version = re.search(r"\[TensorRT v(\d+)\]", help_output)
84
+ if trtexec_version is None:
85
+ raise RuntimeError("vs_colorfix.wavelet: Internal Error: Regex failed to find the version.")
86
+
87
+ trtexec_version = int(trtexec_version.group(1))
88
+ trtexec_version = [trtexec_version // 10000, (trtexec_version % 10000) // 100, trtexec_version % 100]
89
+ if trtexec_version == trt_version:
90
+ builders.append(["trtexec", trtexec_path])
91
+ else:
92
+ errors.append(f"System trtexec: Wrong version {'.'.join(map(str, trtexec_version))}")
93
+ except Exception:
94
+ errors.append("System trtexec: Found but failed to check version.")
95
+ else:
96
+ errors.append("System trtexec: Not found.")
97
+
98
+ # return first compatible builder
99
+ if builders:
100
+ return builders[0]
101
+
102
+ errors = "\n".join(f"{builder}" for builder in errors)
103
+ raise FileNotFoundError(f"vs_colorfix.wavelet: No compatible TensorRT engine builder found. Please install the python packages 'tensorrt', or install trtexec. The required TensorRT version is {'.'.join(map(str, trt_version))}. The required CUDA version is {cuda_major}.\n{errors}")
104
+
105
+
106
+ def _build_engine_trtexec(onnx_path, engine_path, engine_w, engine_h, num_planes, gpu_id, precision, trt_version, trtexec_path):
107
+ # build engine using trtexec, supports trt 10 and 11
108
+
109
+ # settings
110
+ opt_shapes = f"input:1x{num_planes*2}x{engine_h}x{engine_w}"
111
+ io_formats = f"fp{precision}:chw" if trt_version[0] < 11 else "chw"
112
+ cmd = [
113
+ str(trtexec_path),
114
+ *(["--stronglyTyped"] if trt_version[0] < 11 else []),
115
+ "--skipInference",
116
+ "--memPoolSize=workspace:4096",
117
+ "--builderOptimizationLevel=5",
118
+ "--tilingOptimizationLevel=3",
119
+ f"--inputIOFormats={io_formats}",
120
+ f"--outputIOFormats={io_formats}",
121
+ f"--onnx={onnx_path}",
122
+ f"--saveEngine={engine_path}",
123
+ f"--optShapes={opt_shapes}",
124
+ f"--device={gpu_id}",
125
+ ]
126
+
127
+ # build
128
+ try:
129
+ result = subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="locale", errors="replace")
130
+ except subprocess.CalledProcessError as e:
131
+ msg = (
132
+ "vs_colorfix.wavelet: Internal Error: trtexec failed while building the TensorRT engine.\n"
133
+ f" Command: {' '.join(cmd)}\n"
134
+ f" Return code: {e.returncode}\n"
135
+ )
136
+ if e.stdout:
137
+ msg += f"\n=== trtexec stdout ===\n{e.stdout}"
138
+ if e.stderr:
139
+ msg += f"\n=== trtexec stderr ===\n{e.stderr}"
140
+ raise RuntimeError(msg) from e
141
+
142
+
143
+ def _build_engine_python(onnx_path, engine_path, engine_w, engine_h, num_planes, gpu_id, trt_package):
144
+ # build engine using tensorrt python package, supports only trt 11 because of vapoursynth-mlrt-trt
145
+ from cuda.core import Device
146
+ trt = trt_package
147
+
148
+ # custom logger for errors
149
+ class _TrtLogger(trt.ILogger):
150
+ def __init__(self):
151
+ trt.ILogger.__init__(self)
152
+ self.messages = []
153
+ self.fatal = False
154
+ def log(self, severity, msg):
155
+ if severity <= trt.Logger.WARNING:
156
+ self.messages.append((severity, msg))
157
+ if self.fatal:
158
+ logging.critical(f" [{severity}] {msg}")
159
+ elif severity == trt.Logger.INTERNAL_ERROR: # print fatal errors immediately because python may not get control back
160
+ self.fatal = True
161
+ log = "\n".join(f" [{log_severity}] {log_msg}" for log_severity, log_msg in self.messages)
162
+ logging.critical(f"vs_colorfix.wavelet: Internal Error: TensorRT failed while building the TensorRT engine.\n=== TensorRT log ===\n{log}")
163
+ def get_log(self):
164
+ return "\n".join(f" [{severity}] {msg}" for severity, msg in self.messages)
165
+
166
+ # initialize trt and load model
167
+ cur_id = Device().device_id
168
+ try:
169
+ Device(gpu_id).set_current()
170
+ logger = _TrtLogger()
171
+ builder = trt.Builder(logger)
172
+ network = builder.create_network()
173
+ config = builder.create_builder_config()
174
+ parser = trt.OnnxParser(network, logger)
175
+ if not parser.parse_from_file(str(onnx_path)):
176
+ errors = "\n".join(f" {parser.get_error(i)}" for i in range(parser.num_errors))
177
+ raise RuntimeError(f"vs_colorfix.wavelet: Internal Error: TensorRT failed while parsing the ONNX model.\n{errors}")
178
+
179
+ # settings
180
+ opt_shapes = (1, num_planes * 2, engine_h, engine_w) # optShapes
181
+ network.get_input(0).allowed_formats = network.get_output(0).allowed_formats = 1 << int(trt.TensorFormat.LINEAR) # IOFormats:chw
182
+ config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, 4096 << 20) # workspace
183
+ config.builder_optimization_level = 5 # builderOptimizationLevel=5
184
+ config.tiling_optimization_level = trt.TilingOptimizationLevel.FULL # tilingOptimizationLevel=3
185
+
186
+ # build
187
+ profile = builder.create_optimization_profile()
188
+ profile.set_shape(network.get_input(0).name, opt_shapes, opt_shapes, opt_shapes)
189
+ config.add_optimization_profile(profile)
190
+ engine = builder.build_serialized_network(network, config)
191
+ finally:
192
+ Device(cur_id).set_current()
193
+
194
+ if engine is None:
195
+ log = logger.get_log()
196
+ msg = "vs_colorfix.wavelet: Internal Error: TensorRT failed while building the TensorRT engine."
197
+ if log:
198
+ msg += f"\n=== TensorRT log ===\n{log}"
199
+ raise RuntimeError(msg)
200
+
201
+ # save engine
202
+ with open(engine_path, "wb") as f:
203
+ f.write(engine)
204
+
205
+
206
+ def _get_engine(onnx_path, engine_dir, engine_w, engine_h, num_planes, precision, gpu_id=0, force_rebuild=False) -> str:
207
+ # get path to tensorrt engine
208
+ os.makedirs(engine_dir, exist_ok=True) # create engine folder if needed
209
+ model_name = Path(onnx_path).stem
210
+ engine_name = f"{model_name}_h{engine_h}_w{engine_w}_gpu{gpu_id}.engine"
211
+ engine_path = os.path.join(engine_dir, engine_name)
212
+
213
+ # check plugin version
214
+ try:
215
+ info = core.trt.Version()
216
+ except Exception as e:
217
+ raise RuntimeError("vs_colorfix.wavelet: TensorRT backend not installed. Please install the TensorRT dependencies with:\n'pip install -U vs_colorfix[tensorrt] --extra-index-url https://pypi.nvidia.com/'\nOr choose a different backend.") from e
218
+
219
+ # if engine file exist, return it
220
+ if not force_rebuild and os.path.isfile(engine_path) and os.path.getsize(engine_path) >= 512:
221
+ return engine_path
222
+
223
+ # get plugin info
224
+ plugin_path = os.path.dirname(info["path"].decode(errors="ignore"))
225
+ trt_version = int(info["tensorrt_version"].decode(errors="ignore"))
226
+ trt_version = [trt_version // 10000, (trt_version % 10000) // 100, trt_version % 100]
227
+ cuda_major = int(info["cuda_runtime_version"].decode(errors="ignore")) // 1000
228
+
229
+ # build new engine
230
+ logging.warning("vs_colorfix.wavelet: Building new TensorRT engine for width=%d, height=%d and precision=fp%d. This may take a few minutes.", engine_w, engine_h, precision)
231
+ builder_info = _get_builder(plugin_path=plugin_path, trt_version=trt_version, cuda_major=cuda_major)
232
+ if builder_info[0] == "python":
233
+ _build_engine_python(onnx_path=onnx_path, engine_path=engine_path, engine_w=engine_w, engine_h=engine_h, num_planes=num_planes, gpu_id=gpu_id, trt_package=builder_info[1])
234
+ elif builder_info[0] == "trtexec":
235
+ _build_engine_trtexec(onnx_path=onnx_path, engine_path=engine_path, engine_w=engine_w, engine_h=engine_h, num_planes=num_planes, gpu_id=gpu_id, precision=precision, trt_version=trt_version, trtexec_path=builder_info[1])
236
+ else:
237
+ raise RuntimeError(f"vs_colorfix.wavelet: Internal Error: Unknown TensorRT engine builder: {builder_info[0]}")
238
+ logging.warning("vs_colorfix.wavelet: Engine building complete.")
239
+ return engine_path
240
+
241
+
242
+ def _tensorrt_inference(input_clips, onnx_path, engine_dir, clip_w, clip_h, num_planes, precision, num_streams=1, gpu_id=0, force_rebuild=False):
243
+ engine_path = _get_engine(onnx_path=onnx_path, engine_dir=engine_dir, engine_w=clip_w, engine_h=clip_h, num_planes=num_planes, precision=precision, gpu_id=gpu_id, force_rebuild=force_rebuild)
244
+ model_args = dict(engine_path=engine_path, num_streams=num_streams, device_id=gpu_id)
245
+
246
+ # try inference, rebuild engine if it fails
247
+ try:
248
+ out = core.trt.Model(input_clips, **model_args)
249
+ except vs.Error as e:
250
+ err_msg = str(e).lower()
251
+ serialization_keywords = ("serialize", "serialization", "deserialize", "deserialization")
252
+ if any(k in err_msg for k in serialization_keywords) and not force_rebuild:
253
+ logging.warning("vs_colorfix.wavelet: Engine loading failed. This may be due to a TensorRT or driver update. Rebuilding...")
254
+ model_args["engine_path"] = _get_engine(onnx_path=onnx_path, engine_dir=engine_dir, engine_w=clip_w, engine_h=clip_h, num_planes=num_planes, precision=precision, gpu_id=gpu_id, force_rebuild=True)
255
+ out = core.trt.Model(input_clips, **model_args)
256
+ else:
257
+ raise
258
+ return out
259
+
260
+
261
+ def _vsmlrt_inference(clips, refs, wavelets, backend="ncnn", num_streams=1, gpu_id=0, engine_folder=None):
262
+ # choose model and vsmlrt backend, then inference
263
+
264
+ base_clip = clips[0]
265
+ clip_w = base_clip.width
266
+ clip_h = base_clip.height
267
+ num_planes = base_clip.format.num_planes
268
+ precision = 32 if backend in ["ncnn"] else base_clip.format.bits_per_sample # ncnn backend needs fp32 onnx, will be converted to fp16 internally
269
+ force_rebuild = False
270
+ current_dir = os.path.dirname(os.path.abspath(__file__))
271
+ model_file = f"waveletcolorfix_w{wavelets}_c{num_planes}_fp{precision}.onnx"
272
+ onnx_path = os.path.join(current_dir, "models", model_file)
273
+ engine_dir = os.path.join(current_dir, "engines") if engine_folder is None else os.path.abspath(engine_folder)
274
+
275
+ # interleave all input clips
276
+ input_clips = [core.std.Interleave(clips), core.std.Interleave(refs)] if len(clips) > 1 else [clips[0], refs[0]]
277
+
278
+ # inference
279
+ if backend in ["tensorrt", "trt"]:
280
+ out = _tensorrt_inference(input_clips, onnx_path=onnx_path, engine_dir=engine_dir, clip_w=clip_w, clip_h=clip_h, num_planes=num_planes, precision=precision, num_streams=num_streams, gpu_id=gpu_id, force_rebuild=force_rebuild)
281
+ elif backend in ["directml", "dml"]:
282
+ out = core.ort.Model(input_clips, network_path=onnx_path, provider="DML", device_id=gpu_id, num_streams=num_streams)
283
+ elif backend in ["ncnn"]:
284
+ out = core.ncnn.Model(input_clips, network_path=onnx_path, fp16=base_clip.format.bits_per_sample == 16, output_format=1 if base_clip.format.bits_per_sample == 16 else 0, device_id=gpu_id, num_streams=num_streams) # fp16=true/output_format=1 to allow fp16 input/output
285
+ else:
286
+ raise ValueError("vs_colorfix.wavelet: Backend must be CPU, NCNN, DirectML, or TensorRT.")
287
+
288
+ # vsmlrt outputs yuv as rgb, recombine as yuv if input was yuv
289
+ if base_clip.format.color_family == vs.YUV and out.format.color_family != vs.YUV:
290
+ out = core.std.ShufflePlanes(out, planes=[0, 1, 2], colorfamily=base_clip.format.color_family, prop_src=base_clip)
291
+
292
+ # separate clips and return
293
+ return [core.std.SelectEvery(out, cycle=len(clips), offsets=i) for i in range(len(clips))] if len(clips) > 1 else [out]
294
+
295
+
296
+ def _wavelet_color_fix_vsmlrt(clip, ref, wavelets, planes, backend="ncnn", num_streams=1, gpu_id=0, engine_folder=None):
297
+ # gpu backends using vsmlrt
298
+
299
+ if not isinstance(num_streams, int) or isinstance(num_streams, bool):
300
+ raise TypeError("vs_colorfix.wavelet: Number of parallel GPU streams (num_streams) must be an integer.")
301
+ if num_streams < 1:
302
+ raise ValueError("vs_colorfix.wavelet: Number of parallel GPU streams (num_streams) must be at least 1.")
303
+ if clip.format.sample_type != vs.FLOAT:
304
+ raise ValueError("vs_colorfix.wavelet: Input clips must be in float format when using a GPU backend. Use 16-bit float for best performance, if supported by your GPU. Most modern GPUs do.")
305
+
306
+ clip_format = clip.format
307
+ num_planes = clip.format.num_planes
308
+ plane_wavelets = _plane_wavelets(clip_format, wavelets)
309
+
310
+ # if all planes can use the same model and size, inference as one
311
+ if planes == set(range(num_planes)) and clip_format.subsampling_w == 0 and clip_format.subsampling_h == 0 and len(set(plane_wavelets)) == 1:
312
+ return _vsmlrt_inference([clip], [ref], wavelets=plane_wavelets[0], backend=backend, num_streams=num_streams, gpu_id=gpu_id, engine_folder=engine_folder)[0]
313
+
314
+ # else inference selected planes separately, interleaved when possible
315
+ clips = list(core.std.SplitPlanes(clip))
316
+ refs = list(core.std.SplitPlanes(ref))
317
+
318
+ for effective_wavelets, selected_planes in _inference_groups(clips, planes, plane_wavelets):
319
+ selected_out = _vsmlrt_inference([clips[p] for p in selected_planes], [refs[p] for p in selected_planes], wavelets=effective_wavelets, backend=backend, num_streams=num_streams, gpu_id=gpu_id, engine_folder=engine_folder)
320
+ for p, processed in zip(selected_planes, selected_out):
321
+ clips[p] = processed
322
+
323
+ return core.std.ShufflePlanes(clips, [0] * num_planes, clip_format.color_family)
324
+
325
+
326
+ def _wavelet_color_fix_atwt(clip, ref, wavelets, planes):
327
+ # cpu backend using the vapoursynth-atwt plugin
328
+
329
+ if clip.format.sample_type == vs.FLOAT and clip.format.bits_per_sample == 16:
330
+ raise ValueError("vs_colorfix.wavelet: The CPU backend does not support 16-bit float formats. Consider using a GPU backend, or change formats.")
331
+
332
+ clip_format = clip.format
333
+ num_planes = clip.format.num_planes
334
+ plane_wavelets = _plane_wavelets(clip_format, wavelets)
335
+
336
+ def _decompose(base, wavelet_count):
337
+ details = []
338
+ for radius in range(1, wavelet_count + 1):
339
+ detail = core.atwt.ExtractFrequency(base, radius=radius)
340
+ base = core.std.MakeDiff(base, detail)
341
+ details.append(detail)
342
+ return details + [base]
343
+
344
+ def _recombine(layers):
345
+ out = layers[-1]
346
+ for detail in reversed(layers[:-1]):
347
+ out = core.atwt.ReplaceFrequency(base=out, detail=detail)
348
+ return out
349
+
350
+ def _fix_clip(clip, ref, wavelet_count):
351
+ c_layers = _decompose(clip, wavelet_count)
352
+ r_layers = _decompose(ref, wavelet_count)
353
+ return _recombine(c_layers[:-1] + [r_layers[-1]])
354
+
355
+ # process the whole clip at once if possible
356
+ if planes == set(range(num_planes)) and clip_format.subsampling_w == 0 and clip_format.subsampling_h == 0 and len(set(plane_wavelets)) == 1:
357
+ return _fix_clip(clip, ref, plane_wavelets[0])
358
+
359
+ # else each plane separately
360
+ clips = list(core.std.SplitPlanes(clip))
361
+ refs = list(core.std.SplitPlanes(ref))
362
+
363
+ for p in sorted(planes):
364
+ clips[p] = _fix_clip(clips[p], refs[p], plane_wavelets[p])
365
+
366
+ return core.std.ShufflePlanes(clips, [0] * num_planes, clip_format.color_family)
367
+
368
+
369
+ def wavelet_color_fix(clip, ref, wavelets=4, planes=None, backend="ncnn", num_streams=2, gpu_id=0, engine_folder=None):
370
+ """Fixes color shift based on a reference clip. Works similarly to `average()`, but more accurate when color differences are large, at the cost of more computation.
371
+
372
+ Args:
373
+ clip: Clip where the color fix will be applied to.
374
+ ref: Reference clip where the colors are taken from. Should match the base clip somewhat. Compression, grain, or lower resolution are all okay.
375
+ wavelets: Number of wavelets, around 4 seems to work best in most cases. Higher means a more global color match and wider bloom/bleed. Lower means a more
376
+ local color match and smaller bloom/bleed. Lower is also faster. Too low and the reference clip will become visible. Test values 3 and 8 and this will become more clear.
377
+ planes: Which planes to color fix. Any unmentioned planes will simply be copied. None means all planes will be color fixed.
378
+ backend: The backend used to run the color fix. **16-bit float input is always much faster on GPU, but not supported by older GPUs.**
379
+ - `cpu` = CPU mode using the Vapoursynth-ATWT plugin (slow).
380
+ - `ncnn` = GPU mode using vs-mlrt with NCNN support. Works on almost any GPU, even MAC (fast).
381
+ - `directml` = GPU mode using vs-mlrt with DirectML support. Works on most GPUs, but Windows only (fast).
382
+ - `tensorrt` = GPU mode using vs-mlrt with TensorRT support. Requires an Nvidia RTX GPU (very fast).
383
+ num_streams: Number of parallel GPU streams. Higher can be faster, but requires more VRAM. Does not affect the CPU backend.
384
+ gpu_id: GPU index ID starting from 0 for the first compatible GPU. For example to switch between iGPU/dGPU. Does not affect the CPU backend.
385
+ engine_folder: Optional path to the TensorRT engine storage location. By default engines are stored in `vs_colorfix/engines`. Only affects the TensorRT backend.
386
+ """
387
+
388
+ # checks
389
+ if not isinstance(clip, vs.VideoNode):
390
+ raise TypeError("vs_colorfix.wavelet: Clip must be a vapoursynth clip.")
391
+ if not isinstance(ref, vs.VideoNode):
392
+ raise TypeError("vs_colorfix.wavelet: Ref must be a vapoursynth clip.")
393
+ if clip.format.id == vs.PresetVideoFormat.NONE or clip.width == 0 or clip.height == 0:
394
+ raise TypeError("vs_colorfix.wavelet: Clip must have constant format and dimensions.")
395
+ if ref.format.id == vs.PresetVideoFormat.NONE or ref.width == 0 or ref.height == 0:
396
+ raise TypeError("vs_colorfix.wavelet: Ref must have constant format and dimensions.")
397
+ if clip.num_frames != ref.num_frames:
398
+ raise ValueError("vs_colorfix.wavelet: Clip and ref must have the same number of frames.")
399
+ if not isinstance(wavelets, int) or isinstance(wavelets, bool):
400
+ raise TypeError("vs_colorfix.wavelet: Number of wavelets must be an integer.")
401
+ if not 1 <= wavelets <= 10:
402
+ raise ValueError("vs_colorfix.wavelet: Number of wavelets must be in the range 1-10.")
403
+ if not isinstance(gpu_id, int) or isinstance(gpu_id, bool):
404
+ raise TypeError("vs_colorfix.wavelet: GPU ID must be an integer.")
405
+ if gpu_id < 0:
406
+ raise ValueError("vs_colorfix.wavelet: GPU ID can not be negative.")
407
+ if not isinstance(num_streams, int) or isinstance(num_streams, bool):
408
+ raise TypeError("vs_colorfix.wavelet: Number of parallel GPU streams (num_streams) must be an integer.")
409
+ if num_streams < 1:
410
+ raise ValueError("vs_colorfix.wavelet: Number of parallel GPU streams (num_streams) must be at least 1.")
411
+ if clip.format.bits_per_sample <= 8 or ref.format.bits_per_sample <= 8:
412
+ warnings.warn("vs_colorfix.wavelet: Input clips have a low bit depth, which will cause banding. 16-bit input is recommended.", UserWarning, stacklevel=2)
413
+
414
+ clip_format = clip.format
415
+ num_planes = clip.format.num_planes
416
+ backend = backend.lower()
417
+
418
+ if backend in ["directml", "dml"] and sys.platform != "win32":
419
+ raise RuntimeError("vs_colorfix.wavelet: The DirectML backend is only available on Windows.")
420
+ if backend in ["tensorrt", "trt"] and sys.platform not in ("win32", "linux"):
421
+ raise RuntimeError("vs_colorfix.wavelet: The TensorRT backend is only available on Windows and Linux.")
422
+ if backend in ["cpu"] and not hasattr(core, "atwt"):
423
+ raise RuntimeError("vs_colorfix.wavelet: Please install the plugin 'Vapoursynth-ATWT' to use the CPU backend.")
424
+
425
+ if clip_format.id != ref.format.id:
426
+ raise ValueError("vs_colorfix.wavelet: Clip and ref must have the same format.")
427
+ if planes is None:
428
+ planes = list(range(num_planes))
429
+ if isinstance(planes, int):
430
+ planes = [planes]
431
+ if num_planes == 1:
432
+ planes = [0]
433
+ planes = set(planes)
434
+ if not planes <= set(range(num_planes)):
435
+ raise ValueError("vs_colorfix.wavelet: Invalid plane index specified.")
436
+
437
+ # resize ref if needed
438
+ if ref.width != clip.width or ref.height != clip.height:
439
+ ref = core.resize.Bilinear(ref, width=clip.width, height=clip.height)
440
+
441
+ # clamp and shift uv if needed
442
+ shift_uv = False
443
+ if clip_format.sample_type == vs.FLOAT:
444
+ clamp_expr = "x 0 max 1 min"
445
+ if clip_format.color_family == vs.YUV:
446
+ clamp_uv_expr = "x -0.5 max 0.5 min"
447
+ if backend != "cpu":
448
+ shift_uv = any(p in planes for p in (1, 2))
449
+ clamp_uv_expr += " 0.5 +" # shift uv to be within 0-1 for model input
450
+ expr = [clamp_expr if 0 in planes else "", clamp_uv_expr if 1 in planes else "", clamp_uv_expr if 2 in planes else "",]
451
+ else:
452
+ expr = [clamp_expr if p in planes else "" for p in range(num_planes)]
453
+
454
+ clip = _expression(clip, expr=expr)
455
+ ref = _expression(ref, expr=expr)
456
+
457
+ # color fix
458
+ if backend == "cpu":
459
+ clip = _wavelet_color_fix_atwt(clip, ref, wavelets=wavelets, planes=planes)
460
+ else:
461
+ clip = _wavelet_color_fix_vsmlrt(clip, ref, wavelets=wavelets, planes=planes, backend=backend, num_streams=num_streams, gpu_id=gpu_id, engine_folder=engine_folder)
462
+
463
+ # undo uv shift if needed and return
464
+ if shift_uv:
465
+ return _expression(clip, expr=["", "x 0.5 -" if 1 in planes else "", "x 0.5 -" if 2 in planes else ""])
466
+ return clip
@@ -0,0 +1,217 @@
1
+ Metadata-Version: 2.4
2
+ Name: vs_colorfix
3
+ Version: 2.1.0
4
+ Summary: Color Fix, Color Transfer, or Color Match for VapourSynth.
5
+ Project-URL: Homepage, https://github.com/pifroggi/vs_colorfix
6
+ Project-URL: Repository, https://github.com/pifroggi/vs_colorfix
7
+ Project-URL: Issues, https://github.com/pifroggi/vs_colorfix/issues
8
+ Author: pifroggi
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: color fix,color matching,color transfer,filtering,vapoursynth,video
12
+ Classifier: Environment :: GPU
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Multimedia :: Video
15
+ Requires-Python: >=3.12
16
+ Requires-Dist: vapoursynth-mlrt-ncnn
17
+ Requires-Dist: vapoursynth-mlrt-ort; sys_platform == 'win32'
18
+ Requires-Dist: vapoursynth-vszip
19
+ Requires-Dist: vapoursynth>=74
20
+ Provides-Extra: tensorrt
21
+ Requires-Dist: cuda-python; (sys_platform == 'win32' or sys_platform == 'linux') and extra == 'tensorrt'
22
+ Requires-Dist: tensorrt-cu13>=11.1.0.106; (sys_platform == 'win32' or sys_platform == 'linux') and extra == 'tensorrt'
23
+ Requires-Dist: vapoursynth-mlrt-trt>=16.0; (sys_platform == 'win32' or sys_platform == 'linux') and extra == 'tensorrt'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # Color Fix for VapourSynth
27
+
28
+ For example for fixing color shift from AI upscaling/restoration models, or transfering color grading from an old release to a remaster. Also known as Color Transfer or Color Matching. See this collection of [Comparisons](https://slow.pics/c/abXjnKn3).
29
+
30
+ <br />
31
+
32
+ <p align="center">
33
+ <a href="https://slow.pics/c/abXjnKn3">
34
+ <img src="https://raw.githubusercontent.com/pifroggi/vs_colorfix/refs/heads/main/README_img.png" width="600" />
35
+ </a>
36
+ </p>
37
+
38
+ ## Installation
39
+
40
+ ### Nvidia
41
+ ```
42
+ pip install -U vs_colorfix[tensorrt] --extra-index-url https://pypi.nvidia.com/
43
+ ```
44
+ To enable the Wavelet Color Fix CPU backend, install the plugin [Vapoursynth-ATWT](https://github.com/yuygfgg/Vapoursynth-ATWT). *(optional)*
45
+ ### Others
46
+ ```
47
+ pip install -U vs_colorfix
48
+ ```
49
+ To enable the Wavelet Color Fix CPU backend, install the plugin [Vapoursynth-ATWT](https://github.com/yuygfgg/Vapoursynth-ATWT). *(optional)*
50
+
51
+ <br />
52
+
53
+ > [!TIP]
54
+ > For VapourSynth R73 and older, follow the [manual installation steps](https://github.com/pifroggi/vs_colorfix/wiki/Manual-Installation).
55
+
56
+ <br />
57
+
58
+
59
+ ## Average Color Fix
60
+ Fixes color shift by matching the average color of a clip to a reference clip. A very fast way to transfer colors from one clip to another. For large color differences, the Wavelet Color Fix is more accurate.
61
+
62
+ ```python
63
+ import vs_colorfix
64
+ clip = vs_colorfix.average(clip, ref, radius=10, planes=[0, 1, 2], fast=False)
65
+ ```
66
+
67
+ __*`clip`*__
68
+ Base clip where the colors will be applied to.
69
+ Recommended higher than 8-bit to avoid banding.
70
+
71
+ __*`ref`*__
72
+ Reference clip where the colors are taken from.
73
+ Check the [comparisons](https://slow.pics/c/abXjnKn3) to get an idea how close it should match the base clip.
74
+
75
+ __*`radius`*__
76
+ Higher means a more global color match and wider bloom/bleed.
77
+ Lower means a more local color match and smaller bloom/bleed. Too low and the reference clip will become visible.
78
+ Test values 5 and 30 and this will become more clear.
79
+
80
+ __*`planes`* (optional)__
81
+ Which planes to color fix. Any unmentioned planes will simply be copied.
82
+ If not set, all planes will be color-fixed.
83
+
84
+ __*`fast`* (optional)__
85
+ Does the averaging via a downscale instead of a blur, which is much faster, but will produce faint blocky artifacts.
86
+ I found it useful for radius > 60 where artifacts are no longer noticable, or to fix something like a prefilter clip.
87
+
88
+ > [!TIP]
89
+ > * If your clips are not sufficiently aligned or synchronized, use [vs_align](https://github.com/pifroggi/vs_align) to align them first.
90
+ > * To replicate chaiNNers Average Color Fix, you can convert % to radius: `radius = (100/percentage-1)/2`
91
+ > ChaiNNer works like fast=True does here, but it is recommended to leave it off for better results.
92
+
93
+ <br />
94
+
95
+ ## Wavelet Color Fix
96
+ Fixes color shift by first converting into wavelets, then matching the average color of a clip to a reference clip. Works similarly to the Average Color Fix, but more accurate when the color differences are large, at the cost of more computation.
97
+
98
+ ```python
99
+ import vs_colorfix
100
+ clip = vs_colorfix.wavelet(clip, ref, wavelets=4, planes=[0, 1, 2], backend="ncnn", num_streams=2, gpu_id=0, engine_folder=None)
101
+ ```
102
+
103
+ __*`clip`*__
104
+ Base clip where the colors will be applied to.
105
+ Recommended higher than 8-bit to avoid banding.
106
+
107
+ __*`ref`*__
108
+ Reference clip where the colors are taken from.
109
+ Check the [comparisons](https://slow.pics/c/abXjnKn3) to get an idea how close it should match the base clip.
110
+
111
+ __*`wavelets`*__
112
+ Number of wavelets in the 1-10 range. Around 4 seems to work best in most cases.
113
+ Higher means a more global color match and wider bloom/bleed.
114
+ Lower means a more local color match and smaller bloom/bleed. Too low and the reference clip will become visible.
115
+ Test values 3 and 8 and this will become more clear.
116
+
117
+ __*`planes`* (optional)__
118
+ Which planes to color fix. Any unmentioned planes will simply be copied.
119
+ If not set, all planes will be color-fixed.
120
+
121
+ __*`backend`* (optional)__
122
+ The used backend. **16-bit float input is always much faster on GPU, but not supported by older GPUs.**
123
+ * `cpu` CPU mode using the vapoursynth-ATWT plugin *(slow)*.
124
+ * `ncnn` GPU mode using vs-mlrt with NCNN support. Works on almost any GPU, even Mac *(fast)*.
125
+ * `directml` GPU mode using vs-mlrt with DirectML support. Works on most GPUs, Windows only *(fast)*.
126
+ * `tensorrt` GPU mode using vs-mlrt with TensorRT support. Requires an Nvidia RTX GPU. On the first run, this mode will automatically build an engine, which may take a few minutes. Changing wavelets or input dimensions will trigger rebuilding, but build engines are stored *(very fast)*.
127
+
128
+ __*`num_streams`* (optional)__
129
+ Number of parallel GPU streams. Higher can be faster, but requires more VRAM. Does not affect the CPU backend.
130
+
131
+ __*`gpu_id`* (optional)__
132
+ Which GPU to use starting from 0. Can be used to switch between iGPU/dGPU. Does not affect the CPU backend.
133
+
134
+ __*`engine_folder`* (optional)__
135
+ Optional path to the TensorRT engine storage location. By default engines are stored in `vs_colorfix/engines`. Only affects the TensorRT backend.
136
+
137
+ > [!TIP]
138
+ > * On low end GPUs, the NCNN backend can be faster than TensorRT and DirectML.
139
+ > * If your clips are not sufficiently aligned or synchronized, use [vs_align](https://github.com/pifroggi/vs_align) to align them first.
140
+
141
+ <br />
142
+
143
+ ## Benchmarks
144
+ Benchmarks were done on a RTX 4090 GPU and a Ryzen 5900X CPU with 16-bit input clips.
145
+
146
+ <table>
147
+ <tr>
148
+ <td valign="top">
149
+
150
+ <table>
151
+ <thead>
152
+ <tr align="center">
153
+ <th colspan="5">Wavelet Color Fix</th>
154
+ </tr>
155
+ <tr align="center">
156
+ <th>Resolution</th>
157
+ <th>TensorRT</th>
158
+ <th>DirectML</th>
159
+ <th>NCNN</th>
160
+ <th>CPU</th>
161
+ </tr>
162
+ </thead>
163
+ <tbody>
164
+ <tr align="center">
165
+ <td>1440x1080</td>
166
+ <td>~360 fps</td>
167
+ <td>~250 fps</td>
168
+ <td>~250 fps</td>
169
+ <td>~20 fps</td>
170
+ </tr>
171
+ <tr align="center">
172
+ <td>2880x2160</td>
173
+ <td>~80 fps</td>
174
+ <td>~60 fps</td>
175
+ <td>~60 fps</td>
176
+ <td>~5 fps</td>
177
+ </tr>
178
+ </tbody>
179
+ </table>
180
+
181
+ </td>
182
+ <td valign="top">
183
+
184
+ <table>
185
+ <thead>
186
+ <tr align="center">
187
+ <th colspan="3">Average Color Fix</th>
188
+ </tr>
189
+ <tr align="center">
190
+ <th>Resolution</th>
191
+ <th>fast=False</th>
192
+ <th>fast=True</th>
193
+ </tr>
194
+ </thead>
195
+ <tbody>
196
+ <tr align="center">
197
+ <td>1440x1080</td>
198
+ <td>~250 fps</td>
199
+ <td>~850 fps</td>
200
+ </tr>
201
+ <tr align="center">
202
+ <td>2880x2160</td>
203
+ <td>~60 fps</td>
204
+ <td>~150 fps</td>
205
+ </tr>
206
+ </tbody>
207
+ </table>
208
+
209
+ </td>
210
+ </tr>
211
+ </table>
212
+
213
+ <br />
214
+
215
+ ## Acknowledgements
216
+ Average Color Fix idea from [chaiNNer](https://github.com/chaiNNer-org/chaiNNer).
217
+ Wavelet Color Fix idea from [sd-webui-stablesr](https://github.com/pkuliyi2015/sd-webui-stablesr/blob/master/srmodule/colorfix.py).
@@ -0,0 +1,47 @@
1
+ vs_colorfix/__init__.py,sha256=Ovm8i0xiUG_snc7dji22ZG6UtExBoo48xfgKweeMU5A,120
2
+ vs_colorfix/average_color_fix.py,sha256=pxWIw0begMAaTQuENg9mmGf790nXNXdQt8EEdn5Dl64,9305
3
+ vs_colorfix/wavelet_color_fix.py,sha256=ANDQ4bZKqOquasGS5Lp9Q1w3OrNApz0N6swT-yRQq0Y,24852
4
+ vs_colorfix/models/waveletcolorfix_w10_c1_fp16.onnx,sha256=EyYq3Vlso8Cl5Z7cYUSA3RHoymbJefBTvrd-YCgJzxg,11934
5
+ vs_colorfix/models/waveletcolorfix_w10_c1_fp32.onnx,sha256=K9_a26HLpOrHQzV5G2og0uLSknnlrYvolJ7HpmFLR20,11962
6
+ vs_colorfix/models/waveletcolorfix_w10_c3_fp16.onnx,sha256=Ez2mhB0RpEgcQfz9jPA51fG_Ddhix3crrUgoTrM1MdY,12038
7
+ vs_colorfix/models/waveletcolorfix_w10_c3_fp32.onnx,sha256=JMwGhIQse_8l_hzEu-in2FnDiOIB_xrqdoRqZg5pMOs,12170
8
+ vs_colorfix/models/waveletcolorfix_w1_c1_fp16.onnx,sha256=4_W9-ySSE91faIl3WMQUIAsP6w1YJ53LRdV7B-In-v0,1809
9
+ vs_colorfix/models/waveletcolorfix_w1_c1_fp32.onnx,sha256=PxP_YAca1m-XwlGacwwzc-ehDmDZ668aY_4wJ7DeToA,1837
10
+ vs_colorfix/models/waveletcolorfix_w1_c3_fp16.onnx,sha256=5x3l3z74AQ2A2q16TKGc3pcA9QUoLfvzyLUTQ1Xsb3Q,1913
11
+ vs_colorfix/models/waveletcolorfix_w1_c3_fp32.onnx,sha256=WVfWij9P7e_Fwao7OCWQPHbBqIlx0zEBlDbpL1e1rWc,2045
12
+ vs_colorfix/models/waveletcolorfix_w2_c1_fp16.onnx,sha256=_SDLo_e6zCcnxSuwmezksf6vgKpntu5eTdqsHzEKxvE,2929
13
+ vs_colorfix/models/waveletcolorfix_w2_c1_fp32.onnx,sha256=SysdCD16HDRONa7jfeziiIWdNZmC9hi2ef6KeS8brJE,2957
14
+ vs_colorfix/models/waveletcolorfix_w2_c3_fp16.onnx,sha256=yBhS9rMR7Y3mM9Z9D0OWeQLUcgAn_soiqI3KQCm3nGg,3033
15
+ vs_colorfix/models/waveletcolorfix_w2_c3_fp32.onnx,sha256=mTtzEScLSc3KcajcWJs-Y4P__SSDDqdh4YZ7cS6BhvI,3165
16
+ vs_colorfix/models/waveletcolorfix_w3_c1_fp16.onnx,sha256=YWgActbHvKT3otwOv8k0wTFHM4fF7uyG2NVQzeArxlk,4049
17
+ vs_colorfix/models/waveletcolorfix_w3_c1_fp32.onnx,sha256=ebRndA_xFb9Pv9PhKtlW2tgrfYlmev8WDDE0fdXeC1o,4077
18
+ vs_colorfix/models/waveletcolorfix_w3_c3_fp16.onnx,sha256=g8PVaaQG7Lz4VhHDCdbw0_strgDw3QAOvjJjTEe8qmo,4153
19
+ vs_colorfix/models/waveletcolorfix_w3_c3_fp32.onnx,sha256=RZQGR17Tdeb0-PcCeWXFa81BftHPNX5uIItvaSC9B9M,4285
20
+ vs_colorfix/models/waveletcolorfix_w4_c1_fp16.onnx,sha256=IMsySRFvf22-BoMwDNCJQ46lmD3TaGGsRQfNaXlOnPc,5169
21
+ vs_colorfix/models/waveletcolorfix_w4_c1_fp32.onnx,sha256=pMdi4XkS5bvcB_MwVk2Ie9rkdVgHNVoYnvr-gdOa1vg,5197
22
+ vs_colorfix/models/waveletcolorfix_w4_c3_fp16.onnx,sha256=9WbAG1-X1rW8-j8q4E-9aY8NTRi-YDpr_r6Uw4p3k-U,5273
23
+ vs_colorfix/models/waveletcolorfix_w4_c3_fp32.onnx,sha256=nTiJ3HwlFLuJIKtUscASTiwPOSTfw2aFMkKCSaDu4Hc,5405
24
+ vs_colorfix/models/waveletcolorfix_w5_c1_fp16.onnx,sha256=CJ7DrjLJ1J6KSYRruKTU_KB1brd8XGYd6m4kbebSjWA,6289
25
+ vs_colorfix/models/waveletcolorfix_w5_c1_fp32.onnx,sha256=jVgXS57AnyVfqJhvKeB8vFjeappJFBTrOmGphx6bI3A,6317
26
+ vs_colorfix/models/waveletcolorfix_w5_c3_fp16.onnx,sha256=1mDo_8_Zka4DWVPSiYIdKj0PyjbDF0KPgKnL-b6wWJs,6393
27
+ vs_colorfix/models/waveletcolorfix_w5_c3_fp32.onnx,sha256=Rl5LpwoZLcnpKJ6IfkA1OE17TxB_77vQzr_xBG5pX3k,6525
28
+ vs_colorfix/models/waveletcolorfix_w6_c1_fp16.onnx,sha256=nuWxjZ7sWytTXqtpmlDENudlN_e0eS8zaLgcIuMd2Ic,7409
29
+ vs_colorfix/models/waveletcolorfix_w6_c1_fp32.onnx,sha256=SX1VQriGtjGjLF7WUrkf6OShy5a4Sz-zgVxQMiOGVRw,7437
30
+ vs_colorfix/models/waveletcolorfix_w6_c3_fp16.onnx,sha256=lPIJ24oFDOqtoJ7-MCjunlLreLLAsaC40kb5dMn-jVw,7513
31
+ vs_colorfix/models/waveletcolorfix_w6_c3_fp32.onnx,sha256=B3uD2RnxCWHomtS9HnGBWgUtyTa_mEMKfP1H-mbni_4,7645
32
+ vs_colorfix/models/waveletcolorfix_w7_c1_fp16.onnx,sha256=Okb6N8BLziqBeSp8YVbZhJQ_g5--MypL_rCqENT-KHU,8537
33
+ vs_colorfix/models/waveletcolorfix_w7_c1_fp32.onnx,sha256=9sKKKL4xQLhzq7jzSrwrH7DtZGLi0W-bKCXosPgybYU,8565
34
+ vs_colorfix/models/waveletcolorfix_w7_c3_fp16.onnx,sha256=g56ZJQzNMX8-DLG3t4FzPpC8cN1p3suwNJna7xuQudo,8641
35
+ vs_colorfix/models/waveletcolorfix_w7_c3_fp32.onnx,sha256=GP1UPQj66NbE9qoMxVHT1zz16LYCfFzb07gfdCwspc8,8773
36
+ vs_colorfix/models/waveletcolorfix_w8_c1_fp16.onnx,sha256=mpuc3Vnis9UNv3tkFx34XptL3FaWGimQm6K9gxbnpAo,9669
37
+ vs_colorfix/models/waveletcolorfix_w8_c1_fp32.onnx,sha256=bmDeluMJiK9EL88ufM_WnSEqpzKedSEFh42VBrQ0ACk,9697
38
+ vs_colorfix/models/waveletcolorfix_w8_c3_fp16.onnx,sha256=Tba4zYZW6uq4QV2fbT1xyxg-JLeeQ_fCBlzVxzeAi1Y,9773
39
+ vs_colorfix/models/waveletcolorfix_w8_c3_fp32.onnx,sha256=WwH__Q8ebk_l_TjS5yl2tL5VINj_dkaxlSBDKk2Zr9o,9905
40
+ vs_colorfix/models/waveletcolorfix_w9_c1_fp16.onnx,sha256=NcYSw1vTC537HQJFUbu1VsSihxIg1o9Kdiof-H03Sgs,10801
41
+ vs_colorfix/models/waveletcolorfix_w9_c1_fp32.onnx,sha256=iAiQ9HQ_qoozyiD1JubAQ_PduML2Gf9l4bZyjfycerw,10829
42
+ vs_colorfix/models/waveletcolorfix_w9_c3_fp16.onnx,sha256=0G6PsfW9RdjaRE9sWEdBnKUeis9zGlB8UBIN--F26vc,10905
43
+ vs_colorfix/models/waveletcolorfix_w9_c3_fp32.onnx,sha256=VkTJSpasoTdyFof2hr_NW7ZV3th86sfNWl30LMJFW1I,11037
44
+ vs_colorfix-2.1.0.dist-info/METADATA,sha256=RF3WN_YsJasRvTU8GNpS1-AhXNiX_abq-uWw9JC7HVs,8016
45
+ vs_colorfix-2.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
46
+ vs_colorfix-2.1.0.dist-info/licenses/LICENSE,sha256=rDnRnsVuJK-HA3kjcSyoTRoRJcBKkxIGnGch87i1KSE,11337
47
+ vs_colorfix-2.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 pifroggi
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.