Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Expand flagship coverage and add kornia-rs 0.2 comparisons (#6020)

Dmytro Mishkin4897753b8bbf
diff --git a/benchmarks/README.md b/benchmarks/README.md
index fddc9771a..f3d377961 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -14,22 +14,40 @@ otherwise reach for. All flagships share one command line, one console layout an
| Suite | Flagship ops | Baselines |
| --- | --- | --- |
| [`augmentation`](augmentation/flagship.py) | flip, affine, perspective, resized crop, color jiggle, blur, brightness, grayscale (class API, sampling included) | torchvision v2, albumentations, OpenCV, PIL |
-| [`color`](color/flagship.py) | grayscale, HSV, Lab, YCbCr, Bayer demosaic | torchvision v2, scikit-image, OpenCV (per image and stacked), PIL |
-| [`contrib`](contrib/flagship.py) | exact connected components, distance transform | scikit-image, SciPy, OpenCV |
-| [`enhance`](enhance/flagship.py) | normalize, gamma, hue, saturation, equalize, CLAHE | torchvision v2, albumentations, scikit-image, OpenCV, PIL |
-| [`feature`](feature/flagship.py) | Harris and GFTT responses, SIFT detect+describe, SNN matching | scikit-image, OpenCV |
-| [`filters`](filters/flagship.py) | Gaussian, Sobel, Laplacian, median, box, Canny, unsharp, bilateral, guided, motion, Otsu | torchvision v2, albumentations, scikit-image, OpenCV, kornia-rs, PIL |
-| [`geometry`](geometry/flagship.py) | warp perspective/affine, rotate, resize, perspective-transform solve | torchvision v2, OpenCV |
+| [`color`](color/flagship.py) | grayscale, RGB↔HSV, Lab, YCbCr, Bayer demosaic | torchvision v2, scikit-image, OpenCV (per image and stacked), PIL, kornia-rs |
+| [`contrib`](contrib/flagship.py) | exact connected components, distance transform | scikit-image, SciPy, OpenCV, kornia-rs |
+| [`enhance`](enhance/flagship.py) | normalize, gamma, hue, saturation, equalize, CLAHE | torchvision v2, albumentations, scikit-image, OpenCV, PIL, kornia-rs |
+| [`feature`](feature/flagship.py) | Harris and GFTT responses, SIFT detect+describe, SNN/MNN/SMNN matching, batched SMNN | scikit-image, OpenCV, kornia-rs |
+| [`filters`](filters/flagship.py) | Gaussian, Sobel magnitude and spatial gradients, Laplacian, median, box, Canny, unsharp, bilateral, guided, motion, Otsu | torchvision v2, albumentations, scikit-image, OpenCV, kornia-rs, PIL |
+| [`geometry`](geometry/flagship.py) | warp perspective/affine, rotate, resize, remap, point transforms, depth unprojection, perspective-transform solve | torchvision v2, OpenCV, kornia-rs |
| [`io`](io/flagship.py) | JPEG and PNG decode to an RGB uint8 tensor | torchvision, OpenCV, PIL |
-| [`losses`](losses/flagship.py) | binary focal, focal, Dice, SSIM, total variation (forward + backward) | torchvision |
+| [`losses`](losses/flagship.py) | binary focal, focal, Dice (micro, macro, weighted), SSIM, total variation (forward + backward) | torchvision |
| [`metrics`](metrics/flagship.py) | PSNR, SSIM, mean IoU | scikit-image, OpenCV |
-| [`morphology`](morphology/flagship.py) | dilation, erosion, opening, gradient | torchmorph (CUDA only), albumentations, scikit-image, OpenCV |
+| [`morphology`](morphology/flagship.py) | dilation, erosion, opening, gradient | torchmorph (CUDA only), albumentations, scikit-image, OpenCV, kornia-rs |
Modules without a flagship: `models`, `tracking` and the model wrappers in `contrib` need
downloaded weights (learned local features are covered by `feature/local_features.py`); `nerf`,
`sensors`, `x`, `onnx`, `transpiler`, `grad_estimator`, `image`, `core`, `utils` and `testing`
are training loops, containers, exporters or plumbing whose cost is the ops above.
+Coverage is a curated sample, not a usage ranking or an exhaustive API inventory. In particular:
+
+- Color now measures both directions of RGB/HSV; inverse inputs are prepared in each backend's
+ native hue units (radians, turns, degrees, or PIL's quantized bytes).
+- Filters distinguish Sobel magnitude from normalized x/y `spatial_gradient`; the latter's
+ OpenCV counterpart uses prepared float32 inputs, replicate padding, and scale 1/8.
+- Geometry includes image remapping, H*W-point projective transforms, and z-depth unprojection.
+ The depth row has no external baseline; an unrelated operation is not substituted for it.
+- Feature matching includes SNN, MNN, symmetric SNN, and batched symmetric SNN on identical
+ descriptor pairs. OpenCV's baseline includes the required ratio and mutuality filters;
+ its per-pair loop also provides context for Kornia's batched API.
+- Remaining gaps include functional brightness/contrast (augmentation's sampled class calls
+ measure different work), enhancement/normalization variants, 3D gradients and volumetric
+ warps, camera/epipolar primitives, and loss options such as class counts, ignored labels,
+ reductions, Tversky/Lovasz and robust regression. The Dice micro/macro/weighted rows cover
+ distinct reduction paths but do not exhaust those loss regimes. Learned feature/model
+ timing remains in the separate weight-dependent suites below.
+
Deeper, single-topic scripts:
| Directory | Contents |
@@ -149,6 +167,10 @@ Every benchmark here must follow the same rules (utilities in [`common.py`](comm
The `0.9.0rc1` result files predate the pin and have no `opencv_num_threads`: on the
i7-14700K Linux runs, the OpenCV and albumentations cells used every core while torch used 4.
The Apple runs are unaffected, because GCD ignores the pin.
+ `setup_run` also sets `RAYON_NUM_THREADS` to `--threads` before the first native operation.
+ Run each CLI in a fresh process: an existing Rayon global pool cannot be resized by changing
+ the environment. `rayon_num_threads_requested` records the request, not an observed count;
+ older result files may have used Rayon's unrestricted default.
- **Public API only:** benchmark `kornia.*` as users call it β€” no private helpers, no
reimplementations inside the script.
@@ -230,10 +252,26 @@ All flagships build on the same helpers in [`common.py`](common.py), so their ou
The filters flagship includes optional scikit-image baselines. To exercise every
current baseline, install the benchmark-only dependency with
`uv pip install scikit-image`; kornia-rs, a kornia dependency, supplies Gaussian,
-box and median blur, Sobel, and grayscale bilateral. Its module docstring lists
+box and median blur, Sobel, grayscale bilateral, and Canny. Its module docstring lists
differences in padding, kernel support, normalization, and clipping; empty cells
indicate an unavailable dependency or a missing native counterpart.
The grayscale bilateral has a separate row because its Python API only accepts grayscale.
+The [0.2.0 PyPI wheel](https://pypi.org/project/kornia-rs/0.2.0/) also supplies CPU baselines for
+all six color rows, affine/perspective warps, rotations (via affine), resize, normalization,
+equalize/CLAHE, all four morphology rows, SIFT detect+describe, and connected components.
+The optional API resolver supports both the `imgproc` namespace and legacy top-level exports;
+missing functions skip individual cells without requiring a dependency upgrade. Native HSV
+uses 0–255 channels; Lab uses normalized RGB; `ycbcr_from_rgb` returns Y/Cr/Cb. Normalization
+receives mean/std multiplied by 255 because it casts bytes without rescaling. Warp borders,
+demosaicing edges and CLAHE rounding can differ; suite docstrings and parity tests record these.
+All `kornia-rs` columns are CPU loops, including in a `--device cuda` run. The wheel also has
+CUDA APIs, but these need separate device-resident columns: their accepted dtypes and borders
+differ from the NumPy paths. `features.match_descriptors` is a binary Hamming matcher and is
+not a counterpart to these float-descriptor rows; `imgproc.Sift.match` is a possible future
+baseline after its ratio/mutuality semantics are checked. There is no exposed image remap or
+depth-backprojection counterpart in this wheel. The I/O suite already measures Kornia's
+kornia-rs-backed decoding path.
+
See [median parallelism notes](filters/median_parallelism.md) for the CPU/CUDA/MPS
implementation audit and related PyTorch issues and pull requests.
diff --git a/benchmarks/color/flagship.py b/benchmarks/color/flagship.py
index 2f3ca3364..c97b8ab9a 100644
--- a/benchmarks/color/flagship.py
+++ b/benchmarks/color/flagship.py
@@ -15,7 +15,7 @@
# limitations under the License.
#
-"""Flagship color benchmark: kornia.color vs OpenCV, torchvision v2, scikit-image and PIL.
+"""Flagship color benchmark: kornia.color vs OpenCV, torchvision v2, scikit-image, kornia-rs and PIL.
Covers the conversions a pipeline typically pays for β€” the luma reduction, the two perceptual
spaces, a video space and demosaicing β€” not every pair the module exports:
@@ -25,6 +25,7 @@ kornia.color OpenCV (``cv2.cvtColor``) torchvision v2 scik
==================== ============================== ==================== ============= ====================
``rgb_to_grayscale`` ``COLOR_RGB2GRAY`` (uint8) ``rgb_to_grayscale`` ``rgb2gray`` ``convert("L")``
``rgb_to_hsv`` ``COLOR_RGB2HSV_FULL`` (uint8) β€” ``rgb2hsv`` ``convert("HSV")``
+``hsv_to_rgb`` ``COLOR_HSV2RGB`` (float32) β€” ``hsv2rgb`` ``convert("RGB")``
``rgb_to_lab`` ``COLOR_RGB2Lab`` (float32) β€” ``rgb2lab`` β€”
``rgb_to_ycbcr`` ``COLOR_RGB2YCrCb`` (uint8) β€” ``rgb2ycbcr`` ``convert("YCbCr")``
``raw_to_rgb`` ``COLOR_BayerBG2RGB`` (uint8) β€” β€” β€”
@@ -33,7 +34,12 @@ kornia.color OpenCV (``cv2.cvtColor``) torchvision v2 scik
Regimes (see ``benchmarks/README.md``): kornia/torchvision run a batched float BCHW tensor on CPU
or GPU and kornia is differentiable; OpenCV and PIL run single uint8 HWC images on CPU in a Python
loop, their native regime, except Lab, which OpenCV computes on float32 input so its output is real
-CIE Lab rather than the 8-bit rescaling; scikit-image runs normalized float HWC images per image.
+CIE Lab rather than the 8-bit rescaling; HSV-to-RGB also uses float32 OpenCV input;
+scikit-image runs normalized float HWC images per image. kornia-rs also runs a CPU per-image
+loop: grayscale, YCbCr and Bayer use uint8; Lab uses normalized float32 RGB, and both HSV
+conversions use float32 RGB/HSV channels in [0,255] (hue encodes a full turn). Its native
+``ycbcr_from_rgb`` output is ordered Y,Cr,Cb. Its Bayer pattern is ``rggb``, matching CFA.BG;
+border interpolation differs. All Rust inputs are prepared outside timing.
PIL receives ready-made ``Image`` objects, as kornia receives a ready-made tensor. OpenCV
parallelizes ``cvtColor`` over rows, which a single 256x256 image barely feeds, so the pointwise
conversions also get an ``opencv (stacked)`` column: one call on the whole batch viewed as a
@@ -43,7 +49,9 @@ chroma channels, 8-bit HSV and YCbCr are rescaled to 0-255, scikit-image's ``rgb
16-235 studio range, and kornia's hue is in radians. OpenCV's Bayer pattern names are shifted by
one pixel relative to kornia's ``CFA`` names; the ``raw_to_rgb`` row times bilinear demosaicing of
the same single-channel mosaic in both. These are throughput comparisons, not output-equivalent
-ones. Throughput is img/s.
+ones. The inverse HSV row prepares inputs outside timing: hue is radians for kornia,
+turns for scikit-image, degrees for OpenCV float32, and 0-255 for kornia-rs and PIL's quantized HSV images;
+saturation/value are [0, 1] except kornia-rs/PIL's 0-255. Throughput is img/s.
Usage:
python benchmarks/color/flagship.py --batches 1,8,32 --size 256 --device cpu
@@ -72,6 +80,7 @@ from common import (
finish_run,
image_batch,
image_row_fields,
+ kornia_rs_fn,
optional_import,
run_batch_sweep,
setup_run,
@@ -80,7 +89,16 @@ from common import (
import kornia.color as KC
-OPS = ("rgb_to_grayscale", "rgb_to_hsv", "rgb_to_lab", "rgb_to_ycbcr", "raw_to_rgb")
+OPS = ("rgb_to_grayscale", "rgb_to_hsv", "hsv_to_rgb", "rgb_to_lab", "rgb_to_ycbcr", "raw_to_rgb")
+
+RS_OPS = {
+ "rgb_to_grayscale": "gray_from_rgb",
+ "rgb_to_hsv": "hsv_from_rgb",
+ "hsv_to_rgb": "rgb_from_hsv",
+ "rgb_to_lab": "lab_from_rgb",
+ "rgb_to_ycbcr": "ycbcr_from_rgb",
+ "raw_to_rgb": "rgb_from_bayer",
+}
def build_ops(
@@ -99,6 +117,7 @@ def build_ops(
) -> tuple[dict[str, dict[str, Backend]], dict[str, str]]:
"""Build {op: {backend: zero-arg callable}}; each callable converts the whole batch once."""
imgs_u8, batch_f = image_batch(b, h, w, device, dtype)
+ imgs_f255 = [im.astype(np.float32) for im in imgs_u8]
imgs_f = [im.astype(np.float32) / 255.0 for im in imgs_u8]
# One sample per pixel, as a sensor delivers it: the green plane stands in for the mosaic.
raws_u8 = [np.ascontiguousarray(im[..., 1]) for im in imgs_u8]
@@ -125,12 +144,17 @@ def build_ops(
def pil_loop(mode: str) -> Backend:
return (lambda: [im.convert(mode) for im in pil_imgs]) if pil else None
+ def rs_loop(fn_name: str, images: list[np.ndarray], *args: object) -> Backend:
+ fn = kornia_rs_fn(fn_name)
+ return (lambda: [fn(im, *args) for im in images]) if fn else None
+
if include("rgb_to_grayscale"):
row = kornia_row("rgb_to_grayscale", KC.rgb_to_grayscale, batch_f)
row["torchvision v2"] = (lambda: tvf.rgb_to_grayscale(batch_f)) if tvf else None
row["opencv"] = cv_loop(cv2.COLOR_RGB2GRAY, imgs_u8) if cv2 else None
row["opencv (stacked)"] = cv_stacked(cv2.COLOR_RGB2GRAY, stacked_u8) if cv2 else None
row["scikit-image"] = sk_loop("rgb2gray")
+ row["kornia-rs"] = rs_loop("gray_from_rgb", imgs_u8)
row["PIL"] = pil_loop("L")
ops["rgb_to_grayscale"] = row
@@ -139,14 +163,35 @@ def build_ops(
row["opencv"] = cv_loop(cv2.COLOR_RGB2HSV_FULL, imgs_u8) if cv2 else None
row["opencv (stacked)"] = cv_stacked(cv2.COLOR_RGB2HSV_FULL, stacked_u8) if cv2 else None
row["scikit-image"] = sk_loop("rgb2hsv")
+ row["kornia-rs"] = rs_loop("hsv_from_rgb", imgs_f255)
row["PIL"] = pil_loop("HSV")
ops["rgb_to_hsv"] = row
+ if include("hsv_to_rgb"):
+ # Prepare one HSV image in each library's native units outside the timed call.
+ hsv_radians = KC.rgb_to_hsv(batch_f)
+ hsv_turns = hsv_radians.float().cpu().permute(0, 2, 3, 1).numpy().copy()
+ hsv_turns[..., 0] /= 2 * np.pi
+ hsv_degrees = hsv_turns.copy()
+ hsv_degrees[..., 0] *= 360
+ hsv_rs = [np.ascontiguousarray(im * 255) for im in hsv_turns]
+ hsv_cv = [np.ascontiguousarray(im) for im in hsv_degrees]
+ hsv_stacked = hsv_degrees.reshape(b * h, w, 3)
+ hsv_pil = [pil.fromarray(np.rint(im * 255).astype(np.uint8), mode="HSV") for im in hsv_turns] if pil else []
+ row = kornia_row("hsv_to_rgb", KC.hsv_to_rgb, hsv_radians)
+ row["opencv"] = cv_loop(cv2.COLOR_HSV2RGB, hsv_cv) if cv2 else None
+ row["opencv (stacked)"] = cv_stacked(cv2.COLOR_HSV2RGB, hsv_stacked) if cv2 else None
+ row["scikit-image"] = (lambda: [skc.hsv2rgb(im) for im in hsv_turns]) if skc else None
+ row["kornia-rs"] = rs_loop("rgb_from_hsv", hsv_rs)
+ row["PIL"] = (lambda: [im.convert("RGB") for im in hsv_pil]) if pil else None
+ ops["hsv_to_rgb"] = row
+
if include("rgb_to_lab"):
row = kornia_row("rgb_to_lab", KC.rgb_to_lab, batch_f)
row["opencv"] = cv_loop(cv2.COLOR_RGB2Lab, imgs_f) if cv2 else None
row["opencv (stacked)"] = cv_stacked(cv2.COLOR_RGB2Lab, stacked_f) if cv2 else None
row["scikit-image"] = sk_loop("rgb2lab")
+ row["kornia-rs"] = rs_loop("lab_from_rgb", imgs_f)
ops["rgb_to_lab"] = row
if include("rgb_to_ycbcr"):
@@ -154,12 +199,15 @@ def build_ops(
row["opencv"] = cv_loop(cv2.COLOR_RGB2YCrCb, imgs_u8) if cv2 else None
row["opencv (stacked)"] = cv_stacked(cv2.COLOR_RGB2YCrCb, stacked_u8) if cv2 else None
row["scikit-image"] = sk_loop("rgb2ycbcr")
+ row["kornia-rs"] = rs_loop("ycbcr_from_rgb", imgs_u8)
row["PIL"] = pil_loop("YCbCr")
ops["rgb_to_ycbcr"] = row
if include("raw_to_rgb"):
row = kornia_row("raw_to_rgb", KC.raw_to_rgb, raw_f, KC.CFA.BG)
row["opencv"] = cv_loop(cv2.COLOR_BayerBG2RGB, raws_u8) if cv2 else None
+ raws_rs = [im[..., None] for im in raws_u8]
+ row["kornia-rs"] = rs_loop("rgb_from_bayer", raws_rs, "rggb")
ops["raw_to_rgb"] = row
return ops, kornia_row.compile_failures
@@ -182,6 +230,12 @@ def main() -> None:
(cv2, "opencv", cv2_error),
(pil, "PIL", pil_error),
]
+ missing = [(name, err) for lib, name, err in libs if lib is None]
+ missing.extend(
+ (f"kornia-rs/{op}", f"{name} unavailable")
+ for op, name in RS_OPS.items()
+ if (args.ops is None or op in args.ops) and kornia_rs_fn(name) is None
+ )
meta = start_run(
"flagship color",
args,
@@ -190,11 +244,14 @@ def main() -> None:
regimes=[
(
"kornia/torchvision: batched float BCHW; opencv/PIL: uint8 HWC per-image loop (CPU), "
- "opencv Lab on float32; scikit-image: normalized float HWC per-image loop"
+ "opencv Lab and HSV-to-RGB on float32; scikit-image: normalized float HWC per-image loop"
),
+ "HSV-to-RGB: prebuilt HSV, hue radians (kornia), turns (scikit-image), degrees (OpenCV), 0-255 (PIL/Rust)",
+ "kornia-rs (CPU): uint8 gray/YCbCr/Bayer; float32 Lab RGB [0,1], HSV RGB/HSV [0,255]; Y,Cr,Cb output",
+ "kornia-rs Bayer: rggb (CFA.BG), bilinear with different border interpolation",
"opencv (stacked): one cvtColor on the batch viewed as (B*H, W, 3); PIL: prebuilt Image objects",
],
- missing=[(name, err) for lib, name, err in libs if lib is None],
+ missing=missing,
)
backends = [
"kornia (eager)",
@@ -204,6 +261,7 @@ def main() -> None:
"opencv",
"opencv (stacked)",
"PIL",
+ "kornia-rs",
]
results = run_batch_sweep(
batch_list(args),
diff --git a/benchmarks/common.py b/benchmarks/common.py
index 559efeb38..bc63743f6 100644
--- a/benchmarks/common.py
+++ b/benchmarks/common.py
@@ -150,6 +150,7 @@ def run_metadata(device: torch.device) -> dict[str, Any]:
"device": str(device),
"torch_num_threads": torch.get_num_threads(),
"opencv_num_threads": opencv_num_threads,
+ "rayon_num_threads_requested": os.environ.get("RAYON_NUM_THREADS"),
"opencv": _optional_version("cv2"),
"poselib": _optional_version("poselib"),
"torchvision": _optional_version("torchvision"),
@@ -405,6 +406,16 @@ Backend = Optional[Callable[[], object]]
REPO_ROOT = Path(__file__).resolve().parents[1]
+def kornia_rs_fn(name: str) -> Optional[Callable[..., object]]:
+ """Resolve an optional public image operation in new and legacy wheel layouts."""
+ module, _ = optional_import("kornia_rs")
+ if module is None:
+ return None
+ namespace = getattr(module, "imgproc", module)
+ fn = getattr(namespace, name, getattr(module, name, None))
+ return fn if callable(fn) else None
+
+
def optional_import(name: str) -> tuple[Optional[ModuleType], Optional[str]]:
"""Import an optional baseline library, returning ``(module, None)`` or ``(None, reason)``."""
try:
@@ -461,6 +472,10 @@ def setup_run(
) -> tuple[torch.device, torch.dtype, Optional[Callable[[], None]]]:
"""Thread counts, CPU warm-up and pinned seeds; returns ``(device, dtype, sync)``.
+ ``--threads`` also requests the Rayon pool size used by kornia-rs. Run each CLI in a fresh
+ process: Rayon reads RAYON_NUM_THREADS only when its global pool is first initialized.
+ Metadata records the requested value, not an observed count.
+
``--threads`` pins OpenCV as well as torch when OpenCV is installed. Left alone, OpenCV uses
every core while torch uses ``--threads``, and the header would report only torch's count.
Some OpenCV builds ignore the request (the GCD backend of the macOS wheels); ``start_run``
@@ -470,6 +485,7 @@ def setup_run(
``sync`` is the MPS synchronize for ``time_us`` (``blocked_autorange`` already syncs CUDA). The
CPU warm-up runs on accelerator runs too, because they still time CPU-only baselines.
"""
+ os.environ["RAYON_NUM_THREADS"] = str(args.threads)
torch.set_num_threads(args.threads)
cv2, _ = optional_import("cv2") if opencv else (None, None)
if cv2 is not None:
diff --git a/benchmarks/contrib/flagship.py b/benchmarks/contrib/flagship.py
index 03d6a6c1c..1f789cd89 100644
--- a/benchmarks/contrib/flagship.py
+++ b/benchmarks/contrib/flagship.py
@@ -15,7 +15,7 @@
# limitations under the License.
#
-"""Flagship contrib benchmark: kornia.contrib binary-image ops vs OpenCV, scikit-image and SciPy.
+"""Flagship contrib benchmark: kornia.contrib binary-image ops vs OpenCV, scikit-image, SciPy and kornia-rs.
``kornia.contrib`` mixes model wrappers (detectors, super-resolution, ViTs) that need downloaded
weights with classic binary-image operations. This suite covers the latter; the dedicated
@@ -33,7 +33,7 @@ Regimes (see ``benchmarks/README.md``): kornia runs a batched float B1HW mask on
OpenCV, scikit-image and SciPy run single masks on CPU in a Python loop, their native regime. The
mask is thresholded Gaussian-blurred noise (about 30% foreground, blobs of varying size and
shape), the same for every backend. Connected components are exact 8-connected labelings in all
-three columns; kornia's default ``connected_components`` is left out because its fixed pooling
+labeling columns; kornia's default ``connected_components`` is left out because its fixed pooling
budget does not guarantee a correct partition (see ``connected_components.md``). The distance
transforms differ in accuracy: kornia's is a cascaded-convolution approximation
(``kernel_size=3``), OpenCV's a 5x5 chamfer approximation, and SciPy's exact. kornia measures the
@@ -41,7 +41,10 @@ distance to the nearest foreground pixel, OpenCV and SciPy to the nearest zero,
receive the inverted mask and all three answer the same question. The labelers get the mask in
their fastest input type, converted outside the timed call: ``uint8`` for OpenCV and ``bool`` for
scikit-image and SciPy (scikit-image's ``label`` takes a much faster path on ``bool`` and returns
-the same labels). Throughput is img/s.
+the same labels). kornia-rs 0.2+ adds an exact 8-connected CPU labeler, using prebuilt contiguous
+uint8 HWC1 masks and returning native component counts and int32 labels. Label IDs and whether
+counts include the background are backend conventions; the foreground partition is the comparison.
+Its column stays on CPU even when Kornia runs on CUDA or MPS. Throughput is img/s.
Usage:
python benchmarks/contrib/flagship.py --batches 1,8,32 --size 256 --device cpu
@@ -69,6 +72,7 @@ from common import (
batch_list,
finish_run,
image_row_fields,
+ kornia_rs_fn,
optional_import,
run_batch_sweep,
setup_run,
@@ -121,6 +125,9 @@ def build_ops(
row["opencv"] = (lambda: [cv2.connectedComponents(m, connectivity=8) for m in masks_u8]) if cv2 else None
row["scikit-image"] = (lambda: [skmeasure.label(m, connectivity=2) for m in masks_bool]) if skmeasure else None
row["SciPy"] = (lambda: [ndimage.label(m, structure=connectivity8) for m in masks_bool]) if ndimage else None
+ rs_label = kornia_rs_fn("connected_components")
+ rs_masks = [np.ascontiguousarray(m[..., None]) for m in masks_u8]
+ row["kornia-rs"] = (lambda: [rs_label(m, connectivity=8) for m in rs_masks]) if rs_label else None
ops["connected_components_union_find"] = row
if include("distance_transform"):
@@ -141,8 +148,14 @@ def main() -> None:
cv2, cv2_error = optional_import("cv2")
skmeasure, skmeasure_error = optional_import("skimage.measure")
ndimage, ndimage_error = optional_import("scipy.ndimage")
-
- libs = [(skmeasure, "scikit-image", skmeasure_error), (ndimage, "SciPy", ndimage_error), (cv2, "opencv", cv2_error)]
+ krs, krs_error = optional_import("kornia_rs")
+
+ libs = [
+ (skmeasure, "scikit-image", skmeasure_error),
+ (ndimage, "SciPy", ndimage_error),
+ (cv2, "opencv", cv2_error),
+ (krs, "kornia-rs", krs_error),
+ ]
meta = start_run(
"flagship contrib",
args,
@@ -152,11 +165,19 @@ def main() -> None:
(
"kornia: batched float B1HW mask; opencv/scikit-image/SciPy: per-image loop (CPU), "
"uint8 masks except bool for scikit-image and SciPy labeling"
- )
+ ),
+ "kornia-rs: CPU per-image 8-connected labeling, prebuilt uint8 HWC1; native count and int32 labels",
],
- missing=[(name, err) for lib, name, err in libs if lib is None],
+ missing=[(name, err) for lib, name, err in libs if lib is None]
+ + (
+ [("kornia-rs/connected_components_union_find", "connected_components unavailable")]
+ if krs is not None
+ and (args.ops is None or "connected_components_union_find" in args.ops)
+ and kornia_rs_fn("connected_components") is None
+ else []
+ ),
)
- backends = ["kornia (eager)", "kornia (compiled)", "scikit-image", "SciPy", "opencv"]
+ backends = ["kornia (eager)", "kornia (compiled)", "scikit-image", "SciPy", "opencv", "kornia-rs"]
results = run_batch_sweep(
batch_list(args),
lambda b: build_ops(
diff --git a/benchmarks/enhance/flagship.py b/benchmarks/enhance/flagship.py
index 382b7f415..f9bc728c1 100644
--- a/benchmarks/enhance/flagship.py
+++ b/benchmarks/enhance/flagship.py
@@ -54,7 +54,10 @@ runs on float here, the documented regime; on ``uint8`` it uses a lookup table a
faster, which the OpenCV LUT cell represents. ``adjust_saturation`` is not the same algorithm
across columns: kornia scales S in HSV space and converts back, while torchvision and PIL blend
with the grayscale image (kornia's ``adjust_saturation_with_gray_subtraction``); the row times each
-library's saturation adjustment as users call it. Throughput is img/s.
+library's saturation adjustment as users call it. kornia-rs uses uint8 HWC input on CPU;
+normalization casts bytes to float32 without rescaling, so its mean/std are multiplied by 255. Equalize and
+CLAHE process all three channels separately, including contiguous channel copies and concatenation
+inside timing, with the same clip limit and grid as OpenCV; CLAHE can round one byte differently. Throughput is img/s.
Usage:
python benchmarks/enhance/flagship.py --batches 1,8,32 --size 256 --device cpu
@@ -84,6 +87,7 @@ from common import (
finish_run,
image_batch,
image_row_fields,
+ kornia_rs_fn,
optional_import,
run_batch_sweep,
setup_run,
@@ -126,6 +130,13 @@ def build_ops(
def cv_per_channel(fn: Callable[[np.ndarray], np.ndarray]) -> Backend:
return lambda: [cv2.merge([fn(c) for c in cv2.split(im)]) for im in imgs_u8]
+ def rs_per_channel(fn: Callable[..., object], **kwargs: object) -> Backend:
+ # Keep splitting/copying/merging inside the timed RGB operation, like the OpenCV column.
+ return lambda: [
+ np.concatenate([fn(np.ascontiguousarray(im[..., c : c + 1]), **kwargs) for c in range(3)], axis=-1)
+ for im in imgs_u8
+ ]
+
def sk_per_channel(fn: Callable[[np.ndarray], np.ndarray]) -> Backend:
return lambda: [np.stack([fn(im[..., c]) for c in range(im.shape[-1])], axis=-1) for im in imgs_f]
@@ -140,6 +151,9 @@ def build_ops(
row = kornia_row("normalize", KE.normalize, batch_f, mean, std)
row["torchvision v2"] = (lambda: tvf.normalize(batch_f, list(MEAN), list(STD))) if tvf else None
row["albumentations"] = alb(A.Normalize(mean=MEAN, std=STD, max_pixel_value=255.0, p=1.0)) if A else None
+ rs_normalize = kornia_rs_fn("normalize_mean_std")
+ rs_mean, rs_std = tuple(v * 255 for v in MEAN), tuple(v * 255 for v in STD)
+ row["kornia-rs"] = (lambda: [rs_normalize(im, rs_mean, rs_std) for im in imgs_u8]) if rs_normalize else None
ops["normalize"] = row
if include("adjust_gamma"):
@@ -174,6 +188,8 @@ def build_ops(
row["scikit-image"] = sk_per_channel(ske.equalize_hist) if ske else None
if pil and pil_ops:
row["PIL"] = lambda: [pil_ops.equalize(im) for im in pil_imgs]
+ rs_equalize = kornia_rs_fn("equalize_hist")
+ row["kornia-rs"] = rs_per_channel(rs_equalize) if rs_equalize else None
ops["equalize"] = row
if include("equalize_clahe"):
@@ -189,6 +205,8 @@ def build_ops(
row["scikit-image"] = lambda: [
ske.equalize_adapthist(im, kernel_size=kernel, clip_limit=CLAHE_CLIP / 256) for im in imgs_f
]
+ rs_clahe = kornia_rs_fn("clahe")
+ row["kornia-rs"] = rs_per_channel(rs_clahe, clip_limit=CLAHE_CLIP, grid_size=CLAHE_GRID) if rs_clahe else None
ops["equalize_clahe"] = row
return ops, kornia_row.compile_failures
@@ -222,9 +240,19 @@ def main() -> None:
"kornia/torchvision: batched float BCHW (torchvision equalize: uint8 BCHW); "
"albumentations/opencv/PIL: uint8 HWC per-image loop (CPU); scikit-image: normalized float HWC loop"
),
+ "kornia-rs: uint8 HWC CPU loop; normalize produces float32; equalize/CLAHE split and merge all channels",
"PIL: prebuilt Image objects; albumentations CLAHE equalizes only L in Lab, the others all 3 channels",
],
- missing=[(label, imported[key][1]) for key, label in labels.items() if libs[key] is None],
+ missing=[(label, imported[key][1]) for key, label in labels.items() if libs[key] is None]
+ + [
+ (f"kornia-rs/{op}", f"{fn} unavailable")
+ for op, fn in (
+ ("normalize", "normalize_mean_std"),
+ ("equalize", "equalize_hist"),
+ ("equalize_clahe", "clahe"),
+ )
+ if (args.ops is None or op in args.ops) and kornia_rs_fn(fn) is None
+ ],
)
backends = [
"kornia (eager)",
@@ -234,6 +262,7 @@ def main() -> None:
"scikit-image",
"opencv",
"PIL",
+ "kornia-rs",
]
results = run_batch_sweep(
batch_list(args),
diff --git a/benchmarks/feature/flagship.py b/benchmarks/feature/flagship.py
index e898d5ea8..025f6ae36 100644
--- a/benchmarks/feature/flagship.py
+++ b/benchmarks/feature/flagship.py
@@ -15,7 +15,7 @@
# limitations under the License.
#
-"""Flagship feature benchmark: kornia.feature vs OpenCV and scikit-image.
+"""Flagship feature benchmark: kornia.feature vs OpenCV, scikit-image and kornia-rs.
Covers the local-feature pipeline end to end β€” a corner response, a full detector + descriptor,
and descriptor matching β€” rather than every detector and descriptor the module exports:
@@ -27,6 +27,9 @@ kornia.feature OpenCV (per-image loop, CPU) scikit
``gftt_response`` ``cv2.cornerMinEigenVal(blockSize=7, ksize=3)`` ``corner_shi_tomasi(sigma=1)``
``SIFTFeature`` ``cv2.SIFT_create(nfeatures=512).detectAndCompute`` β€”
``match_snn`` ``BFMatcher(NORM_L2).knnMatch(k=2)`` + ratio test β€”
+``match_mnn`` ``BFMatcher(NORM_L2, crossCheck=True).match`` β€”
+``match_smnn`` two ``knnMatch(k=2)`` calls + ratio/mutual filters β€”
+``match_smnn_batched`` same per-pair OpenCV loop as ``match_smnn`` β€”
=================== =================================================== ==============================
Regimes (see ``benchmarks/README.md``): kornia runs a batched float B1HW tensor on CPU or GPU and
@@ -41,11 +44,22 @@ detector accepts one image per call, so its SIFT row loops over the batch like O
images use ``local_features.py`` and ``sift_scale_space.py``; learned detectors and descriptors
(DISK, ALIKED, HardNet, ...) need downloaded weights and are measured there too.
-``match_snn`` matches 2048 128-d descriptors against 2048, with a 0.8 ratio test, one pair per
-batch element; neither library batches pairs, so both loop in Python. The OpenCV column includes
-the list comprehension that applies the ratio test to ``knnMatch``'s result, which is how the API
-is used. Throughput counts images for the first three rows and descriptor-set pairs for
-``match_snn``; the JSON ``units`` is therefore ``items/s``.
+kornia-rs 0.2+ adds a CPU SIFT detect+describe loop with a persistent detector and the same
+512-feature budget. Its prebuilt float32 HWC1 inputs contain the same rounded 0..255 pixels
+as OpenCV's uint8 inputs; normalizing them to 0..1 would change SIFT's contrast threshold.
+It returns native host keypoints and float32 SIFT descriptors, like OpenCV; Kornia defaults to
+RootSIFT normalization. The column stays on CPU when
+Kornia runs on CUDA or MPS; GPU residency and descriptor matching are not measured here.
+
+Matching rows share the same 2048-by-2048 unit-normalized 128-d descriptor pairs: the second
+set is a seeded noisy permutation of the first, so the ratio tests accept and reject matches.
+SNN uses an inclusive 0.8 ratio test, MNN uses mutual nearest neighbors, and SMNN requires both
+mutuality and the ratio test in both directions. Kornia's unbatched functions and OpenCV loop
+over pairs in Python; ``match_smnn_batched`` processes all pairs together (distance storage
+scales as B*2048*2048). OpenCV includes Python ratio filtering and mutual-pair intersection;
+its inputs are prebuilt float32 arrays. Matches have the same index semantics away from distance
+ties; native output containers and quality scores differ. Throughput counts images for the
+first three rows and descriptor-set pairs for every matching row; JSON units are ``items/s``.
Usage:
python benchmarks/feature/flagship.py --batches 1,8,32 --size 256 --device cpu
@@ -58,7 +72,7 @@ import argparse
import sys
from pathlib import Path
from types import ModuleType
-from typing import Optional
+from typing import Any, Optional
import numpy as np
import torch
@@ -73,6 +87,7 @@ from common import (
batch_list,
finish_run,
image_row_fields,
+ kornia_rs_fn,
optional_import,
run_batch_sweep,
setup_run,
@@ -82,7 +97,7 @@ from common import (
import kornia.feature as KF
from kornia.filters import gaussian_blur2d
-OPS = ("harris_response", "gftt_response", "SIFTFeature", "match_snn")
+OPS = ("harris_response", "gftt_response", "SIFTFeature", "match_snn", "match_mnn", "match_smnn", "match_smnn_batched")
NUM_FEATURES, NUM_DESCRIPTORS, DESCRIPTOR_DIM, SNN_RATIO = 512, 2048, 128, 0.8
@@ -105,8 +120,33 @@ def descriptor_pairs(b: int) -> tuple[torch.Tensor, torch.Tensor]:
return d1, torch.nn.functional.normalize(noisy, dim=-1)
-def match_pairs(d1: torch.Tensor, d2: torch.Tensor) -> list[tuple[torch.Tensor, torch.Tensor]]:
- return [KF.match_snn(d1[i], d2[i], SNN_RATIO) for i in range(d1.shape[0])]
+def match_pairs(d1: torch.Tensor, d2: torch.Tensor, name: str = "match_snn") -> list[tuple[torch.Tensor, torch.Tensor]]:
+ matcher = getattr(KF, name)
+ return [
+ matcher(d1[i], d2[i]) if name == "match_mnn" else matcher(d1[i], d2[i], SNN_RATIO) for i in range(d1.shape[0])
+ ]
+
+
+def opencv_matches(matcher: Any, d1: np.ndarray, d2: np.ndarray, name: str) -> list[Any]:
+ """Native BF matching plus inclusive ratio filtering and, for SMNN, reverse consistency."""
+ if name == "match_mnn":
+ return list(matcher.match(d1, d2))
+ forward = matcher.knnMatch(d1, d2, k=2)
+ # Zero second-neighbor distance is an undefined ratio, rejected by Kornia too.
+ accepted = [
+ pair[0]
+ for pair in forward
+ if len(pair) == 2 and pair[1].distance > 0 and pair[0].distance <= SNN_RATIO * pair[1].distance
+ ]
+ if name == "match_snn":
+ return accepted
+ reverse = matcher.knnMatch(d2, d1, k=2)
+ reverse_pairs = {
+ (pair[0].trainIdx, pair[0].queryIdx)
+ for pair in reverse
+ if len(pair) == 2 and pair[1].distance > 0 and pair[0].distance <= SNN_RATIO * pair[1].distance
+ }
+ return [match for match in accepted if (match.queryIdx, match.trainIdx) in reverse_pairs]
def build_ops(
@@ -161,19 +201,29 @@ def build_ops(
if cv2:
cv_sift = cv2.SIFT_create(nfeatures=NUM_FEATURES)
row["opencv"] = lambda: [cv_sift.detectAndCompute(im, None) for im in imgs_u8]
+ rs_sift_type = kornia_rs_fn("Sift")
+ row["kornia-rs"] = None
+ if rs_sift_type is not None:
+ rs_sift = rs_sift_type(n_features=NUM_FEATURES)
+ rs_images = [np.ascontiguousarray(im[..., None], dtype=np.float32) for im in imgs_u8]
+ row["kornia-rs"] = lambda: [rs_sift.detect_and_compute(im) for im in rs_images]
ops["SIFTFeature"] = row
- if include("match_snn"):
- row = kornia_row("match_snn", match_pairs, d1_dev, d2_dev)
+ for name in ("match_snn", "match_mnn", "match_smnn", "match_smnn_batched"):
+ if not include(name):
+ continue
+ if name == "match_smnn_batched":
+ row = kornia_row(name, KF.match_smnn_batched, d1_dev, d2_dev, SNN_RATIO)
+ else:
+ row = kornia_row(name, match_pairs, d1_dev, d2_dev, name)
if cv2:
- matcher = cv2.BFMatcher(cv2.NORM_L2)
+ matcher = cv2.BFMatcher(cv2.NORM_L2, crossCheck=name == "match_mnn")
- def cv_match(i: int) -> list[object]:
- knn = matcher.knnMatch(d1_np[i], d2_np[i], k=2)
- return [m for m, n in knn if m.distance < SNN_RATIO * n.distance]
+ def cv_match_pairs(matcher: Any = matcher, name: str = name) -> list[list[Any]]:
+ return [opencv_matches(matcher, d1_np[i], d2_np[i], name) for i in range(b)]
- row["opencv"] = lambda: [cv_match(i) for i in range(b)]
- ops["match_snn"] = row
+ row["opencv"] = cv_match_pairs
+ ops[name] = row
return ops, kornia_row.compile_failures
@@ -186,8 +236,9 @@ def main() -> None:
cv2, cv2_error = optional_import("cv2")
skf, skf_error = optional_import("skimage.feature")
+ krs, krs_error = optional_import("kornia_rs")
- libs = [(skf, "scikit-image", skf_error), (cv2, "opencv", cv2_error)]
+ libs = [(skf, "scikit-image", skf_error), (cv2, "opencv", cv2_error), (krs, "kornia-rs", krs_error)]
meta = start_run(
"flagship feature",
args,
@@ -196,12 +247,20 @@ def main() -> None:
regimes=[
(
"kornia: batched float B1HW; opencv/scikit-image: grayscale per-image loop (CPU); "
- "items = images, except match_snn = descriptor-set pairs"
- )
+ "items = images, except matching rows = descriptor-set pairs; descriptors float32 in OpenCV"
+ ),
+ "kornia-rs SIFT: CPU per-image loop, prebuilt float32 HWC1 0..255, persistent detector, 512 features",
+ "matching: same 2048x2048 128-d pairs; inclusive 0.8 SNN/SMNN ratios; MNN uses cross-check",
+ "match_smnn_batched batches pairs in Kornia; all other matching cells loop over pairs",
],
- missing=[(name, err) for lib, name, err in libs if lib is None],
+ missing=[(name, err) for lib, name, err in libs if lib is None]
+ + (
+ [("kornia-rs/SIFTFeature", "Sift unavailable")]
+ if krs is not None and (args.ops is None or "SIFTFeature" in args.ops) and kornia_rs_fn("Sift") is None
+ else []
+ ),
)
- backends = ["kornia (eager)", "kornia (compiled)", "scikit-image", "opencv"]
+ backends = ["kornia (eager)", "kornia (compiled)", "scikit-image", "opencv", "kornia-rs"]
results = run_batch_sweep(
batch_list(args),
lambda b: build_ops(
diff --git a/benchmarks/filters/flagship.py b/benchmarks/filters/flagship.py
index 7c7eba556..d256d110a 100644
--- a/benchmarks/filters/flagship.py
+++ b/benchmarks/filters/flagship.py
@@ -24,6 +24,7 @@ Covers the core image filters with fixed nominal parameters across backends
kornia.filters OpenCV (uint8 HWC per-image loop) others
======================== ================================= ====================================================
gaussian_blur2d cv2.GaussianBlur albumentations, torchvision, skimage, kornia-rs, PIL
+spatial_gradient cv2.Sobel(dx/dy), float32 scale=1/8, replicate border
sobel cv2.Sobel(dx/dy) -> cv2.magnitude skimage, kornia-rs
laplacian cv2.Laplacian skimage
median_blur cv2.medianBlur albumentations, skimage, kornia-rs, PIL
@@ -50,7 +51,9 @@ Canny thresholds are each library's standard
defaults β€” kornia 0.1/0.2 on the unnormalised Sobel magnitude of [0, 1] floats, OpenCV 100/200 on uint8
gradients β€” the domains differ, so that row compares regimes, not identical outputs. kornia's canny converts to
grayscale internally per its definition; the OpenCV canny loop therefore includes ``cv2.cvtColor``
-(sobel runs per-channel in both). Throughput is img/s.
+(sobel runs per-channel in both). ``spatial_gradient`` returns normalized x/y Sobel derivatives
+per channel; OpenCV receives prepared float32 [0, 1] images, uses scale=1/8 and replicate padding,
+and returns two HWC arrays per image. Kornia returns (B, C, 2, H, W). Throughput is img/s.
The Laplacian columns are different operators: Kornia uses an L1-normalized all-ones window with
center ``1 - kernel_area``; OpenCV sums second Sobel derivatives and scikit-image's kernel differs
@@ -60,7 +63,10 @@ and scikit-image (``mode='mirror'``), and replicated borders in OpenCV. The scik
mean is a uint8 footprint-based box filter with truncated boundary footprints. These are
native-regime throughput comparisons, not output-equivalent comparisons.
-kornia-rs exposes Gaussian, box and median blur and Sobel in its Python API. The median operator
+kornia-rs Canny includes RGB-to-gray conversion, thresholds 100/200 and L1 gradients, matching
+the OpenCV call scope; its grayscale rounding can differ. These native uint8 thresholds are not
+Kornia's normalized defaults. kornia-rs exposes Gaussian, box and median blur and Sobel in its
+Python API. The median operator
accepts only 3x3 or 5x5 uint8 images and uses replicated borders. Its Sobel is f32 magnitude; its
normalization and borders can differ from Kornia. kornia-rs also exposes a bilateral filter only for
single-channel uint8 images. The grayscale bilateral row converts the common RGB image to
@@ -112,6 +118,7 @@ from common import (
finish_run,
image_batch,
image_row_fields,
+ kornia_rs_fn,
optional_import,
run_batch_sweep,
setup_run,
@@ -123,6 +130,7 @@ import kornia.filters as KF
AVAILABLE_OPS = (
"gaussian_blur2d",
"sobel",
+ "spatial_gradient",
"laplacian",
"median_blur",
"box_blur",
@@ -250,12 +258,7 @@ def build_specialized_ops(
def krs_fn(name: str) -> Optional[Callable[..., object]]:
"""Resolve a kornia-rs function across wheel layouts (imgproc submodule vs top-level)."""
- try:
- import kornia_rs
- except Exception:
- return None
- ns = getattr(kornia_rs, "imgproc", kornia_rs)
- return getattr(ns, name, getattr(kornia_rs, name, None))
+ return kornia_rs_fn(name)
def build_ops(
@@ -319,6 +322,23 @@ def build_ops(
)
ops["gaussian_blur2d"] = row
+ if include("spatial_gradient"):
+ row = kornia_row("spatial_gradient", lambda: KF.spatial_gradient(batch_f, mode="sobel", normalized=True))
+ row["opencv"] = (
+ (
+ lambda: [
+ (
+ cv2.Sobel(im, cv2.CV_32F, 1, 0, ksize=3, scale=1 / 8, borderType=cv2.BORDER_REPLICATE),
+ cv2.Sobel(im, cv2.CV_32F, 0, 1, ksize=3, scale=1 / 8, borderType=cv2.BORDER_REPLICATE),
+ )
+ for im in imgs_f
+ ]
+ )
+ if cv2
+ else None
+ )
+ ops["spatial_gradient"] = row
+
if include("sobel"):
krs_sobel = krs_fn("sobel")
row = kornia_row("sobel", lambda: KF.sobel(batch_f))
@@ -394,7 +414,12 @@ def build_ops(
)
row["albumentations"] = None
row["torchvision v2"] = None
- row["kornia-rs"] = None
+ krs_canny, krs_gray = krs_fn("canny"), krs_fn("gray_from_rgb")
+ row["kornia-rs"] = (
+ (lambda: [krs_canny(krs_gray(im), 100.0, 200.0, l2_gradient=False) for im in imgs_u8])
+ if krs_canny and krs_gray
+ else None
+ )
ops["canny"] = row
ops.update(
@@ -437,9 +462,11 @@ def main() -> None:
regimes=[
(
"kornia/torchvision: batched float BCHW; "
- "albumentations/opencv/kornia-rs/PIL: uint8 HWC per-image loop (CPU), except kornia-rs Sobel float32; "
+ "albumentations/opencv/kornia-rs/PIL: uint8 HWC per-image loop (CPU), "
+ "except kornia-rs Sobel and opencv spatial_gradient float32; "
"scikit-image: normalized float HWC per-image loop except uint8 rank mean"
- )
+ ),
+ "spatial_gradient: normalized x/y Sobel, OpenCV float32 [0,1], scale=1/8, replicate padding",
],
missing=missing,
)
@@ -451,8 +478,9 @@ def main() -> None:
f"# NOTE: scikit-image restoration not available ({skimage_restoration_error}) "
"β€” bilateral rows are skipped"
)
- if krs_fn("gaussian_blur") is None:
- print("# NOTE: kornia-rs filter APIs not available β€” its column is skipped")
+ for name in ("gaussian_blur", "box_blur", "sobel", "median_blur", "bilateral_filter", "canny", "gray_from_rgb"):
+ if krs_fn(name) is None:
+ print(f"# NOTE: kornia-rs/{name} unavailable β€” affected cells are skipped")
backends = [
"kornia (eager)",
diff --git a/benchmarks/geometry/flagship.py b/benchmarks/geometry/flagship.py
index 0ca7d5723..22f9d9180 100644
--- a/benchmarks/geometry/flagship.py
+++ b/benchmarks/geometry/flagship.py
@@ -15,29 +15,44 @@
# limitations under the License.
#
-"""Flagship geometry-op benchmark: kornia vs OpenCV vs torchvision v2.
+"""Flagship geometry-op benchmark: kornia vs OpenCV, torchvision v2 and kornia-rs.
-Covers the differentiated-core ops named by the W3 benchmark plan:
+Covers image warps, point transforms and depth unprojection:
============================= ========================================== ==============
kornia (batched float BCHW) OpenCV (uint8 HWC, per-image Python loop) torchvision v2
============================= ========================================== ==============
``warp_perspective`` ``cv2.warpPerspective`` β€”
``warp_affine`` ``cv2.warpAffine`` β€”
-``rotate`` ``cv2.warpAffine(getRotationMatrix2D)`` ``tvf.rotate``
-``rotate_shared`` ``cv2.warpAffine(getRotationMatrix2D)`` ``tvf.rotate``
+``rotate`` ``cv2.warpAffine`` (prepared matrix) ``tvf.rotate``
+``rotate_shared`` ``cv2.warpAffine`` (prepared matrix) ``tvf.rotate``
``resize`` ``cv2.resize`` ``tvf.resize``
``get_perspective_transform`` ``cv2.getPerspectiveTransform`` (per pair) β€”
+``remap`` ``cv2.remap`` (float32) β€”
+``transform_points`` ``cv2.perspectiveTransform`` (float32) β€”
+``depth_to_3d`` β€” β€”
============================= ========================================== ==============
Regimes (same framing as ``benchmarks/augmentation``): kornia/torchvision run a batched float
tensor on CPU or GPU and kornia is differentiable; OpenCV runs single uint8 images on CPU in
-a Python loop β€” its native regime. Columns are regime comparisons, not apples-to-apples.
+a Python loop β€” its native regime. kornia-rs runs uint8 HWC CPU image loops for resize,
+affine/perspective warps and both rotate rows (via the same precomputed rotation matrix).
+Columns are regime comparisons, not apples-to-apples. Rust's bilinear warps zero samples with
+source coordinates outside [0,W)x[0,H), but clamp the second neighbor inside that domain;
+Kornia/OpenCV instead blend with zero padding at the border. Rust also quantizes interpolation.
+These edge differences are retained, not corrected with extra work in the timed call.
Equal footing: bilinear interpolation, no antialiasing anywhere (torchvision gets an explicit
``antialias=False``), identical transform parameters across backends, pinned seeds.
``rotate`` passes B angle parameters; ``rotate_shared`` passes a singleton angle so Kornia can
reuse one sampling grid. Both use 30 degrees, matching torchvision's shared-angle API.
+``remap`` uses prepared float32 images and pixel maps offset by (+0.25, -0.5), bilinear
+interpolation and zero padding, with ``align_corners=True`` in Kornia. These offsets are exact
+on OpenCV's 1/32 interpolation table; arbitrary offsets can differ. ``transform_points`` applies
+a fixed projective matrix to H*W seeded 2D points per batch item; OpenCV gets float32 point sets.
+``depth_to_3d`` unprojects positive z-depth [0.5, 4.5] with focal length W and centered principal
+point, with no normalization or external baseline. One item means one image, depth map, point
+set (H*W points), or four-correspondence solve, depending on the row.
Usage:
python benchmarks/geometry/flagship.py --batches 1,8,32 --size 256 --device cpu
@@ -66,6 +81,7 @@ from common import (
finish_run,
image_batch,
image_row_fields,
+ kornia_rs_fn,
optional_import,
run_batch_sweep,
setup_run,
@@ -74,7 +90,25 @@ from common import (
import kornia.geometry as KG
-OPS = ("warp_perspective", "warp_affine", "rotate", "rotate_shared", "resize", "get_perspective_transform")
+OPS = (
+ "warp_perspective",
+ "warp_affine",
+ "rotate",
+ "rotate_shared",
+ "resize",
+ "get_perspective_transform",
+ "remap",
+ "transform_points",
+ "depth_to_3d",
+)
+
+RS_OPS = {
+ "warp_perspective": "warp_perspective",
+ "warp_affine": "warp_affine",
+ "rotate": "warp_affine",
+ "rotate_shared": "warp_affine",
+ "resize": "resize",
+}
def build_ops(
@@ -113,6 +147,15 @@ def build_ops(
m_np = m_affine.float().cpu().numpy()
h_np = h_mat.float().cpu().numpy().astype(np.float64)
src_np, dst_np = src_pts32.numpy(), dst_pts32.numpy()
+ # Python sequences are required by the Rust binding; prepare them before timing.
+ m_rs = m_np.reshape(b, 6).tolist()
+ h_rs = h_np.reshape(b, 9).tolist()
+ rotation_center = torch.tensor([[(w - 1) / 2, (h - 1) / 2]], device=device, dtype=dtype)
+ m_rot = KG.get_rotation_matrix2d(rotation_center, angle[:1], scale[:1])[0].float().cpu().numpy()
+ m_rot_rs = m_rot.reshape(6).tolist()
+ rs_affine = kornia_rs_fn("warp_affine")
+ rs_perspective = kornia_rs_fn("warp_perspective")
+ rs_resize = kornia_rs_fn("resize")
kornia_row = KorniaRows(device, do_compile, skip_compile)
ops: dict[str, dict[str, Backend]] = {}
@@ -125,21 +168,33 @@ def build_ops(
row["opencv"] = (
(lambda: [cv2.warpPerspective(im, h_np[i], (w, h)) for i, im in enumerate(imgs_u8)]) if cv2 else None
)
+ row["kornia-rs"] = (
+ (lambda: [rs_perspective(im, h_rs[i], (h, w), "bilinear") for i, im in enumerate(imgs_u8)])
+ if rs_perspective
+ else None
+ )
ops["warp_perspective"] = row
if include("warp_affine"):
row = kornia_row("warp_affine", lambda: KG.warp_affine(batch_f, m_affine, (h, w)))
row["opencv"] = (lambda: [cv2.warpAffine(im, m_np[i], (w, h)) for i, im in enumerate(imgs_u8)]) if cv2 else None
+ row["kornia-rs"] = (
+ (lambda: [rs_affine(im, m_rs[i], (h, w), "bilinear") for i, im in enumerate(imgs_u8)])
+ if rs_affine
+ else None
+ )
ops["warp_affine"] = row
if include("rotate"):
row = kornia_row("rotate", lambda: KG.rotate(batch_f, angle))
if cv2:
- m_rot = cv2.getRotationMatrix2D(((w - 1) / 2, (h - 1) / 2), angle_deg, 1.0)
row["opencv"] = lambda: [cv2.warpAffine(im, m_rot, (w, h)) for im in imgs_u8]
row["torchvision v2"] = (
(lambda: tvf.rotate(batch_f, angle_deg, interpolation=tvf.InterpolationMode.BILINEAR)) if tvf else None
)
+ row["kornia-rs"] = (
+ (lambda: [rs_affine(im, m_rot_rs, (h, w), "bilinear") for im in imgs_u8]) if rs_affine else None
+ )
ops["rotate"] = row
if include("rotate_shared"):
@@ -147,11 +202,13 @@ def build_ops(
shared_angle = angle[:1]
row = kornia_row("rotate_shared", lambda: KG.rotate(batch_f, shared_angle))
if cv2:
- m_rot_shared = cv2.getRotationMatrix2D(((w - 1) / 2, (h - 1) / 2), angle_deg, 1.0)
- row["opencv"] = lambda: [cv2.warpAffine(im, m_rot_shared, (w, h)) for im in imgs_u8]
+ row["opencv"] = lambda: [cv2.warpAffine(im, m_rot, (w, h)) for im in imgs_u8]
row["torchvision v2"] = (
(lambda: tvf.rotate(batch_f, angle_deg, interpolation=tvf.InterpolationMode.BILINEAR)) if tvf else None
)
+ row["kornia-rs"] = (
+ (lambda: [rs_affine(im, m_rot_rs, (h, w), "bilinear") for im in imgs_u8]) if rs_affine else None
+ )
ops["rotate_shared"] = row
if include("resize"):
@@ -159,12 +216,52 @@ def build_ops(
row = kornia_row("resize", lambda: KG.resize(batch_f, dst_size, interpolation="bilinear"))
row["opencv"] = (lambda: [cv2.resize(im, (dst_size[1], dst_size[0])) for im in imgs_u8]) if cv2 else None
row["torchvision v2"] = (lambda: tvf.resize(batch_f, list(dst_size), antialias=False)) if tvf else None
+ row["kornia-rs"] = (
+ (lambda: [rs_resize(im, dst_size, "bilinear", antialias=False) for im in imgs_u8]) if rs_resize else None
+ )
ops["resize"] = row
if include("get_perspective_transform"):
row = kornia_row("get_perspective_transform", lambda: KG.get_perspective_transform(src_pts, dst_pts))
row["opencv"] = (lambda: [cv2.getPerspectiveTransform(src_np[i], dst_np[i]) for i in range(b)]) if cv2 else None
ops["get_perspective_transform"] = row
+ if include("remap"):
+ # Quarter-pixel offsets are represented exactly by OpenCV's 1/32 interpolation table.
+ yy, xx = np.mgrid[:h, :w].astype(np.float32)
+ map_x_np, map_y_np = xx + 0.25, yy - 0.5
+ map_x = torch.from_numpy(map_x_np).to(device=device, dtype=dtype).expand(b, -1, -1)
+ map_y = torch.from_numpy(map_y_np).to(device=device, dtype=dtype).expand(b, -1, -1)
+ imgs_f = [im.astype(np.float32) / 255 for im in imgs_u8]
+ row = kornia_row("remap", lambda: KG.remap(batch_f, map_x, map_y, align_corners=True))
+ row["opencv"] = (
+ (
+ lambda: [
+ cv2.remap(im, map_x_np, map_y_np, cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT) for im in imgs_f
+ ]
+ )
+ if cv2
+ else None
+ )
+ ops["remap"] = row
+
+ if include("transform_points"):
+ points_cpu = torch.rand(b, h * w, 2, generator=gen) * torch.tensor([w, h])
+ transform_cpu = torch.tensor([[1.05, 0.02, 2.0], [-0.01, 0.95, -1.0], [0.0001, -0.0002, 1.0]])
+ transforms = transform_cpu.expand(b, -1, -1).to(device=device, dtype=dtype)
+ points = points_cpu.to(device=device, dtype=dtype)
+ point_arrays = [np.ascontiguousarray(p.numpy()[:, None]) for p in points_cpu]
+ transform_np = transform_cpu.numpy()
+ row = kornia_row("transform_points", KG.transform_points, transforms, points)
+ row["opencv"] = (lambda: [cv2.perspectiveTransform(p, transform_np) for p in point_arrays]) if cv2 else None
+ ops["transform_points"] = row
+
+ if include("depth_to_3d"):
+ depth = 0.5 + 4 * batch_f[:, :1]
+ intrinsics = torch.tensor(
+ [[w, 0.0, (w - 1) / 2], [0.0, w, (h - 1) / 2], [0.0, 0.0, 1.0]], device=device, dtype=dtype
+ ).expand(b, -1, -1)
+ row = kornia_row("depth_to_3d", KG.depth_to_3d, depth, intrinsics)
+ ops["depth_to_3d"] = row
return ops, kornia_row.compile_failures
@@ -177,19 +274,29 @@ def main() -> None:
cv2, cv2_error = optional_import("cv2")
tvf, tvf_error = optional_import("torchvision.transforms.v2.functional")
+ missing = [
+ (name, err) for lib, name, err in [(cv2, "opencv", cv2_error), (tvf, "torchvision", tvf_error)] if lib is None
+ ]
+ missing.extend(
+ (f"kornia-rs/{op}", f"{name} unavailable")
+ for op, name in RS_OPS.items()
+ if (args.ops is None or op in args.ops) and kornia_rs_fn(name) is None
+ )
meta = start_run(
"flagship geometry",
args,
device,
units="items/s",
- regimes=["kornia/torchvision: batched float BCHW; opencv: uint8 HWC per-image loop (CPU)"],
- missing=[
- (name, err)
- for lib, name, err in [(cv2, "opencv", cv2_error), (tvf, "torchvision", tvf_error)]
- if lib is None
+ regimes=[
+ "kornia/torchvision: batched float; opencv: uint8 images except float32 remap/point transforms (CPU)",
+ "kornia-rs (CPU): uint8 HWC loop, bilinear/no antialias; prepared forward matrices; rotate via warp_affine",
+ "Rust warp borders: zero outside [0,W)x[0,H), clamp last neighbor inside; differs from zero-pad blending",
+ "remap: prepared pixel maps (+0.25,-0.5), bilinear, zero padding, align_corners=True",
+ "items = images, depth maps, H*W point sets, or four-correspondence solves; depth_to_3d has no baseline",
],
+ missing=missing,
)
- backends = ["kornia (eager)", "kornia (compiled)", "torchvision v2", "opencv"]
+ backends = ["kornia (eager)", "kornia (compiled)", "torchvision v2", "opencv", "kornia-rs"]
results = run_batch_sweep(
batch_list(args),
lambda b: build_ops(
diff --git a/benchmarks/losses/flagship.py b/benchmarks/losses/flagship.py
index 1661d885a..934cf3ecb 100644
--- a/benchmarks/losses/flagship.py
+++ b/benchmarks/losses/flagship.py
@@ -26,6 +26,8 @@ kornia.losses torchvision task
``binary_focal_loss_with_logits`` ``ops.sigmoid_focal_loss`` dense binary detection
``focal_loss`` β€” 21-class segmentation
``dice_loss`` β€” 21-class segmentation
+``dice_loss_macro`` β€” per-class Dice, present classes
+``dice_loss_weighted`` β€” class-weighted micro Dice
``ssim_loss`` β€” image reconstruction
``total_variation`` β€” image regularization
================================= ====================================== ============================
@@ -35,7 +37,9 @@ device, so every column is the same regime. Classification losses score ``(B, 21
against ``(B, H, W)`` labels; the binary focal loss scores ``(B, 1, H, W)`` logits against
``{0, 1}`` targets with ``alpha=0.25, gamma=2`` and mean reduction in both libraries. ``ssim_loss``
uses an 11x11 window; ``total_variation`` sums over each image and the batch is summed before the
-backward. ``--compile`` compiles the loss function; the backward then runs through AOTAutograd,
+backward. Dice rows cover default micro, macro, and micro with class weights linearly spaced
+from 0.5 to 1.5; all use the same logits and labels. ``--compile`` compiles the loss function;
+the backward then runs through AOTAutograd,
and both are compiled during the untimed warmup. Other libraries' losses are thin wrappers over the
same PyTorch ops and are left out rather than timed as look-alikes. Throughput is img/s.
@@ -73,7 +77,15 @@ from common import (
import kornia.losses as KL
-OPS = ("binary_focal_loss_with_logits", "focal_loss", "dice_loss", "ssim_loss", "total_variation")
+OPS = (
+ "binary_focal_loss_with_logits",
+ "focal_loss",
+ "dice_loss",
+ "dice_loss_macro",
+ "dice_loss_weighted",
+ "ssim_loss",
+ "total_variation",
+)
NUM_CLASSES, ALPHA, GAMMA, WINDOW = 21, 0.25, 2.0, 11
@@ -136,6 +148,15 @@ def build_ops(
if include("dice_loss"):
ops["dice_loss"] = kornia_row("dice_loss", logits, KL.dice_loss, logits, labels)
+ if include("dice_loss_macro"):
+ ops["dice_loss_macro"] = kornia_row("dice_loss_macro", logits, KL.dice_loss, logits, labels, "macro")
+
+ if include("dice_loss_weighted"):
+ weights = torch.linspace(0.5, 1.5, NUM_CLASSES, device=device, dtype=dtype)
+ ops["dice_loss_weighted"] = kornia_row(
+ "dice_loss_weighted", logits, KL.dice_loss, logits, labels, "micro", 1e-8, weights
+ )
+
if include("ssim_loss"):
ops["ssim_loss"] = kornia_row("ssim_loss", recon, KL.ssim_loss, recon, batch_f, WINDOW)
diff --git a/benchmarks/morphology/flagship.py b/benchmarks/morphology/flagship.py
index df96ec162..7f56678b1 100644
--- a/benchmarks/morphology/flagship.py
+++ b/benchmarks/morphology/flagship.py
@@ -48,7 +48,10 @@ library's default: kornia's ``geodesic`` border and OpenCV's default border valu
out-of-image pixels out of the max/min; torchmorph and scikit-image follow SciPy and reflect at the
border (``mode="reflect"``). torchmorph's flat ``size=5`` element is the same 5x5 square.
scikit-image has no gradient operator, so its row is ``dilation - erosion`` in int16, which is the
-definition. Throughput is img/s.
+definition. kornia-rs runs uint8 HWC CPU images with a 5x5 box and replicate borders, which
+produce the same extrema as geodesic borders for this full square. Opening composes its public
+erode/dilate calls; gradient subtracts their uint8 outputs (dilation >= erosion, so no underflow).
+Throughput is img/s.
Usage:
python benchmarks/morphology/flagship.py --batches 1,8,32 --size 256 --device cpu
@@ -77,6 +80,7 @@ from common import (
finish_run,
image_batch,
image_row_fields,
+ kornia_rs_fn,
optional_import,
run_batch_sweep,
setup_run,
@@ -132,6 +136,16 @@ def build_ops(
dilated = skm.dilation(channel, footprint).astype(np.int16)
return dilated - skm.erosion(channel, footprint).astype(np.int16)
+ rs_dilate, rs_erode = kornia_rs_fn("dilate"), kornia_rs_fn("erode")
+ rs_kwargs = {"kernel": "box", "size": (KERNEL_SIZE, KERNEL_SIZE), "border": "replicate"}
+ rs_ops = {
+ "dilation": (lambda im: rs_dilate(im, **rs_kwargs)) if rs_dilate else None,
+ "erosion": (lambda im: rs_erode(im, **rs_kwargs)) if rs_erode else None,
+ "opening": (lambda im: rs_dilate(rs_erode(im, **rs_kwargs), **rs_kwargs)) if rs_dilate and rs_erode else None,
+ "gradient": (lambda im: rs_dilate(im, **rs_kwargs) - rs_erode(im, **rs_kwargs))
+ if rs_dilate and rs_erode
+ else None,
+ }
cv_ops = {
"dilation": (lambda im: cv2.dilate(im, kernel_np)) if cv2 else None,
"erosion": (lambda im: cv2.erode(im, kernel_np)) if cv2 else None,
@@ -165,6 +179,8 @@ def build_ops(
alb_t = alb_ops.get(name)
row["albumentations"] = (lambda alb_t=alb_t: [alb_t(image=im)["image"] for im in imgs_u8]) if alb_t else None
row["scikit-image"] = per_channel(sk_fn) if sk_fn else None
+ rs_fn = rs_ops[name]
+ row["kornia-rs"] = (lambda rs_fn=rs_fn: [rs_fn(im) for im in imgs_u8]) if rs_fn else None
ops[name] = row
return ops, kornia_row.compile_failures
@@ -197,12 +213,22 @@ def main() -> None:
(
f"{KERNEL_SIZE}x{KERNEL_SIZE} square element; kornia: batched float BCHW; "
"torchmorph: batched float32 BCHW (CUDA only); "
- "opencv/albumentations: uint8 HWC per-image loop (CPU); scikit-image: uint8 per-image, per-channel loop"
+ "opencv/albumentations/kornia-rs: uint8 HWC per-image loop (CPU); "
+ "scikit-image: uint8 per-image, per-channel loop"
)
],
- missing=[(name, err) for lib, name, err in libs if lib is None],
+ missing=[(name, err) for lib, name, err in libs if lib is None]
+ + [(f"kornia-rs/{fn}", "API unavailable") for fn in ("dilate", "erode") if kornia_rs_fn(fn) is None],
)
- backends = ["kornia (eager)", "kornia (compiled)", "torchmorph", "albumentations", "scikit-image", "opencv"]
+ backends = [
+ "kornia (eager)",
+ "kornia (compiled)",
+ "torchmorph",
+ "albumentations",
+ "scikit-image",
+ "opencv",
+ "kornia-rs",
+ ]
results = run_batch_sweep(
batch_list(args),
lambda b: build_ops(
diff --git a/tests/test_benchmark_timing.py b/tests/test_benchmark_timing.py
index c1e29cbd3..0dca83d7c 100644
--- a/tests/test_benchmark_timing.py
+++ b/tests/test_benchmark_timing.py
@@ -351,3 +351,16 @@ def test_filter_benchmark_missing_pillow_filters():
)
assert len(ops) == 3
assert all(row["PIL"] is None for row in ops.values())
+
+
+def test_setup_requests_rayon_threads(monkeypatch):
+ monkeypatch.setenv("RAYON_NUM_THREADS", "19")
+ monkeypatch.setattr(common, "warm_up_cpu", lambda: None)
+ previous = torch.get_num_threads()
+ try:
+ common.setup_run(argparse.Namespace(threads=2, device="cpu", dtype="float32"), opencv=False)
+ assert common.os.environ["RAYON_NUM_THREADS"] == "2"
+ assert common.run_metadata(torch.device("cpu"))["rayon_num_threads_requested"] == "2"
+ finally:
+ torch.set_num_threads(previous)
diff --git a/tests/test_flagship_coverage.py b/tests/test_flagship_coverage.py
new file mode 100644
index 000000000..aba1c3dfd
--- /dev/null
+++ b/tests/test_flagship_coverage.py
@@ -0,0 +1,217 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from __future__ import annotations
+
+import importlib.util
+import sys
+from pathlib import Path
+
+import numpy as np
+import pytest
+import torch
+
+from testing.base import BaseTester
+
+NEW_OPS = {
+ "color": {"hsv_to_rgb"},
+ "filters": {"spatial_gradient"},
+ "geometry": {"remap", "transform_points", "depth_to_3d"},
+ "feature": {"match_snn", "match_mnn", "match_smnn", "match_smnn_batched"},
+}
+
+
+def load_suite(suite):
+ path = Path(__file__).parents[1] / "benchmarks" / suite / "flagship.py"
+ spec = importlib.util.spec_from_file_location(f"flagship_{suite}", path)
+ assert spec is not None
+ assert spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ old_path = sys.path.copy()
+ try:
+ spec.loader.exec_module(module)
+ finally:
+ sys.path[:] = old_path
+ return module
+
+
+def build(suite, module, cv2=None, skc=None):
+ args = (2, 16, 20, torch.device("cpu"), torch.float32, False)
+ selected = frozenset(NEW_OPS[suite])
+ if suite == "color":
+ return module.build_ops(*args, cv2, None, skc, None, selected=selected)[0]
+ if suite == "filters":
+ return module.build_ops(*args, cv2, None, None, None, None, selected_ops=selected)[0]
+ return module.build_ops(*args, cv2, None, selected=selected)[0]
+
+
+class TestFlagshipCoverage(BaseTester):
+ @pytest.mark.parametrize("suite", NEW_OPS)
+ @pytest.mark.device_agnostic
+ def test_without_optional_libraries(self, suite, monkeypatch):
+ module = load_suite(suite)
+ declared = module.AVAILABLE_OPS if suite == "filters" else module.OPS
+ assert NEW_OPS[suite] <= set(declared)
+ if suite == "feature":
+ monkeypatch.setattr(module, "NUM_DESCRIPTORS", 32)
+ ops = build(suite, module)
+ assert set(ops) == NEW_OPS[suite]
+ for row in ops.values():
+ assert row.get("opencv") is None
+ result = row["kornia (eager)"]()
+ tensors = result if isinstance(result, (list, tuple)) else [result]
+ for value in tensors:
+ for tensor in value if isinstance(value, tuple) else [value]:
+ assert torch.isfinite(tensor).all()
+
+ @pytest.mark.device_agnostic
+ def test_hsv_inverse_native_units(self):
+ cv2 = pytest.importorskip("cv2")
+ module = load_suite("color")
+ row = build("color", module, cv2)["hsv_to_rgb"]
+ actual = row["kornia (eager)"]()
+ _, expected = module.image_batch(2, 16, 20, torch.device("cpu"), torch.float32)
+ self.assert_close(actual, expected)
+ for backend in ("opencv", "opencv (stacked)"):
+ result = np.asarray(row[backend]()).reshape(2, 16, 20, 3)
+ self.assert_close(actual, torch.from_numpy(result).permute(0, 3, 1, 2))
+
+ @pytest.mark.device_agnostic
+ def test_hsv_inverse_scikit_image(self):
+ skc = pytest.importorskip("skimage.color")
+ row = build("color", load_suite("color"), skc=skc)["hsv_to_rgb"]
+ expected = torch.from_numpy(np.asarray(row["scikit-image"]())).permute(0, 3, 1, 2)
+ self.assert_close(row["kornia (eager)"](), expected)
+
+ @pytest.mark.device_agnostic
+ def test_spatial_gradient_opencv(self):
+ cv2 = pytest.importorskip("cv2")
+ row = build("filters", load_suite("filters"), cv2)["spatial_gradient"]
+ # Native OpenCV output is a pair of HWC derivative arrays per image.
+ expected = torch.from_numpy(np.asarray(row["opencv"]())).permute(0, 4, 1, 2, 3)
+ self.assert_close(row["kornia (eager)"](), expected)
+
+ @pytest.mark.parametrize("op", ["remap", "transform_points"])
+ @pytest.mark.device_agnostic
+ def test_geometry_opencv(self, op):
+ cv2 = pytest.importorskip("cv2")
+ row = build("geometry", load_suite("geometry"), cv2)[op]
+ actual = row["kornia (eager)"]()
+ expected = torch.from_numpy(np.asarray(row["opencv"]()))
+ expected = expected.permute(0, 3, 1, 2) if op == "remap" else expected.squeeze(2)
+ self.assert_close(actual, expected, rtol=1e-4, atol=2e-5)
+
+ @pytest.mark.device_agnostic
+ def test_depth_projection(self):
+ module = load_suite("geometry")
+ row = build("geometry", module)["depth_to_3d"]
+ points = row["kornia (eager)"]()
+ assert points.shape == (2, 3, 16, 20)
+ assert (points[:, 2] > 0).all()
+ y, x = torch.meshgrid(torch.arange(16), torch.arange(20), indexing="ij")
+ self.assert_close(points[:, 0] / points[:, 2] * 20 + 9.5, x.float().expand(2, -1, -1))
+ self.assert_close(points[:, 1] / points[:, 2] * 20 + 7.5, y.float().expand(2, -1, -1))
+
+ @pytest.mark.parametrize("op", sorted(NEW_OPS["feature"]))
+ @pytest.mark.device_agnostic
+ def test_matching_opencv(self, op, monkeypatch):
+ cv2 = pytest.importorskip("cv2")
+ module = load_suite("feature")
+ monkeypatch.setattr(module, "NUM_DESCRIPTORS", 32)
+ row = build("feature", module, cv2)[op]
+ actual = row["kornia (eager)"]()
+ if op == "match_smnn_batched":
+ _, indices = actual
+ actual_pairs = [{tuple(pair.tolist()) for pair in indices[indices[:, 0] == b, 1:]} for b in range(2)]
+ else:
+ actual_pairs = [{tuple(pair.tolist()) for pair in indices} for _, indices in actual]
+ expected = [{(m.queryIdx, m.trainIdx) for m in matches} for matches in row["opencv"]()]
+ assert all(actual_pairs)
+ assert actual_pairs == expected
+
+ @pytest.mark.device_agnostic
+ def test_snn_inclusive_threshold(self, monkeypatch):
+ cv2 = pytest.importorskip("cv2")
+ module = load_suite("feature")
+ monkeypatch.setattr(
+ module,
+ "descriptor_pairs",
+ lambda b: (torch.zeros(b, 1, 1), torch.tensor([[[4.0], [5.0]]]).expand(b, -1, -1)),
+ )
+ row = build("feature", module, cv2)["match_snn"]
+ assert len(row["kornia (eager)"]()[0][1]) == 1
+ assert len(row["opencv"]()[0]) == 1
+
+ @pytest.mark.device_agnostic
+ def test_matching_mutuality_and_reverse_ratio(self, monkeypatch):
+ cv2 = pytest.importorskip("cv2")
+ module = load_suite("feature")
+ # Both first queries pass forward SNN, but only query 0 is mutual. Its
+ # reverse ratio is 0.09/0.11 > 0.8, so neither survives symmetric SNN.
+ monkeypatch.setattr(
+ module,
+ "descriptor_pairs",
+ lambda b: (
+ torch.tensor([[[0.0], [0.2], [10.0]]]).expand(b, -1, -1),
+ torch.tensor([[[0.09], [9.0], [20.0]]]).expand(b, -1, -1),
+ ),
+ )
+ expected = {
+ "match_snn": {(0, 0), (1, 0), (2, 1)},
+ "match_mnn": {(0, 0), (2, 1)},
+ "match_smnn": {(2, 1)},
+ "match_smnn_batched": {(2, 1)},
+ }
+ for name, row in build("feature", module, cv2).items():
+ result = row["kornia (eager)"]()
+ indices = result[1][:, 1:] if name == "match_smnn_batched" else result[0][1]
+ assert {tuple(pair.tolist()) for pair in indices} == expected[name]
+ assert {(m.queryIdx, m.trainIdx) for m in row["opencv"]()[0]} == expected[name]
+
+ @pytest.mark.parametrize("op", ["dice_loss", "dice_loss_macro", "dice_loss_weighted"])
+ def test_dice_variants_backward(self, op, device, dtype):
+ module = load_suite("losses")
+ ops, failures = module.build_ops(2, 16, 20, device, dtype, False, None, selected=frozenset({op}))
+ assert not failures
+ (gradient,) = ops[op]["kornia (eager)"]()
+ assert gradient.shape == (2, module.NUM_CLASSES, 16, 20)
+ assert torch.isfinite(gradient).all()
+ assert (gradient != 0).any()
+
+ @pytest.mark.device_agnostic
+ def test_hsv_inverse_pil(self):
+ pil = pytest.importorskip("PIL.Image")
+ module = load_suite("color")
+ ops, _ = module.build_ops(
+ 2,
+ 16,
+ 20,
+ torch.device("cpu"),
+ torch.float32,
+ False,
+ None,
+ None,
+ None,
+ pil,
+ selected=frozenset({"hsv_to_rgb"}),
+ )
+ row = ops["hsv_to_rgb"]
+ expected = (
+ torch.from_numpy(np.asarray([np.asarray(im) for im in row["PIL"]()])).permute(0, 3, 1, 2).float() / 255
+ )
+ # Byte hue quantization can move RGB by approximately three byte levels.
+ self.assert_close(row["kornia (eager)"](), expected, atol=4 / 255, rtol=0)
diff --git a/tests/test_flagship_rs_color_geometry.py b/tests/test_flagship_rs_color_geometry.py
new file mode 100644
index 000000000..2857172c3
--- /dev/null
+++ b/tests/test_flagship_rs_color_geometry.py
@@ -0,0 +1,140 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from __future__ import annotations
+
+import numpy as np
+import pytest
+import torch
+
+from testing.base import BaseTester
+
+from tests.test_flagship_coverage import load_suite
+
+RS_OPS = {
+ "color": ("rgb_to_grayscale", "rgb_to_hsv", "hsv_to_rgb", "rgb_to_lab", "rgb_to_ycbcr", "raw_to_rgb"),
+ "geometry": ("warp_perspective", "warp_affine", "rotate", "rotate_shared", "resize"),
+}
+
+
+def build(module, suite):
+ args = (2, 16, 20, torch.device("cpu"), torch.float32, False, None, None)
+ if suite == "color":
+ args += (None, None)
+ return module.build_ops(*args, selected=frozenset(RS_OPS[suite]))[0]
+
+
+def require_rs():
+ rs = pytest.importorskip("kornia_rs")
+ if not hasattr(rs, "imgproc") or not hasattr(rs.imgproc, "rgb_from_hsv"):
+ pytest.skip("Requires the kornia-rs 0.2 color/geometry API")
+ return rs
+
+
+class TestFlagshipRsColorGeometry(BaseTester):
+ @pytest.mark.parametrize("suite", RS_OPS)
+ def test_missing_optional_api(self, suite, monkeypatch):
+ module = load_suite(suite)
+ monkeypatch.setattr(module, "kornia_rs_fn", lambda name: None, raising=False)
+ for row in build(module, suite).values():
+ assert "kornia-rs" in row
+ assert row["kornia-rs"] is None
+ assert torch.isfinite(row["kornia (eager)"]()).all()
+
+ @pytest.mark.parametrize("op", RS_OPS["color"])
+ def test_color_native_units(self, op):
+ require_rs()
+ row = build(load_suite("color"), "color")[op]
+ assert callable(row.get("kornia-rs"))
+ native = np.asarray(row["kornia-rs"]())
+ actual = torch.from_numpy(native).permute(0, 3, 1, 2).float()
+ expected = row["kornia (eager)"]()
+ if op == "rgb_to_hsv":
+ assert native.dtype == np.float32
+ actual[:, 0] *= 2 * torch.pi / 255
+ actual[:, 1:] /= 255
+ elif op == "rgb_to_lab":
+ assert native.dtype == np.float32
+ else:
+ assert native.dtype == (np.float32 if op == "hsv_to_rgb" else np.uint8)
+ actual /= 255
+ if op == "rgb_to_ycbcr":
+ # The Rust function's native ordering is Y, Cr, Cb despite its name.
+ actual = actual[:, [0, 2, 1]]
+ if op == "raw_to_rgb":
+ # Both demosaic RGGB; their border interpolation rules differ.
+ actual, expected = actual[..., 2:-2, 2:-2], expected[..., 2:-2, 2:-2]
+ self.assert_close(actual, expected, atol=0.02 if op == "rgb_to_lab" else 2 / 255, rtol=0)
+
+ @pytest.mark.parametrize("op", RS_OPS["geometry"])
+ def test_geometry_interior_parity(self, op, monkeypatch):
+ require_rs()
+ module = load_suite("geometry")
+
+ def smooth_images(b, h, w, device, dtype):
+ # A low-frequency image makes byte rounding observable without amplifying
+ # tiny coordinate quantization differences into large pixel differences.
+ yy, xx = np.mgrid[:h, :w]
+ image = np.stack((xx * 4 + 20, yy * 4 + 20, xx + yy + 20), axis=-1).astype(np.uint8)
+ images = [image.copy() for _ in range(b)]
+ tensor = torch.from_numpy(np.asarray(images)).permute(0, 3, 1, 2).to(device=device, dtype=dtype) / 255
+ return images, tensor
+
+ monkeypatch.setattr(module, "image_batch", smooth_images)
+ row = build(module, "geometry")[op]
+ assert callable(row.get("kornia-rs"))
+ native = np.asarray(row["kornia-rs"]())
+ assert native.dtype == np.uint8
+ actual = torch.from_numpy(native).permute(0, 3, 1, 2).float() / 255
+ expected = row["kornia (eager)"]()
+ assert actual.shape == expected.shape
+ if op == "resize":
+ self.assert_close(actual, expected, atol=1 / 255, rtol=0)
+ else:
+ # Independent all-ones image identifies positions whose bilinear footprint
+ # lies fully inside the source; the Rust border rule is tested separately.
+ monkeypatch.setattr(
+ module,
+ "image_batch",
+ lambda b, h, w, device, dtype: (
+ [np.full((h, w, 3), 255, np.uint8) for _ in range(b)],
+ torch.ones(b, 3, h, w, device=device, dtype=dtype),
+ ),
+ )
+ mask_row = build(module, "geometry")[op]
+ mask = mask_row["kornia (eager)"]() > 1 - 1e-5
+ assert mask.any()
+ self.assert_close(actual[mask], expected[mask], atol=1 / 255, rtol=0)
+
+ def test_rotate_uses_same_precomputed_matrix(self):
+ require_rs()
+ rows = build(load_suite("geometry"), "geometry")
+ np.testing.assert_array_equal(rows["rotate"]["kornia-rs"](), rows["rotate_shared"]["kornia-rs"]())
+
+ @pytest.mark.parametrize("op", ["warp_affine", "warp_perspective"])
+ def test_native_warp_border_convention(self, op):
+ rs = require_rs()
+ image = np.full((4, 5, 3), 200, np.uint8)
+ matrix = [1.0, 0.0, 0.5, 0.0, 1.0, 0.0]
+ if op == "warp_perspective":
+ matrix += [0.0, 0.0, 1.0]
+ result = getattr(rs.imgproc, op)(image, matrix, (4, 5), "bilinear")
+ np.testing.assert_array_equal(result[0, :, 0], [0, 200, 200, 200, 200])
+ matrix[2] = -0.5
+ result = getattr(rs.imgproc, op)(image, matrix, (4, 5), "bilinear")
+ np.testing.assert_array_equal(result, image)
diff --git a/tests/test_flagship_rs_feature_contrib.py b/tests/test_flagship_rs_feature_contrib.py
new file mode 100644
index 000000000..b24c99365
--- /dev/null
+++ b/tests/test_flagship_rs_feature_contrib.py
@@ -0,0 +1,125 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from __future__ import annotations
+
+import numpy as np
+import pytest
+import torch
+
+from testing.base import BaseTester
+
+from tests.test_flagship_coverage import load_suite
+
+
+def build(module, suite):
+ args = (2, 64, 80, torch.device("cpu"), torch.float32, False, None, None)
+ if suite == "contrib":
+ args += (None,)
+ selected = frozenset(["SIFTFeature" if suite == "feature" else "connected_components_union_find"])
+ return module.build_ops(*args, selected=selected)[0]
+
+
+def require_rs(name):
+ rs = pytest.importorskip("kornia_rs")
+ if not hasattr(rs, "imgproc") or not hasattr(rs.imgproc, name):
+ pytest.skip("Requires the kornia-rs 0.2 feature/contrib API")
+ return rs
+
+
+class TestFlagshipRsFeatureContrib(BaseTester):
+ @pytest.mark.parametrize("suite", ["feature", "contrib"])
+ def test_missing_optional_api(self, suite, monkeypatch):
+ module = load_suite(suite)
+ if suite == "feature":
+ monkeypatch.setattr(module, "NUM_DESCRIPTORS", 8)
+ monkeypatch.setattr(module, "kornia_rs_fn", lambda name: None, raising=False)
+ for row in build(module, suite).values():
+ assert "kornia-rs" in row
+ assert row["kornia-rs"] is None
+
+ def test_sift_prepared_input_and_persistent_detector(self, monkeypatch):
+ module = load_suite("feature")
+ monkeypatch.setattr(module, "NUM_DESCRIPTORS", 8)
+ instances = []
+ calls = []
+
+ class Sift:
+ def __init__(self, n_features):
+ assert n_features == module.NUM_FEATURES
+ instances.append(self)
+
+ def detect_and_compute(self, image):
+ assert image.dtype == np.float32
+ assert image.flags.c_contiguous
+ assert image.ndim == 3
+ assert image.shape[-1] == 1
+ assert 1 < image.max() <= 255
+ assert image.min() >= 0
+ calls.append(image)
+ return [], np.empty((0, 128), dtype=np.float32)
+
+ monkeypatch.setattr(module, "kornia_rs_fn", lambda name: Sift if name == "Sift" else None, raising=False)
+ row = build(module, "feature")["SIFTFeature"]
+ assert callable(row.get("kornia-rs"))
+ assert len(instances) == 1
+ assert not calls
+ row["kornia-rs"]()
+ row["kornia-rs"]()
+ assert len(instances) == 1
+ assert calls[0] is calls[2]
+ assert calls[1] is calls[3]
+
+ def test_sift_matches_opencv_feature_count(self, monkeypatch):
+ require_rs("Sift")
+ cv2 = pytest.importorskip("cv2")
+ module = load_suite("feature")
+ monkeypatch.setattr(module, "NUM_DESCRIPTORS", 8)
+ row = build(module, "feature")["SIFTFeature"]
+ assert callable(row.get("kornia-rs"))
+ detector = cv2.SIFT_create(nfeatures=module.NUM_FEATURES)
+ gray = module.blob_images(2, 64, 80)
+ for image, (keypoints, descriptors) in zip(gray, row["kornia-rs"]()):
+ pixels = (image[0].numpy() * 255).round().astype(np.uint8)
+ expected, _ = detector.detectAndCompute(pixels, None)
+ assert len(keypoints) == len(expected) > 0
+ assert descriptors.shape == (len(keypoints), 128)
+ assert descriptors.dtype == np.float32
+ assert np.isfinite(descriptors).all()
+
+ def test_connected_components_partition(self, monkeypatch):
+ require_rs("connected_components")
+ module = load_suite("contrib")
+ # The diagonal pair must join under 8-connectivity; the distant point
+ # remains separate. Compare partitions, since native label IDs and
+ # whether the returned count includes background can differ.
+ masks = torch.zeros(2, 1, 64, 80)
+ masks[:, :, 2, 2] = 1
+ masks[:, :, 3, 3] = 1
+ masks[:, :, 50, 50] = 1
+ monkeypatch.setattr(module, "blob_masks", lambda b, h, w: masks)
+ row = build(module, "contrib")["connected_components_union_find"]
+ assert callable(row.get("kornia-rs"))
+ expected = row["kornia (eager)"]()
+ for i, (_, labels) in enumerate(row["kornia-rs"]()):
+ labels = np.asarray(labels).reshape(64, 80)
+ foreground = masks[i, 0].numpy().astype(bool)
+ assert np.array_equal(labels != 0, foreground)
+ actual = torch.from_numpy(labels[foreground])
+ reference = expected[i, 0][torch.from_numpy(foreground)]
+ self.assert_close(actual[:, None] == actual[None, :], reference[:, None] == reference[None, :])
diff --git a/tests/test_flagship_rs_native.py b/tests/test_flagship_rs_native.py
new file mode 100644
index 000000000..e2bf57aae
--- /dev/null
+++ b/tests/test_flagship_rs_native.py
@@ -0,0 +1,104 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from __future__ import annotations
+
+import sys
+from types import SimpleNamespace
+
+import numpy as np
+import pytest
+import torch
+
+from testing.base import BaseTester
+
+from tests.test_flagship_coverage import load_suite
+
+
+class TestFlagshipRsNative(BaseTester):
+ @pytest.mark.device_agnostic
+ def test_resolver_layouts(self, monkeypatch):
+ load_suite("enhance")
+ common = sys.modules["common"]
+
+ def fn():
+ return None
+
+ for wheel in (SimpleNamespace(probe=fn), SimpleNamespace(imgproc=SimpleNamespace(probe=fn))):
+ monkeypatch.setitem(sys.modules, "kornia_rs", wheel)
+ assert common.kornia_rs_fn("probe") is fn
+ assert common.kornia_rs_fn("missing") is None
+ monkeypatch.setitem(sys.modules, "kornia_rs", None)
+ assert common.kornia_rs_fn("probe") is None
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("suite", ["enhance", "morphology", "filters"])
+ def test_missing_native_functions(self, suite, monkeypatch):
+ module = load_suite(suite)
+ monkeypatch.setattr(module, "krs_fn" if suite == "filters" else "kornia_rs_fn", lambda name: None)
+ ops = self.build(suite, module, None)
+ assert all(row.get("kornia-rs") is None for row in ops.values())
+
+ @staticmethod
+ def build(suite, module, cv2):
+ args = (2, 32, 40, torch.device("cpu"), torch.float32, False)
+ if suite == "enhance":
+ libs = dict.fromkeys(("cv2", "tvf", "A", "ske", "pil_enh", "pil_ops", "pil"))
+ libs["cv2"] = cv2
+ return module.build_ops(*args, libs, selected=frozenset(("normalize", "equalize", "equalize_clahe")))[0]
+ if suite == "morphology":
+ return module.build_ops(*args, cv2, None, None, None)[0]
+ return module.build_ops(*args, cv2, None, None, None, None, selected_ops=frozenset(("canny",)))[0]
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("suite", ["enhance", "morphology", "filters"])
+ def test_native_outputs(self, suite):
+ pytest.importorskip("kornia_rs")
+ cv2 = pytest.importorskip("cv2")
+ module = load_suite(suite)
+ ops = self.build(suite, module, cv2)
+ required = {
+ "enhance": ("normalize_mean_std", "equalize_hist", "clahe"),
+ "morphology": ("dilate", "erode"),
+ "filters": ("canny", "gray_from_rgb"),
+ }
+ if any(sys.modules["common"].kornia_rs_fn(name) is None for name in required[suite]):
+ pytest.skip("installed kornia-rs lacks the requested APIs")
+ for name, row in ops.items():
+ assert callable(row.get("kornia-rs"))
+ actual = row["kornia-rs"]()
+ assert len(actual) == 2
+ if name == "normalize":
+ expected = row["kornia (eager)"]().permute(0, 2, 3, 1)
+ self.assert_close(torch.from_numpy(np.asarray(actual)), expected)
+ elif name == "canny":
+ # RGB->gray rounding can differ by one level: compare Canny using its own gray input.
+ imgs, _ = module.image_batch(2, 32, 40, torch.device("cpu"), torch.float32)
+ gray = module.krs_fn("gray_from_rgb")
+ for image, result in zip(imgs, actual):
+ expected = cv2.Canny(gray(image)[..., 0], 100, 200)
+ np.testing.assert_array_equal(result[..., 0], expected)
+ elif name == "equalize_clahe":
+ # Identical grid/clip parameters; native interpolation can round one byte differently.
+ self.assert_close(
+ torch.from_numpy(np.asarray(actual)).float(),
+ torch.from_numpy(np.asarray(row["opencv"]())).float(),
+ atol=1,
+ rtol=0,
+ )
+ else:
+ np.testing.assert_array_equal(np.asarray(actual), np.asarray(row["opencv"]()))