🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(models): runnable snippets and input/output figures on every model page (#4178)
Jian Shidc7790608c7b
diff --git a/.gitignore b/.gitignoreindex 3593e710e..47486e9bf 100644--- a/.gitignore+++ b/.gitignore@@ -26,6 +26,8 @@ docs/source/community/adoption.rstdocs/source/_generated/*DS_Store*jpg+# model input/output figures rendered by docs/generate_model_examples.py are committed+!docs/source/_static/img/models/*.jpg# onnx tests create temp.onnx file*.onnxdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 54a357841..66523e0df 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0* An **Adoption** page (`community/adoption`) listing the most-starred GitHub repositories andpackages that depend on kornia, rendered at build time from `docs/source/_data/dependents.json`;`docs/fetch_dependents.py` refreshes that snapshot from GitHub's dependency graph. (#4155)+* Every page in the **Models** section of the docs now opens with the shortest script that runs the+ model and a figure of its output on a real input, with the paper card moved to the bottom. The+ figures are rendered by `docs/generate_model_examples.py` and committed under+ `docs/source/_static/img/models/`, so the docs build needs neither the weights nor the sample+ images. (#4178)### Breaking changes@@ -142,6 +147,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Bug fixes+* `VisualPrompter.predict()` called without any prompt (the "run the prediction without prompts" example on the+ Segment Anything page) raised `TypeError: object of type 'NoneType' has no len()` from the prompt augmentation+ container; it now predicts from the image embedding alone, as documented. (#4178)* Follow-up fixes to the documentation revamp (#4155): the landing page's filtering card quoted the combined`filters`/`color`/`enhance`/`morphology` count next to a `kornia.filters` label, the "Why Kornia?" hero carouselresumed after a visitor picked a tab, the Community page linked to the now-unregistered `librecv.org`, and thediff --git a/docs/generate_model_examples.py b/docs/generate_model_examples.pynew file mode 100644index 000000000..d690b02b2--- /dev/null+++ b/docs/generate_model_examples.py@@ -0,0 +1,456 @@+# 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.+#++"""Render the input/output figures shown on the ``docs/source/models/*.rst`` pages.++Unlike ``generate_examples.py`` this script is *not* run by the Sphinx build: it downloads several+pretrained checkpoints (RT-DETR, SAM ViT-B, SOLD2, DeFMO, ...) and runs them on the CPU, which is too+slow and too download-heavy for a docs build. Run it once when a model or its API changes and commit+the resulting figures under ``docs/source/_static/img/models/``::++ python docs/generate_model_examples.py # all models+ python docs/generate_model_examples.py loftr sold2 # a subset++Each ``figure_<name>`` function runs the model the same way the corresponding page's "Run it" snippet+does (same builder, weights, inputs and prompts) and then draws the result; keep the two in sync when+either changes.+"""++from __future__ import annotations++import sys+from pathlib import Path++import matplotlib as mpl++mpl.use("Agg") # select the headless backend before pyplot is imported++import matplotlib.pyplot as plt+import requests+import torch++import kornia as K+from kornia.image import tensor_to_image+from kornia.io import get_sample_images++torch.manual_seed(0)++OUT = Path(__file__).absolute().parent / "source/_static/img/models"+DATA = "https://raw.githubusercontent.com/kornia/data/main/"+KNCHURCH = "https://github.com/kornia/data_test/raw/8b98f44abbe92b7a84631ed06613b08fee7dae14/knchurch_disk.pt"+IMAGENET_CLASSES = "https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt"++FIGURES: dict = {}+++def figure(fn):+ FIGURES[fn.__name__.removeprefix("figure_")] = fn+ return fn+++def sample(name: str, size: tuple[int, int] | None = None) -> torch.Tensor:+ """One ``(1, 3, H, W)`` float image in [0, 1] from the kornia data repository."""+ img = get_sample_images(paths=[DATA + name], resize=size, as_list=True)[0]+ return img[None]+++def knchurch() -> tuple[torch.Tensor, torch.Tensor]:+ d = torch.hub.load_state_dict_from_url(KNCHURCH, map_location="cpu")+ return d["img1"], d["img2"]+++def imagenet_classes() -> list[str]:+ response = requests.get(IMAGENET_CLASSES, timeout=60)+ response.raise_for_status()+ return response.text.strip().splitlines()+++def show(ax, img: torch.Tensor, title: str = "") -> None:+ ax.imshow(tensor_to_image(img[0] if img.dim() == 4 else img), cmap="gray" if img.shape[-3] == 1 else None)+ ax.set_title(title, fontsize=10)+ ax.set_axis_off()+++def save(fig, name: str) -> None:+ OUT.mkdir(parents=True, exist_ok=True)+ fig.savefig(OUT / f"{name}.jpg", dpi=110, bbox_inches="tight", pil_kwargs={"quality": 88})+ plt.close(fig)+ print(f"wrote {OUT / name}.jpg")+++def topk_bars(ax, logits: torch.Tensor, names: list[str], title: str) -> None:+ probs = logits.softmax(-1)[0]+ top = probs.topk(5)+ ax.barh(range(5)[::-1], top.values.tolist(), color="#4c72b0")+ ax.set_yticks(range(5)[::-1], [names[i] for i in top.indices.tolist()], fontsize=9)+ ax.set_xlim(0, 1)+ ax.set_xlabel("softmax probability")+ ax.set_title(title, fontsize=10)+++# --------------------------------------------------------------------------- object detection+++@figure+def figure_rt_detr() -> None:+ from kornia.contrib.object_detection import RTDETRDetectorBuilder++ image = sample("delorean.png")+ detector = RTDETRDetectorBuilder.build("rtdetr_r18vd") # runs at the 640 px the weights were trained for+ detections = detector(image) # one (D, 6) tensor per image: class id, score, x, y, w, h++ fig, axs = plt.subplots(1, 2, figsize=(9, 3.4))+ show(axs[0], image, "input")+ show(axs[1], image, f"RT-DETR (r18vd): {detections[0].shape[0]} detections above 0.3")+ for cls, score, x, y, w, h in detections[0].tolist():+ axs[1].add_patch(mpl.patches.Rectangle((x, y), w, h, fill=False, color="lime", lw=1.5))+ axs[1].text(x, y - 3, f"class {int(cls)} · {score:.2f}", color="lime", fontsize=8, fontweight="bold")+ save(fig, "rt_detr")+++@figure+def figure_yunet() -> None:+ from kornia.contrib import FaceDetector, FaceDetectorResult, FaceKeypoint++ image = sample("crowd.jpg", (587, 900))+ detector = FaceDetector() # YuNet expects pixel values in [0, 255]+ faces = [FaceDetectorResult(f) for f in detector(image * 255.0)[0]] # one result per detected face++ fig, axs = plt.subplots(1, 2, figsize=(11, 3.8))+ show(axs[0], image, "input")+ show(axs[1], image, f"YuNet: {len(faces)} faces with score > 0.3 (boxes + 5 landmarks)")+ for f in faces:+ x1, y1, x2, y2 = f.xmin.item(), f.ymin.item(), f.xmax.item(), f.ymax.item()+ axs[1].add_patch(mpl.patches.Rectangle((x1, y1), x2 - x1, y2 - y1, fill=False, color="lime", lw=1.0))+ for kp in FaceKeypoint:+ x, y = f.get_keypoint(kp).tolist()+ axs[1].plot(x, y, ".", color="yellow", ms=2.5)+ fig.tight_layout()+ save(fig, "yunet")+++# --------------------------------------------------------------------------- segmentation+++def _sam_figure(model_type: str, name: str, title: str) -> None:+ from kornia.contrib.visual_prompter import VisualPrompter+ from kornia.geometry.boxes import Boxes+ from kornia.geometry.keypoints import Keypoints+ from kornia.models.sam import SamConfig++ image = sample("simba.png")[0] # (3, H, W)+ prompter = VisualPrompter(SamConfig(model_type, pretrained=True))+ prompter.set_image(image) # encode once, query many times++ keypoints = Keypoints(torch.tensor([[[300.0, 90.0]]])) # (K, N, 2): K prompts of N (x, y) points; on the eye+ labels = torch.tensor([[1]]) # 1 = foreground, 0 = background+ box = Boxes.from_tensor(torch.tensor([[[180.0, 20.0, 380.0, 240.0]]]), mode="xyxy") # around the head+ point_pred = prompter.predict(keypoints=keypoints, keypoints_labels=labels) # 3 candidate masks+ box_pred = prompter.predict(boxes=box, multimask_output=False) # 1 mask++ best = point_pred.scores.argmax() # pick the candidate with the highest predicted IoU+ fig, axs = plt.subplots(1, 3, figsize=(12, 3.0))+ show(axs[0], image, "input + prompts (star: point, box)")+ axs[0].plot(300, 90, "*", color="lime", ms=12, mec="black")+ axs[0].add_patch(mpl.patches.Rectangle((180, 20), 200, 220, fill=False, color="cyan", lw=1.5))+ for ax, pred, m, t in ((axs[1], point_pred, best, "point"), (axs[2], box_pred, 0, "box")):+ show(ax, image, f"{title}, {t} prompt (predicted IoU {pred.scores[0, m]:.2f})")+ mask = pred.binary_masks[0, m].float()+ ax.imshow(tensor_to_image(torch.stack([mask * 0, mask, mask * 0.6, mask * 0.55])), interpolation="nearest")+ fig.tight_layout()+ save(fig, name)+++@figure+def figure_segment_anything() -> None:+ _sam_figure("vit_b", "segment_anything", "SAM ViT-B")+++@figure+def figure_mobile_sam() -> None:+ _sam_figure("mobile_sam", "mobile_sam", "MobileSAM")+++@figure+def figure_efficient_vit() -> None:+ from kornia.models.efficient_vit import EfficientViT, EfficientViTConfig++ image = sample("panda.jpg", (224, 224))+ model = EfficientViT.from_config(EfficientViTConfig.from_pretrained("b1", 224)).eval()+ with torch.no_grad():+ feats = model(image) # dict of feature maps: "input", "stage0" ... "stage_final"++ stages = [k for k in feats if k.startswith("stage")]+ fig, axs = plt.subplots(1, 1 + len(stages), figsize=(2.3 * (1 + len(stages)), 2.6))+ show(axs[0], image, "input 224x224")+ for ax, k in zip(axs[1:], stages):+ f = feats[k][0]+ ax.imshow(f.abs().mean(0), cmap="magma")+ ax.set_title(f"{k}: {tuple(f.shape)}", fontsize=8)+ ax.set_axis_off()+ fig.suptitle("EfficientViT-B1 pyramid, mean |activation| per stage", fontsize=10)+ save(fig, "efficient_vit")+++# --------------------------------------------------------------------------- classification backbones+++@figure+def figure_tiny_vit() -> None:+ from kornia.models.tiny_vit import TinyViT++ image = sample("panda.jpg", (224, 224))+ model = TinyViT.from_config("5m", pretrained=True).eval() # ImageNet-1k weights+ with torch.no_grad():+ logits = model(image) # (1, 1000)++ fig, axs = plt.subplots(1, 2, figsize=(9, 3), width_ratios=[1, 1.6])+ show(axs[0], image, "input 224x224")+ topk_bars(axs[1], logits, imagenet_classes(), "TinyViT-5M top-5 ImageNet classes")+ fig.tight_layout()+ save(fig, "tiny_vit")+++@figure+def figure_vit() -> None:+ from kornia.models.vit import VisionTransformer++ image = sample("panda.jpg", (224, 224))+ vit = VisionTransformer.from_config("vit_b/16", pretrained=True).eval() # AugReg ImageNet-21k weights+ with torch.no_grad():+ tokens = vit(image) # (1, 197, 768): class token + 14x14 patch tokens++ fig, axs = plt.subplots(1, 3, figsize=(11, 3.2), width_ratios=[1, 1, 1.3])+ show(axs[0], image, "input 224x224 → 14x14 patches of 16 px")+ for p in range(0, 224, 16):+ axs[0].axhline(p - 0.5, color="white", lw=0.4, alpha=0.7)+ axs[0].axvline(p - 0.5, color="white", lw=0.4, alpha=0.7)+ axs[1].imshow(tokens[0, 1:].norm(dim=-1).view(14, 14), cmap="viridis")+ axs[1].set_title("‖patch token‖ on the 14x14 grid", fontsize=10)+ axs[1].set_axis_off()+ axs[2].imshow(tokens[0, :, :96].T, aspect="auto", cmap="coolwarm")+ axs[2].set_title("output (1, 197, 768): first 96 dims of each token", fontsize=10)+ axs[2].set_xlabel("token (0 = class token)")+ axs[2].set_ylabel("embedding dim")+ fig.suptitle("VisionTransformer vit_b/16 with the pretrained AugReg ImageNet-21k weights", fontsize=10)+ fig.tight_layout()+ save(fig, "vit")+++@figure+def figure_vit_mobile() -> None:+ from kornia.models.vit_mobile import MobileViT++ image = sample("panda.jpg", (256, 256))+ mvit = MobileViT(mode="xxs").eval() # random init: no pretrained weights+ with torch.no_grad():+ feats = mvit(image) # (1, 320, 8, 8) feature map++ fig, axs = plt.subplots(1, 2, figsize=(7.5, 3.6))+ show(axs[0], image, "input 256x256")+ axs[1].imshow(feats[0].abs().mean(0), cmap="magma")+ axs[1].set_title(f"output {tuple(feats.shape)}: mean |activation|", fontsize=10)+ axs[1].set_axis_off()+ fig.suptitle("MobileViT-XXS with random initialisation (stride-32 feature map)", fontsize=10)+ fig.tight_layout()+ save(fig, "vit_mobile")+++# --------------------------------------------------------------------------- local features and matching+++def _draw_matches(ax, img1, img2, pts1, pts2, title: str, max_lines: int = 150) -> None:+ w = img1.shape[-1]+ show(ax, torch.cat([img1, img2], dim=-1), title)+ idx = torch.randperm(len(pts1))[:max_lines]+ for (x1, y1), (x2, y2) in zip(pts1[idx].tolist(), pts2[idx].tolist()):+ ax.plot([x1, x2 + w], [y1, y2], color="lime", lw=0.4, alpha=0.8)+ ax.plot(pts1[:, 0], pts1[:, 1], ".", color="yellow", ms=1.2)+ ax.plot(pts2[:, 0] + w, pts2[:, 1], ".", color="yellow", ms=1.2)+++@figure+def figure_loftr() -> None:+ from kornia.feature import LoFTR++ img1, img2 = knchurch() # two (1, 3, H, W) views of the same scene+ matcher = LoFTR(pretrained="outdoor").eval()+ with torch.no_grad():+ out = matcher({"image0": K.color.rgb_to_grayscale(img1), "image1": K.color.rgb_to_grayscale(img2)})+ pts1, pts2, conf = out["keypoints0"], out["keypoints1"], out["confidence"]++ fig, ax = plt.subplots(figsize=(9, 5))+ _draw_matches(+ ax, img1, img2, pts1, pts2, f"LoFTR (outdoor): {len(pts1)} matches, mean confidence {conf.mean():.2f}"+ )+ save(fig, "loftr")+++@figure+def figure_sold2() -> None:+ from kornia.feature import SOLD2++ img1, img2 = knchurch()+ gray = K.color.rgb_to_grayscale(torch.cat([img1, img2]))+ sold2 = SOLD2(pretrained=True).eval()+ with torch.no_grad():+ out = sold2(gray) # line_segments: list of (N, 2, 2) in (y, x); dense_desc: (B, 128, H/4, W/4)+ lines1, lines2 = out["line_segments"]+ matches = sold2.match(+ lines1, lines2, out["dense_desc"][0:1], out["dense_desc"][1:2]+ ) # (N1,) index into lines2, -1 = none++ valid = matches != -1+ m1, m2 = lines1[valid], lines2[matches[valid]]+ fig, axs = plt.subplots(1, 3, figsize=(12, 4.2), width_ratios=[1, 1, 2])+ for ax, img, lines, t in (+ (axs[0], img1, lines1, "SOLD2 lines, image 1"),+ (axs[1], img2, lines2, "SOLD2 lines, image 2"),+ ):+ show(ax, img, f"{t} ({len(lines)})")+ for (y1, x1), (y2, x2) in lines.tolist():+ ax.plot([x1, x2], [y1, y2], color="lime", lw=0.8)+ w = img1.shape[-1]+ show(axs[2], torch.cat([img1, img2], dim=-1), f"{int(valid.sum())} matched lines")+ colors = plt.cm.hsv(torch.linspace(0, 1, len(m1)).numpy())+ for c, ((ay, ax_), (by, bx)), ((cy, cx), (dy, dx)) in zip(colors, m1.tolist(), m2.tolist()):+ axs[2].plot([ax_, bx], [ay, by], color=c, lw=1.2)+ axs[2].plot([cx + w, dx + w], [cy, dy], color=c, lw=1.2)+ save(fig, "sold2")+++@figure+def figure_hardnet() -> None:+ from kornia.feature import HardNet, KeyNetDetector, extract_patches_from_pyramid, match_snn++ img1, img2 = knchurch()+ gray1, gray2 = K.color.rgb_to_grayscale(img1), K.color.rgb_to_grayscale(img2)+ detector = KeyNetDetector(pretrained=True, num_features=1500).eval()+ hardnet = HardNet(pretrained=True).eval()+ with torch.no_grad():+ lafs1, _ = detector(gray1)+ lafs2, _ = detector(gray2)+ patches1 = extract_patches_from_pyramid(gray1, lafs1)[0] # (N, 1, 32, 32)+ patches2 = extract_patches_from_pyramid(gray2, lafs2)[0]+ desc1, desc2 = hardnet(patches1), hardnet(patches2) # (N, 128), L2-normalised+ _, idx = match_snn(desc1, desc2, th=0.9)++ pts1 = K.feature.get_laf_center(lafs1)[0, idx[:, 0]]+ pts2 = K.feature.get_laf_center(lafs2)[0, idx[:, 1]]+ fig = plt.figure(figsize=(12, 4.2))+ gs = fig.add_gridspec(2, 2, width_ratios=[1, 1.9])+ ax = fig.add_subplot(gs[0, 0])+ ax.imshow(tensor_to_image(torch.cat(list(patches1[:8]), dim=-1)), cmap="gray")+ ax.set_title("8 of the 1500 KeyNet patches (32x32)", fontsize=10)+ ax.set_axis_off()+ ax = fig.add_subplot(gs[1, 0])+ ax.imshow(desc1[:8], aspect="auto", cmap="coolwarm")+ ax.set_title("their HardNet descriptors (8 x 128)", fontsize=10)+ ax.set_yticks([])+ ax = fig.add_subplot(gs[:, 1])+ _draw_matches(ax, img1, img2, pts1, pts2, f"KeyNet + HardNet + SNN matching: {len(idx)} matches")+ fig.tight_layout()+ save(fig, "hardnet")+++@figure+def figure_affnet() -> None:+ from kornia.feature import KeyNetDetector, LAFAffNetShapeEstimator, laf_to_boundary_points++ img1, _ = knchurch()+ gray = K.color.rgb_to_grayscale(img1)+ detector = KeyNetDetector(pretrained=True, num_features=32).eval()+ affnet = LAFAffNetShapeEstimator(pretrained=True).eval()+ with torch.no_grad():+ lafs, _ = detector(gray) # (1, N, 2, 3) circular local affine frames+ lafs_affine = affnet(lafs, gray) # (1, N, 2, 3) affine-covariant frames++ h, w = gray.shape[-2:]+ fig, axs = plt.subplots(1, 2, figsize=(7, 4.4))+ panels = ((axs[0], lafs, "KeyNet LAFs (isotropic)"), (axs[1], lafs_affine, "after AffNet (affine shape)"))+ for ax, frames, t in panels:+ show(ax, img1, t)+ for pts in laf_to_boundary_points(frames)[0].tolist():+ xs, ys = zip(*pts)+ ax.plot(xs, ys, color="lime", lw=1.0)+ ax.set_xlim(0, w)+ ax.set_ylim(h, 0)+ save(fig, "affnet")+++# --------------------------------------------------------------------------- edges and enhance+++@figure+def figure_dexined() -> None:+ from kornia.contrib.edge_detection import EdgeDetectorBuilder++ image = sample("girona.png")+ detector = EdgeDetectorBuilder.build("dexined", pretrained=True, image_size=352) # resize + normalise + sigmoid+ with torch.no_grad():+ edges = detector(image)[0] # list of (1, 1, H, W) edge probabilities in [0, 1], one per input image++ fig, axs = plt.subplots(1, 2, figsize=(9, 3.2))+ show(axs[0], image, "input")+ show(axs[1], 1 - edges, "DexiNed edge probability (dark = edge)")+ save(fig, "dexined")+++@figure+def figure_defmo() -> None:+ from kornia.feature import DeFMO++ # Synthesise a striped ball flying across a static background: the blurred frame is the+ # mean of its 24 positions, exactly the image-formation model DeFMO inverts.+ background = sample("girona.png", (240, 320))+ h, w = background.shape[-2:]+ yy, xx = torch.meshgrid(torch.arange(h), torch.arange(w), indexing="ij")+ orange = torch.tensor([1.0, 0.6, 0.1])[None, :, None, None]+ navy = torch.tensor([0.05, 0.05, 0.25])[None, :, None, None]+ frames = []+ for t in torch.linspace(0, 1, 24):+ cx, cy = 80 + 160 * t, 150 - 60 * t+ alpha = (((xx - cx) ** 2 + (yy - cy) ** 2) < 42**2).float()[None, None]+ stripe = (((xx - cx) + (yy - cy)).abs() < 10).float()[None, None]+ frames.append(alpha * (orange * (1 - stripe) + navy * stripe) + (1 - alpha) * background)+ blurred = torch.stack(frames).mean(0) # (1, 3, H, W)++ defmo = DeFMO(pretrained=True).eval()+ with torch.no_grad():+ subframes = defmo(torch.cat([blurred, background], dim=1)) # (1, 24, 4, H, W) RGBA sub-frames++ fig, axs = plt.subplots(2, 4, figsize=(12, 4.8))+ show(axs[0, 0], blurred, "input: motion-blurred frame")+ show(axs[0, 1], background, "input: background estimate")+ show(axs[0, 2], frames[0], "ground truth, first sub-frame")+ show(axs[0, 3], frames[-1], "ground truth, last sub-frame")+ for ax, i in zip(axs[1], (0, 8, 16, 23)):+ rgba = subframes[0, i]+ composed = rgba[3:] * rgba[:3] + (1 - rgba[3:]) * background[0] # alpha-blend onto the background+ show(ax, composed, f"DeFMO sub-frame {i + 1}/24")+ fig.tight_layout()+ save(fig, "defmo")+++if __name__ == "__main__":+ wanted = sys.argv[1:] or list(FIGURES)+ unknown = [n for n in wanted if n not in FIGURES]+ if unknown:+ raise SystemExit(f"unknown figure(s) {unknown}; choose from {sorted(FIGURES)}")+ for n in wanted:+ print(f"== {n}")+ FIGURES[n]()diff --git a/docs/source/_static/img/models/affnet.jpg b/docs/source/_static/img/models/affnet.jpgnew file mode 100644index 000000000..bc6762643Binary files /dev/null and b/docs/source/_static/img/models/affnet.jpg differdiff --git a/docs/source/_static/img/models/defmo.jpg b/docs/source/_static/img/models/defmo.jpgnew file mode 100644index 000000000..c5857b301Binary files /dev/null and b/docs/source/_static/img/models/defmo.jpg differdiff --git a/docs/source/_static/img/models/dexined.jpg b/docs/source/_static/img/models/dexined.jpgnew file mode 100644index 000000000..f7d145861Binary files /dev/null and b/docs/source/_static/img/models/dexined.jpg differdiff --git a/docs/source/_static/img/models/efficient_vit.jpg b/docs/source/_static/img/models/efficient_vit.jpgnew file mode 100644index 000000000..c5f90b36fBinary files /dev/null and b/docs/source/_static/img/models/efficient_vit.jpg differdiff --git a/docs/source/_static/img/models/hardnet.jpg b/docs/source/_static/img/models/hardnet.jpgnew file mode 100644index 000000000..9bfa3966bBinary files /dev/null and b/docs/source/_static/img/models/hardnet.jpg differdiff --git a/docs/source/_static/img/models/loftr.jpg b/docs/source/_static/img/models/loftr.jpgnew file mode 100644index 000000000..0724f5b8fBinary files /dev/null and b/docs/source/_static/img/models/loftr.jpg differdiff --git a/docs/source/_static/img/models/mobile_sam.jpg b/docs/source/_static/img/models/mobile_sam.jpgnew file mode 100644index 000000000..7247bd5e5Binary files /dev/null and b/docs/source/_static/img/models/mobile_sam.jpg differdiff --git a/docs/source/_static/img/models/rt_detr.jpg b/docs/source/_static/img/models/rt_detr.jpgnew file mode 100644index 000000000..19e582620Binary files /dev/null and b/docs/source/_static/img/models/rt_detr.jpg differdiff --git a/docs/source/_static/img/models/segment_anything.jpg b/docs/source/_static/img/models/segment_anything.jpgnew file mode 100644index 000000000..0267f04d9Binary files /dev/null and b/docs/source/_static/img/models/segment_anything.jpg differdiff --git a/docs/source/_static/img/models/sold2.jpg b/docs/source/_static/img/models/sold2.jpgnew file mode 100644index 000000000..c3a666ad3Binary files /dev/null and b/docs/source/_static/img/models/sold2.jpg differdiff --git a/docs/source/_static/img/models/tiny_vit.jpg b/docs/source/_static/img/models/tiny_vit.jpgnew file mode 100644index 000000000..3becd1e41Binary files /dev/null and b/docs/source/_static/img/models/tiny_vit.jpg differdiff --git a/docs/source/_static/img/models/vit.jpg b/docs/source/_static/img/models/vit.jpgnew file mode 100644index 000000000..1c6539930Binary files /dev/null and b/docs/source/_static/img/models/vit.jpg differdiff --git a/docs/source/_static/img/models/vit_mobile.jpg b/docs/source/_static/img/models/vit_mobile.jpgnew file mode 100644index 000000000..ef5848828Binary files /dev/null and b/docs/source/_static/img/models/vit_mobile.jpg differdiff --git a/docs/source/_static/img/models/yunet.jpg b/docs/source/_static/img/models/yunet.jpgnew file mode 100644index 000000000..31650550bBinary files /dev/null and b/docs/source/_static/img/models/yunet.jpg differdiff --git a/docs/source/models/affnet.rst b/docs/source/models/affnet.rstindex 14be44d5e..575936b59 100644--- a/docs/source/models/affnet.rst+++ b/docs/source/models/affnet.rst@@ -5,6 +5,43 @@ AffNet:bdg-primary:`Affine shape estimation` :bdg-secondary:`MIT`+AffNet predicts the affine shape of a local region so that the same surface patch, seen from two viewpoints, is+normalised to the same square before it is described. :class:`~kornia.feature.LAFAffNetShapeEstimator` takes the+local affine frames (LAFs) of any detector and returns frames with the estimated ellipse in place of the circle.++Run it+------++.. code-block:: python++ import torch+ from kornia.color import rgb_to_grayscale+ from kornia.feature import KeyNetDetector, LAFAffNetShapeEstimator, laf_to_boundary_points+ from kornia.io import load_image++ gray = rgb_to_grayscale(load_image("church_1.png")[None]) # (1, 1, H, W)++ detector = KeyNetDetector(pretrained=True, num_features=32).eval()+ affnet = LAFAffNetShapeEstimator(pretrained=True).eval()+ with torch.no_grad():+ lafs, _ = detector(gray) # (1, N, 2, 3) isotropic local affine frames+ lafs_affine = affnet(lafs, gray) # (1, N, 2, 3) affine-covariant frames++ boundaries = laf_to_boundary_points(lafs_affine) # (1, N, 50, 2) ellipse outlines in (x, y) pixels, for plotting++.. figure:: /_static/img/models/affnet.jpg+ :align: center+ :alt: The same church photograph twice: on the left with circular KeyNet regions, on the right with the elliptical regions AffNet estimated for them.++ The 32 strongest KeyNet regions before (circles) and after AffNet (ellipses that follow the local surface).++The estimated frames feed straight into :func:`~kornia.feature.extract_patches_from_pyramid` and a descriptor such+as :class:`~kornia.feature.HardNet`; :class:`~kornia.feature.KeyNetAffNetHardNet` wires the three together, and+:class:`~kornia.feature.PatchAffineShapeEstimator` is the raw patch-to-shape network.++Paper+-----+.. card:::link: https://paperswithcode.com/paper/repeatability-is-not-enough-learning-affinediff --git a/docs/source/models/defmo.rst b/docs/source/models/defmo.rstindex 5c676c47c..617890c92 100644--- a/docs/source/models/defmo.rst+++ b/docs/source/models/defmo.rst@@ -5,6 +5,45 @@ DeFMO:bdg-primary:`Enhance` :bdg-primary:`Deblurring` :bdg-secondary:`Apache-2.0`+DeFMO takes a single frame in which a fast-moving object is motion-blurred, plus an estimate of the static+background, and renders the object sharp at 24 moments of the exposure, as a high-speed camera would have seen it.+:class:`~kornia.feature.DeFMO` takes the two images stacked along the channel axis and returns RGBA sub-frames.++Run it+------++.. code-block:: python++ import torch+ from kornia.feature import DeFMO+ from kornia.io import load_image++ blurred = load_image("blurred.png")[None] # (1, 3, 240, 320) frame with a motion-blurred object+ background = load_image("background.png")[None] # (1, 3, 240, 320) the same view without the object++ defmo = DeFMO(pretrained=True).eval()+ with torch.no_grad():+ subframes = defmo(torch.cat([blurred, background], dim=1)) # (1, 24, 4, 240, 320) RGBA sub-frames++ rgba = subframes[0, 0] # first sub-frame: rgb = rgba[:3], alpha = rgba[3:]+ composed = rgba[3:] * rgba[:3] + (1 - rgba[3:]) * background[0] # paste it back onto the background++.. figure:: /_static/img/models/defmo.jpg+ :align: center+ :alt: Top row, the blurred input, the background and two ground-truth sub-frames of a striped ball; bottom row, four DeFMO sub-frames showing the sharp ball at successive positions.++ A striped ball rendered at 24 positions over a street photo and averaged into one blurred frame (top left).+ DeFMO recovers its shape and trajectory from that frame and the background (bottom, four of the 24 sub-frames,+ composited onto the background). The direction of motion is ambiguous from a single blur, so the sub-frame+ order may be reversed.++The network is fully convolutional and the output keeps the input resolution; the pretrained weights were trained+on ``240×320`` crops around the object, so results are best near that scale. Each sub-frame's alpha channel is the+object mask, so the trajectory is the sequence of alpha centroids.++Paper+-----+.. card:::link: https://paperswithcode.com/paper/defmo-deblurring-and-shape-recovery-of-fastdiff --git a/docs/source/models/dexined.rst b/docs/source/models/dexined.rstindex 0e48803ce..63494dc8d 100644--- a/docs/source/models/dexined.rst+++ b/docs/source/models/dexined.rst@@ -7,6 +7,40 @@ DexiNed:bdg-primary:`Edge detection` :bdg-secondary:`MIT`+DexiNed is a dense inception-style network that predicts thin, well-localised edges and was trained from scratch+on the BIPED edge dataset. The quickest way to run it is+:class:`~kornia.contrib.edge_detection.EdgeDetectorBuilder`, which wraps :class:`~kornia.models.dexined.DexiNed`+with the resize, normalisation and sigmoid it expects and resizes the edge map back to the input size.++Run it+------++.. code-block:: python++ import torch+ from kornia.contrib.edge_detection import EdgeDetectorBuilder+ from kornia.io import load_image++ image = load_image("girona.png")[None] # (1, 3, H, W) float in [0, 1]++ detector = EdgeDetectorBuilder.build("dexined", pretrained=True, image_size=352) # runs the net at 352 px+ with torch.no_grad():+ edges = detector(image)[0] # (1, 1, H, W) edge probabilities in [0, 1], one per input image++.. figure:: /_static/img/models/dexined.jpg+ :align: center+ :alt: A street photo and, next to it, the DexiNed edge map drawn as dark lines on white.++ The input image and its DexiNed edge probability map (dark = edge).++The detector accepts a batch tensor or a list of ``(3, H, W)`` images of different sizes and returns one edge map+per image. To use the bare network, :class:`~kornia.models.dexined.DexiNed` takes a ``(B, 3, H, W)`` input scaled to+``[0, 255]`` and mean-subtracted and returns the fused edge logits; ``EdgeDetectorBuilder`` also exposes+``to_onnx()`` for export.++Paper+-----+.. card:::link: https://www.computer.org/csdl/proceedings-article/wacv/2020/09093290/1jPbjFHmwi4@@ -25,6 +59,5 @@ DexiNed+++**Authors:** X. Soria and E. Riba and A. Sappa-.. image:: https://github.com/xavysp/DexiNed/raw/master/figs/DexiNed_banner.png:align: centerdiff --git a/docs/source/models/efficient_vit.rst b/docs/source/models/efficient_vit.rstindex 8064c7311..0ffcae122 100644--- a/docs/source/models/efficient_vit.rst+++ b/docs/source/models/efficient_vit.rst@@ -5,6 +5,43 @@ EfficientViT:bdg-primary:`Segmentation` :bdg-primary:`Classification` :bdg-primary:`Detection` :bdg-secondary:`Apache-2.0`+EfficientViT is a high-resolution vision backbone built on multi-scale linear attention. Kornia ships the ImageNet+pretrained backbones (``b1``, ``b2``, ``b3`` at 224/256/288 px) as :class:`~kornia.models.efficient_vit.EfficientViT`.+The model returns a dictionary with the input and the feature map after each stage, so it plugs into any dense+prediction or classification head.++Run it+------++.. code-block:: python++ import torch+ from kornia.io import load_image+ from kornia.geometry import resize+ from kornia.models.efficient_vit import EfficientViT, EfficientViTConfig++ image = resize(load_image("panda.jpg")[None], (224, 224)) # (1, 3, 224, 224) float in [0, 1]++ model = EfficientViT.from_config(EfficientViTConfig.from_pretrained("b1", 224)).eval()+ with torch.no_grad():+ features = model(image) # dict: "input", "stage0" ... "stage4", "stage_final"++ for name, feat in features.items():+ print(name, tuple(feat.shape)) # stage0 (1, 16, 112, 112) ... stage_final (1, 256, 7, 7)++.. figure:: /_static/img/models/efficient_vit.jpg+ :align: center+ :alt: The input image followed by six feature-map heatmaps of decreasing resolution, from 112x112 down to 7x7.++ Mean absolute activation of every stage of ``b1`` at 224 px: the resolution halves and the channel count doubles+ from ``stage0`` (16 × 112 × 112) to ``stage_final`` (256 × 7 × 7).++The backbone carries no classification head; global-average-pool ``stage_final`` and add an ``nn.Linear`` for+classification, or feed the pyramid to a segmentation or detection neck.++Paper+-----+.. card:::link: https://arxiv.org/abs/2205.14756diff --git a/docs/source/models/hardnet.rst b/docs/source/models/hardnet.rstindex c3755856c..077850b0a 100644--- a/docs/source/models/hardnet.rst+++ b/docs/source/models/hardnet.rst@@ -5,6 +5,51 @@ HardNet:bdg-primary:`Local feature descriptor` :bdg-secondary:`MIT`+HardNet turns a ``32×32`` grayscale patch into a 128-dimensional L2-normalised descriptor, the same size as SIFT+but trained with a hard-negative margin loss. :class:`~kornia.feature.HardNet` is the descriptor only: pair it with+a detector such as :class:`~kornia.feature.KeyNetDetector`, extract patches from the local affine frames and match+the descriptors with :func:`~kornia.feature.match_snn`.++Run it+------++.. code-block:: python++ import torch+ from kornia.color import rgb_to_grayscale+ from kornia.feature import HardNet, KeyNetDetector, extract_patches_from_pyramid, get_laf_center, match_snn+ from kornia.io import load_image++ gray1 = rgb_to_grayscale(load_image("church_1.png")[None]) # (1, 1, H, W)+ gray2 = rgb_to_grayscale(load_image("church_2.png")[None])++ detector = KeyNetDetector(pretrained=True, num_features=1500).eval()+ hardnet = HardNet(pretrained=True).eval()+ with torch.no_grad():+ lafs1, _ = detector(gray1) # (1, N, 2, 3) local affine frames+ lafs2, _ = detector(gray2)+ patches1 = extract_patches_from_pyramid(gray1, lafs1)[0] # (N, 1, 32, 32)+ patches2 = extract_patches_from_pyramid(gray2, lafs2)[0]+ desc1, desc2 = hardnet(patches1), hardnet(patches2) # (N, 128), L2-normalised+ dists, idx = match_snn(desc1, desc2, th=0.9) # (M, 1) distances, (M, 2) index pairs++ pts1 = get_laf_center(lafs1)[0, idx[:, 0]] # (M, 2) matched (x, y) in image 1+ pts2 = get_laf_center(lafs2)[0, idx[:, 1]]++.. figure:: /_static/img/models/hardnet.jpg+ :align: center+ :alt: Eight 32 by 32 grayscale patches with their 128-dimensional descriptors shown as a heatmap, next to two church photographs joined by the matched keypoints.++ Eight of the KeyNet patches and their HardNet descriptors (left), and the second-nearest-neighbour ratio+ matches between the two views (right).++:class:`~kornia.feature.HardNet8` is the wider follow-up trained on more data, and+:class:`~kornia.feature.LocalFeature` bundles detector, orientation, shape and descriptor into one module+(see :class:`~kornia.feature.KeyNetHardNet`).++Paper+-----+.. card:::link: https://paperswithcode.com/paper/working-hard-to-know-your-neighbors-marginsdiff --git a/docs/source/models/index.rst b/docs/source/models/index.rstindex 23aa9aec0..486894455 100644--- a/docs/source/models/index.rst+++ b/docs/source/models/index.rst@@ -6,9 +6,9 @@ Kornia ModelsKornia ships a curated set of model architectures, each wrapped as a regular ``nn.Module``. Most of them come withpretrained weights that are downloaded on first use; MobileViT ships as an architecture only, for training or for-loading your own checkpoint. The pages below summarize each model's paper, task and licence. The builders that-construct them are documented on the :doc:`kornia.models </models>` API page, and the local-feature models under-:doc:`kornia.feature </feature>`.+loading your own checkpoint. Each page below opens with the shortest script that runs the model, shows what it+returns on a real input, and ends with the paper. The builders that construct the models are documented on the+:doc:`kornia.models </models>` API page, and the local-feature models under :doc:`kornia.feature </feature>`... list-table:::header-rows: 1diff --git a/docs/source/models/loftr.rst b/docs/source/models/loftr.rstindex 57b255bd5..6734be91f 100644--- a/docs/source/models/loftr.rst+++ b/docs/source/models/loftr.rst@@ -5,6 +5,45 @@ LoFTR:bdg-primary:`Image matching` :bdg-secondary:`Apache-2.0`+LoFTR matches two images without detecting keypoints first: a transformer establishes coarse pixel-wise matches+and refines them at a finer level, which is what makes it work on low-texture surfaces where detectors fail.+:class:`~kornia.feature.LoFTR` takes a dictionary with two grayscale images and returns the matched pixel+coordinates and a confidence per match.++Run it+------++.. code-block:: python++ import torch+ from kornia.color import rgb_to_grayscale+ from kornia.feature import LoFTR+ from kornia.io import load_image++ img1 = load_image("church_1.png")[None] # (1, 3, H, W) float in [0, 1]+ img2 = load_image("church_2.png")[None]++ matcher = LoFTR(pretrained="outdoor").eval() # 'outdoor' (MegaDepth) or 'indoor' (ScanNet)+ with torch.no_grad():+ out = matcher({"image0": rgb_to_grayscale(img1), "image1": rgb_to_grayscale(img2)})++ pts1, pts2, conf = out["keypoints0"], out["keypoints1"], out["confidence"] # (N, 2) (x, y) pixels, (N, 2), (N,)++.. figure:: /_static/img/models/loftr.jpg+ :align: center+ :alt: Two photographs of the same church side by side, with green lines connecting the LoFTR matches between them.++ Matches between two views of the same building; each green line joins ``keypoints0[i]`` to ``keypoints1[i]``.+ Feed the pairs to :class:`~kornia.geometry.ransac.RANSAC` or :func:`~kornia.geometry.homography.find_homography_dlt`+ to estimate the geometry between the views.++The two images may have different sizes, and ``out["batch_indexes"]`` tells which pair of a batch each match+belongs to. :class:`~kornia.feature.LocalFeatureMatcher` and the :doc:`image matching application+</applications/image_matching>` show LoFTR next to the detector-based pipelines.++Paper+-----+.. card:::link: https://paperswithcode.com/paper/loftr-detector-free-local-feature-matchingdiff --git a/docs/source/models/mobile_sam.rst b/docs/source/models/mobile_sam.rstindex 05ac42e97..38c51063d 100644--- a/docs/source/models/mobile_sam.rst+++ b/docs/source/models/mobile_sam.rst@@ -5,6 +5,47 @@ MobileSAM:bdg-primary:`Segmentation` :bdg-primary:`Visual prompting` :bdg-secondary:`Apache-2.0`+MobileSAM replaces SAM's ViT-H image encoder with a distilled TinyViT, making the model about 60× smaller while+keeping the same prompt encoder and mask decoder. In Kornia it is one more ``model_type`` of+:class:`~kornia.models.sam.SamConfig`, so it is used exactly like :doc:`SAM <segment_anything>` through the+:class:`~kornia.contrib.visual_prompter.VisualPrompter`.++Run it+------++.. code-block:: python++ import torch+ from kornia.io import load_image+ from kornia.models.sam import SamConfig+ from kornia.contrib.visual_prompter import VisualPrompter+ from kornia.geometry.boxes import Boxes+ from kornia.geometry.keypoints import Keypoints++ image = load_image("simba.png") # (3, H, W) float in [0, 1]++ prompter = VisualPrompter(SamConfig("mobile_sam", pretrained=True)) # ~40 MB checkpoint+ prompter.set_image(image) # encode once, query many times++ keypoints = Keypoints(torch.tensor([[[300.0, 90.0]]])) # (K, N, 2): K prompts of N (x, y) points, in pixels+ prediction = prompter.predict(keypoints=keypoints, keypoints_labels=torch.tensor([[1]])) # 1 = foreground+ best = prediction.binary_masks[0, prediction.scores.argmax()] # (H, W) bool++ box = Boxes.from_tensor(torch.tensor([[[180.0, 20.0, 380.0, 240.0]]]), mode="xyxy")+ mask = prompter.predict(boxes=box, multimask_output=False).binary_masks[0, 0]++.. figure:: /_static/img/models/mobile_sam.jpg+ :align: center+ :alt: A cartoon lion cub with a point and a box prompt drawn on it (left), and the MobileSAM masks for the point prompt and the box prompt overlaid in green (centre, right).++ MobileSAM masks for the same point and box prompts used on the :doc:`SAM page <segment_anything>`, with the+ predicted IoU scores in the titles.++For the full prompter API, checkpoint loading and prompter-free usage, refer to :doc:`segment_anything`.++Paper+-----+.. card:::link: https://arxiv.org/abs/2306.14289@@ -20,31 +61,3 @@ MobileSAM+++**Authors:** Chaoning Zhang, Dongshen Han, Yu Qiao, Jung Uk Kim, Sung-Ho Bae, Seungkyu Lee, Choong Seon Hong---Usage-~~~~~--MobileSAM is integrated directly into our Segment Anything implementation. Once you have loaded MobileSAM, you can use it just like SAM.--.. code:: python-- import torch- from kornia.models.sam import SamConfig- from kornia.contrib.visual_prompter import VisualPrompter- from kornia.geometry.keypoints import Keypoints-- image = torch.rand(3, 512, 512) # (3, H, W) float in [0, 1]- prompter = VisualPrompter(SamConfig("mobile_sam", pretrained=True))- prompter.set_image(image)-- keypoints = Keypoints(torch.tensor([[[400.0, 375.0]]])) # (B, N, 2) in (x, y)- labels = torch.tensor([[1]]) # (B, N); 1 = foreground point, 0 = background point-- prediction = prompter.predict(- keypoints=keypoints,- keypoints_labels=labels,- multimask_output=False,- )--For more information on how to use SAM and :py:class:`kornia.contrib.visual_prompter.VisualPrompter`, refer to :doc:`segment_anything`.diff --git a/docs/source/models/rt_detr.rst b/docs/source/models/rt_detr.rstindex bba638a99..7eaec9681 100644--- a/docs/source/models/rt_detr.rst+++ b/docs/source/models/rt_detr.rst@@ -5,27 +5,45 @@ RT-DETR:bdg-primary:`Object detection` :bdg-secondary:`Apache-2.0`+RT-DETR is a real-time, end-to-end transformer detector trained on MS-COCO. Kornia wraps it in+:class:`~kornia.contrib.object_detection.RTDETRDetectorBuilder`, which bundles the resize/normalise pre-processing+and the box post-processing, so a ``(B, 3, H, W)`` float image in ``[0, 1]`` goes in and one ``(D, 6)`` tensor per+image comes out with ``class_id, score, x, y, w, h`` in the original pixel coordinates.++Run it+------+.. code-block:: pythonfrom kornia.io import load_imagefrom kornia.contrib.object_detection import RTDETRDetectorBuilder- input_img = load_image("image.jpg")[None] # (1, 3, H, W) float in [0, 1]+ image = load_image("delorean.png")[None] # (1, 3, H, W) float in [0, 1]++ detector = RTDETRDetectorBuilder.build("rtdetr_r18vd") # downloads the COCO weights; runs at 640 px+ detections = detector(image) # list with one (D, 6) tensor per image: class id, score, x, y, w, h++ for class_id, score, x, y, w, h in detections[0].tolist():+ print(f"class {int(class_id)}: {score:.2f} at ({x:.0f}, {y:.0f}) size {w:.0f}x{h:.0f}")- # NOTE: available models: 'rtdetr_r18vd', 'rtdetr_r34vd', 'rtdetr_r50vd_m', 'rtdetr_r50vd', 'rtdetr_r101vd'.- # NOTE: recommended image scales: [480, 512, 544, 576, 608, 640, 640, 640, 672, 704, 736, 768, 800]- detector = RTDETRDetectorBuilder.build("rtdetr_r18vd", image_size=640)+.. figure:: /_static/img/models/rt_detr.jpg+ :align: center+ :alt: A photo of a car (left) and the same photo with two RT-DETR detections drawn as green boxes with class id and score (right).- # get the detections: one (D, 6) tensor per image with class id, score, x, y, w, h- detections = detector(input_img)+ Input image and the boxes returned by ``rtdetr_r18vd``, drawn with the detected class id+ (COCO id 2 is *car*) and confidence. Figures on these pages are rendered by ``docs/generate_model_examples.py``.- # draw the bounding boxes on the images directly- output = detector.visualize(input_img, detections, output_type="pil")- output[0].save("Kornia-RTDETR-output.png")+Detections are filtered with ``confidence_threshold=0.3`` by default; pass a different value to ``build`` to keep+more or fewer boxes. ``detector.visualize(image, detections, output_type="pil")`` draws the boxes for you, and+``detector.to_onnx("rtdetr-640.onnx", image_size=640)`` exports the model together with its pre- and post-processing.- # convert the whole model, including pre- and post-processing, to ONNX- detector.to_onnx("RTDETR-640.onnx", image_size=640)+Available variants, from fastest to most accurate: ``rtdetr_r18vd``, ``rtdetr_r34vd``, ``rtdetr_r50vd_m``,+``rtdetr_r50vd`` and ``rtdetr_r101vd``. When ``build`` is given a ``model_name`` it always resizes the input to the+640 px the weights were trained for and ignores ``image_size=``; that argument only applies together with a+``config=`` object, where multiples of 32 between 480 and 800 are recommended.+Paper+-----.. card:::link: https://arxiv.org/abs/2304.08069diff --git a/docs/source/models/segment_anything.rst b/docs/source/models/segment_anything.rstindex 7ce5cfa49..5c6ee63c0 100644--- a/docs/source/models/segment_anything.rst+++ b/docs/source/models/segment_anything.rst@@ -5,34 +5,48 @@ Segment Anything (SAM):bdg-primary:`Segmentation` :bdg-primary:`Visual prompting` :bdg-secondary:`Apache-2.0`-The Segment Anything Model (SAM) produces high quality object masks from input prompts such as points or boxes, and it-can be used to generate masks for all objects in an image.+The Segment Anything Model (SAM) produces high quality object masks from input prompts such as points or boxes.+Kornia ships the model as :class:`~kornia.models.sam.Sam` and a high-level+:class:`~kornia.contrib.visual_prompter.VisualPrompter` that encodes an image once and answers any number of prompt+queries against it, returning a :class:`~kornia.models.structures.SegmentationResults` with the mask logits, the+predicted IoU scores and thresholded ``binary_masks``.-.. card::- :link: https://segment-anything.com/+Run it+------- **Segment Anything**- ^^^- **Abstract:** We introduce the Segment Anything (SAM) project: a new task, model, and dataset for image- segmentation. Using our efficient model in a data collection loop, we built the largest segmentation- dataset to date (by far), with over 1 billion masks on 11M licensed and privacy respecting images. The- model is designed and trained to be promptable, so it can transfer zero-shot to new image distributions- and tasks. We evaluate its capabilities on numerous tasks and find that its zero-shot performance is impressive- -- often competitive with or even superior to prior fully supervised results. We are releasing the Segment Anything- Model (SAM) and corresponding dataset (SA-1B) of 1B masks and 11M images at https://segment-anything.com to foster- research into foundation models for computer vision.+.. code-block:: python- **Tasks:** Segmentation+ import torch+ from kornia.io import load_image+ from kornia.models.sam import SamConfig+ from kornia.contrib.visual_prompter import VisualPrompter+ from kornia.geometry.boxes import Boxes+ from kornia.geometry.keypoints import Keypoints- **Datasets:** SA-1B+ image = load_image("simba.png") # (3, H, W) float in [0, 1]- **Licence:** Apache+ prompter = VisualPrompter(SamConfig("vit_b", pretrained=True)) # vit_h, vit_l, vit_b or mobile_sam+ prompter.set_image(image) # encode once, query many times- +++- **Authors:** Alexander Kirillov and Eric Mintun and Nikhila Ravi and Hanzi Mao and Chloe Rolland and Laura- Gustafson and Alex Berg and Wan-Yen Lo and Piotr Dollar and Ross Girshick+ # a foreground point (label 1; 0 would be background) -> three candidate masks+ keypoints = Keypoints(torch.tensor([[[300.0, 90.0]]])) # (K, N, 2): K prompts of N (x, y) points, in pixels+ prediction = prompter.predict(keypoints=keypoints, keypoints_labels=torch.tensor([[1]]))+ best = prediction.binary_masks[0, prediction.scores.argmax()] # (H, W) bool, highest predicted IoU++ # a box prompt -> a single mask+ box = Boxes.from_tensor(torch.tensor([[[180.0, 20.0, 380.0, 240.0]]]), mode="xyxy")+ prediction = prompter.predict(boxes=box, multimask_output=False)+ mask = prediction.binary_masks[0, 0] # (H, W) bool++.. figure:: /_static/img/models/segment_anything.jpg+ :align: center+ :alt: A cartoon lion cub with a point and a box prompt drawn on it (left), and the SAM masks for the point prompt and the box prompt overlaid in green (centre, right).+ ``vit_b`` masks for the point prompt (best of the three candidates) and the box prompt, with the predicted IoU+ scores in the titles.+The sections below cover the full prompter API, building :class:`~kornia.models.sam.Sam` from a config or a+checkpoint, and calling the model without the prompter.How to use SAM from Kornia--------------------------@@ -157,14 +171,16 @@ can be used to query the SAM model for image masks.)#------------------------------------------------- # or run the prediction using the previous logits+ # or run the prediction using the previous logits as a mask prompt: one (K, 1, 256, 256)+ # low-resolution mask per query, so pick the candidate with the best predicted IoU+ best = prediction.scores[0].argmax()prediction = prompter.predict(- masks=prediction.logits,+ masks=prediction.logits[:, best : best + 1],multimask_output=True,)- # The `prediction` is a SegmentationResults dataclass with the masks, scores and logits- print(prediction.masks.shape)+ # The `prediction` is a SegmentationResults dataclass with the logits, scores and thresholded binary masks+ print(prediction.binary_masks.shape)print(prediction.scores)print(prediction.logits.shape)@@ -313,3 +329,31 @@ This is a simple example of how to use the loaded SAM model directly. We recomme# Binary masks, thresholded from the logitsmasks = prediction.binary_masks+++Paper+-----++.. card::+ :link: https://segment-anything.com/++ **Segment Anything**+ ^^^+ **Abstract:** We introduce the Segment Anything (SAM) project: a new task, model, and dataset for image+ segmentation. Using our efficient model in a data collection loop, we built the largest segmentation+ dataset to date (by far), with over 1 billion masks on 11M licensed and privacy respecting images. The+ model is designed and trained to be promptable, so it can transfer zero-shot to new image distributions+ and tasks. We evaluate its capabilities on numerous tasks and find that its zero-shot performance is impressive+ -- often competitive with or even superior to prior fully supervised results. We are releasing the Segment Anything+ Model (SAM) and corresponding dataset (SA-1B) of 1B masks and 11M images at https://segment-anything.com to foster+ research into foundation models for computer vision.++ **Tasks:** Segmentation++ **Datasets:** SA-1B++ **Licence:** Apache++ ++++ **Authors:** Alexander Kirillov and Eric Mintun and Nikhila Ravi and Hanzi Mao and Chloe Rolland and Laura+ Gustafson and Alex Berg and Wan-Yen Lo and Piotr Dollar and Ross Girshickdiff --git a/docs/source/models/sold2.rst b/docs/source/models/sold2.rstindex 962d29e5a..de0a136a2 100644--- a/docs/source/models/sold2.rst+++ b/docs/source/models/sold2.rst@@ -5,6 +5,46 @@ SOLD2:bdg-primary:`Line detection` :bdg-primary:`Line matching` :bdg-secondary:`MIT`+SOLD² detects line segments and describes them in one network, so lines can be matched across views the way+keypoints are. :class:`~kornia.feature.SOLD2` returns the segments of each image together with a dense descriptor+map, and its ``match`` method pairs the segments of two images. :class:`~kornia.feature.SOLD2_detector` is the+detector alone.++Run it+------++.. code-block:: python++ import torch+ from kornia.color import rgb_to_grayscale+ from kornia.feature import SOLD2+ from kornia.io import load_image++ img1 = load_image("church_1.png")[None] # (1, 3, H, W) float in [0, 1]+ img2 = load_image("church_2.png")[None]+ gray = rgb_to_grayscale(torch.cat([img1, img2])) # (2, 1, H, W)++ sold2 = SOLD2(pretrained=True).eval()+ with torch.no_grad():+ out = sold2(gray)+ lines1, lines2 = out["line_segments"] # list of (N, 2, 2) endpoints in (y, x) pixels, one per image+ desc = out["dense_desc"] # (2, 128, H/4, W/4)+ matches = sold2.match(lines1, lines2, desc[0:1], desc[1:2]) # (N1,) index into lines2, -1 = no match++ matched1, matched2 = lines1[matches != -1], lines2[matches[matches != -1]]++.. figure:: /_static/img/models/sold2.jpg+ :align: center+ :alt: Two photographs of the same church with the detected line segments drawn in green, and a third panel where matched lines are drawn in the same colour on both images.++ Segments detected in each image (left, centre) and the matched pairs, one colour per pair (right).++The input is a grayscale batch; ``out`` also carries the raw ``junction_heatmap`` and ``line_heatmap`` maps. The+detection and matching thresholds are set through the ``config`` argument of :class:`~kornia.feature.SOLD2`.++Paper+-----+.. card:::link: https://arxiv.org/abs/2104.03362diff --git a/docs/source/models/tiny_vit.rst b/docs/source/models/tiny_vit.rstindex 82afe1aa6..51edf6c1f 100644--- a/docs/source/models/tiny_vit.rst+++ b/docs/source/models/tiny_vit.rst@@ -7,6 +7,45 @@ TinyViT:bdg-primary:`Image classification` :bdg-primary:`Detection`+TinyViT is a family of small vision transformers (5M, 11M and 21M parameters) distilled from large teachers on+ImageNet-22k. Kornia's :class:`~kornia.models.tiny_vit.TinyViT` ships the ImageNet-1k classification heads, so it+works out of the box as a classifier, and its backbone is the image encoder behind :doc:`MobileSAM <mobile_sam>`.++Run it+------++.. code-block:: python++ import torch+ from kornia.io import load_image+ from kornia.geometry import resize+ from kornia.models.tiny_vit import TinyViT++ image = resize(load_image("panda.jpg")[None], (224, 224)) # (1, 3, 224, 224) float in [0, 1]++ model = TinyViT.from_config("5m", pretrained=True).eval() # '5m', '11m' or '21m'; ImageNet-1k head+ with torch.no_grad():+ logits = model(image) # (1, 1000)++ top5 = logits.softmax(-1).topk(5)+ print(top5.indices, top5.values) # ImageNet class ids and probabilities++.. figure:: /_static/img/models/tiny_vit.jpg+ :align: center+ :alt: A panda photo next to a bar chart of the five most probable ImageNet classes, with giant panda far ahead.++ Top-5 ImageNet classes predicted by TinyViT-5M for the input on the left.++``pretrained`` also accepts ``'in22k'`` and, for ``'21m'``, the higher-resolution ``'in1k_384'`` and+``'in1k_512'`` checkpoints; pass ``img_size=`` to run at another resolution and the attention biases are+interpolated. The ImageNet-22k checkpoint carries a 21841-class head, so load it with+``TinyViT.from_config("5m", pretrained="in22k", num_classes=21841)``: with the default ``num_classes=1000`` the+head does not match, is reset to zeros with a warning and the model returns all-zero logits. For feature extraction+replace the head instead: ``model.head = torch.nn.Identity()`` makes the model return the pooled embedding.++Paper+-----+.. card:::link: https://arxiv.org/abs/2207.10666@@ -23,18 +62,3 @@ TinyViT.. image:: https://github.com/microsoft/Cream/blob/main/TinyViT/.figure/framework.png?raw=true:align: center--Usage-~~~~~--You can use TinyViT models as follows.--.. code:: python-- import torch- from kornia.models.tiny_vit import TinyViT-- model = TinyViT.from_config("5m", pretrained=True) # ImageNet-1k pre-trained-- img = torch.rand(1, 3, 224, 224)- out = model(img) # (1, 1000) ImageNet logitsdiff --git a/docs/source/models/vit.rst b/docs/source/models/vit.rstindex 9169ed6ce..69104d2c8 100644--- a/docs/source/models/vit.rst+++ b/docs/source/models/vit.rst@@ -7,53 +7,44 @@ Vision Transformer (ViT):bdg-primary:`Image classification` :bdg-secondary:`Apache-2.0`-.. card::- :link: https://paperswithcode.com/paper/an-image-is-worth-16x16-words-transformers-1+:class:`~kornia.models.vit.VisionTransformer` is a plain ViT encoder: the image is cut into ``patch_size`` squares,+each patch becomes a token, a class token is prepended and a stack of transformer blocks mixes them. It returns+one embedding per token, ``(B, 1 + N, embed_dim)``, with the class token first, and has **no classification head**.+``VisionTransformer.from_config(..., pretrained=True)`` loads the AugReg ImageNet-21k weights for ``vit_ti/16``,+``vit_s/16``, ``vit_s/32``, ``vit_b/16``, ``vit_b/32`` and ``vit_l/16``; the plain constructor gives a randomly+initialised model of any size.- **ViT: An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale**- ^^^- **Abstract:** While the Transformer architecture has become the de-facto standard for natural language processing tasks, its applications to computer vision remain limited. In vision, attention is either applied in conjunction with convolutional networks, or used to replace certain components of convolutional networks while keeping their overall structure in place. We show that this reliance on CNNs is not necessary and a pure transformer applied directly to sequences of image patches can perform very well on image classification tasks. When pre-trained on large amounts of data and transferred to multiple mid-sized or small image recognition benchmarks (ImageNet, CIFAR-100, VTAB, etc. ), Vision Transformer (ViT) attains excellent results compared to state-of-the-art convolutional networks while requiring substantially fewer computational resources to train.+Run it+------- **Tasks:** Image Classification, Fine-Grained Image Classification, Document Image Classification+.. code-block:: python- **Datasets:** CIFAR-10, ImageNet, CIFAR-100-- **Conference:** ICLR 2021+ import torch+ from kornia.io import load_image+ from kornia.geometry import resize+ from kornia.models.vit import VisionTransformer- **Licence:** Apache-2.0+ image = resize(load_image("panda.jpg")[None], (224, 224)) # (1, 3, 224, 224) float in [0, 1]- +++- **Authors:** Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby+ vit = VisionTransformer.from_config("vit_b/16", pretrained=True).eval() # AugReg ImageNet-21k weights+ with torch.no_grad():+ tokens = vit(image) # (1, 197, 768): class token + 14×14 patch tokens+ cls, patches = tokens[:, 0], tokens[:, 1:] # (1, 768) and (1, 196, 768)-.. image:: https://github.com/google-research/vision_transformer/raw/main/vit_figure.png+.. figure:: /_static/img/models/vit.jpg:align: center+ :alt: A panda photo with the 16-pixel patch grid drawn on it, a 14x14 heatmap of patch-token norms, and a heatmap of the output token embeddings.+ The 14×14 patch grid a 224 px image is split into, the norm of each output patch token of the pretrained+ ``vit_b/16`` on that grid, and the first 96 dimensions of all 197 output tokens.-Kornia-ViT+Add a head-----------We provide the operator :py:class:`~kornia.models.vit.VisionTransformer` that is meant to be used across tasks.-One can use the *ViT* in Kornia as follows:--.. code:: python-- import torch- from kornia.models.vit import VisionTransformer-- img = torch.rand(1, 3, 224, 224)- vit = VisionTransformer(image_size=224, patch_size=16)- out = vit(img) # (1, 197, 768): the class token followed by 196 patch tokens--Usage-~~~~~--``kornia-vit`` does not include any classification head. The backbone returns one embedding per token,-``(B, 1 + N, hidden_dim)``, with the class token first; a classifier reads the class token and adds a linear-head using standard PyTorch modules:+A classifier reads the class token and adds a linear layer on top of the pretrained encoder:-.. code:: python+.. code-block:: python- import torchimport torch.nn as nnfrom kornia.models.vit import VisionTransformer@@ -61,42 +52,37 @@ head using standard PyTorch modules:class Classifier(nn.Module):def __init__(self, num_classes: int = 1000) -> None:super().__init__()- self.backbone = VisionTransformer(image_size=224, patch_size=16)- self.head = nn.Linear(768, num_classes) # 768 is the default hidden_dim+ self.backbone = VisionTransformer.from_config("vit_b/16", pretrained=True)+ self.head = nn.Linear(768, num_classes) # 768 is the embed_dim of the base models- def forward(self, x: torch.Tensor) -> torch.Tensor:- tokens = self.backbone(x) # (B, 197, 768)- return self.head(tokens[:, 0]) # (B, num_classes), from the class token+ def forward(self, x):+ return self.head(self.backbone(x)[:, 0]) # (B, num_classes) from the class token+The same pattern gives multi-task or dense heads: keep the class token for image-level outputs, or reshape the+196 patch tokens back to a ``14 × 14`` map for detection and segmentation necks. To build a model of another size+from scratch, ``VisionTransformer(image_size, patch_size, embed_dim, depth, num_heads, dropout_rate, dropout_attn)``+exposes the layout directly.- img = torch.rand(1, 3, 224, 224)- out = Classifier()(img) # (1, 1000)- scores = out.argmax(-1) # (1,)+Paper+------Beyond simple image classification, the API is flexible enough to design your own pipelines, e.g.-for multi-task learning, object detection or segmentation. We show an example of a multi-task-module with two different classification heads:+.. card::+ :link: https://paperswithcode.com/paper/an-image-is-worth-16x16-words-transformers-1-.. code:: python+ **ViT: An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale**+ ^^^+ **Abstract:** While the Transformer architecture has become the de-facto standard for natural language processing tasks, its applications to computer vision remain limited. In vision, attention is either applied in conjunction with convolutional networks, or used to replace certain components of convolutional networks while keeping their overall structure in place. We show that this reliance on CNNs is not necessary and a pure transformer applied directly to sequences of image patches can perform very well on image classification tasks. When pre-trained on large amounts of data and transferred to multiple mid-sized or small image recognition benchmarks (ImageNet, CIFAR-100, VTAB, etc. ), Vision Transformer (ViT) attains excellent results compared to state-of-the-art convolutional networks while requiring substantially fewer computational resources to train.- import torch- import torch.nn as nn- from kornia.models.vit import VisionTransformer+ **Tasks:** Image Classification, Fine-Grained Image Classification, Document Image Classification- class MultiTaskTransformer(nn.Module):- def __init__(self) -> None:- super().__init__()- self.transformer = VisionTransformer(- image_size=224, patch_size=16)- self.head1 = nn.Linear(768, 10) # Example: 768 is the default hidden_dim- self.head2 = nn.Linear(768, 50)-- def forward(self, x: torch.Tensor):- cls_token = self.transformer(x)[:, 0] # (B, 768)- return {- "head1": self.head1(cls_token),- "head2": self.head2(cls_token),- }--.. tip::- More heads, examples and a training API are coming soon!+ **Datasets:** CIFAR-10, ImageNet, CIFAR-100++ **Conference:** ICLR 2021++ **Licence:** Apache-2.0++ ++++ **Authors:** Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby++.. image:: https://github.com/google-research/vision_transformer/raw/main/vit_figure.png+ :align: centerdiff --git a/docs/source/models/vit_mobile.rst b/docs/source/models/vit_mobile.rstindex 63a01af3b..bb66ece00 100644--- a/docs/source/models/vit_mobile.rst+++ b/docs/source/models/vit_mobile.rst@@ -7,57 +7,68 @@ MobileViT:bdg-primary:`Image classification` :bdg-primary:`Detection` :bdg-primary:`Segmentation`-.. card::- :link: https://arxiv.org/abs/2110.02178+MobileViT interleaves MobileNetV2 blocks with small transformer blocks that treat patches as tokens, giving a+light-weight backbone with a global receptive field. :class:`~kornia.models.vit_mobile.MobileViT` implements the+``xxs``, ``xs`` and ``s`` variants as an **architecture only** (random initialisation, no classification head) and+returns a stride-32 feature map.- **MobileViT: Light-weight, General-purpose, and Mobile-friendly Vision Transformer**- ^^^- **Abstract:** Light-weight convolutional neural networks (CNNs) are the de-facto for mobile vision tasks. Their spatial inductive biases allow them to learn representations with fewer parameters across different vision tasks. However, these networks are spatially local. To learn global representations, self-attention-based vision trans-formers (ViTs) have been adopted. Unlike CNNs, ViTs are heavy-weight. In this paper, we ask the following question: is it possible to combine the strengths of CNNs and ViTs to build a light-weight and low latency network for mobile vision tasks? Towards this end, we introduce MobileViT, a light-weight and general-purpose vision transformer for mobile devices. MobileViT presents a different perspective for the global processing of information with transformers, i.e., transformers as convolutions. Our results show that MobileViT significantly outperforms CNN- and ViT-based networks across different tasks and datasets. On the ImageNet-1k dataset, MobileViT achieves top-1 accuracy of 78.4% with about 6 million parameters, which is 3.2% and 6.2% more accurate than MobileNetv3 (CNN-based) and DeIT (ViT-based) for a similar number of parameters. On the MS-COCO object detection task, MobileViT is 5.7% more accurate than Mo-bileNetv3 for a similar number of parameters.+Run it+------- **Tasks:** Image Classification, Object Detection, Semantic Segmentation+.. code-block:: python- **Datasets:** ImageNet, MS-COCO, PASCAL VOC+ import torch+ from kornia.models.vit_mobile import MobileViT- +++- **Authors:** Sachin Mehta, Mohammad Rastegari+ mvit = MobileViT(mode="xxs") # 'xxs', 'xs' or 's'; random init-.. image:: https://user-images.githubusercontent.com/67839539/136470152-2573529e-1a24-4494-821d-70eb4647a51d.png+ image = torch.rand(1, 3, 256, 256)+ features = mvit(image) # (1, 320, 8, 8) feature map, stride 32++.. figure:: /_static/img/models/vit_mobile.jpg:align: center+ :alt: A 256 by 256 panda photo next to an 8 by 8 heatmap of the mean absolute activation of the output feature map.+ The 256×256 input and the mean absolute activation of the ``(320, 8, 8)`` output of MobileViT-XXS. With random+ weights the map is not meaningful yet; train the model or load your own checkpoint.-Kornia-MobileViT-----------------+Add a head+-----------We provide :py:class:`~kornia.models.vit_mobile.MobileViT` which can be used for many downstream tasks, e.g., classification, object detection and semantic segmentation.-One can use the *MobileViT* in Kornia as follows:+Pool the feature map and add a linear layer for classification; the output channel count is 320 for ``xxs``,+384 for ``xs`` and 640 for ``s``:-.. code:: python+.. code-block:: pythonimport torch+ import torch.nn as nnfrom kornia.models.vit_mobile import MobileViT- img = torch.rand(1, 3, 256, 256)- mvit = MobileViT(mode='xxs')- out = mvit(img) # (1, 320, 8, 8) feature map+ classifier = nn.Sequential(+ MobileViT(mode="xxs"),+ nn.AdaptiveAvgPool2d(1),+ nn.Flatten(),+ nn.Linear(320, 1000),+ )+ logits = classifier(torch.rand(1, 3, 256, 256)) # (1, 1000)-Usage-~~~~~+Paper+------Similar to ``Kornia-ViT``, ``Kornia-MobileViT`` does not include any classification head. But you can add it simply by doing:+.. card::+ :link: https://arxiv.org/abs/2110.02178-.. code:: python+ **MobileViT: Light-weight, General-purpose, and Mobile-friendly Vision Transformer**+ ^^^+ **Abstract:** Light-weight convolutional neural networks (CNNs) are the de-facto for mobile vision tasks. Their spatial inductive biases allow them to learn representations with fewer parameters across different vision tasks. However, these networks are spatially local. To learn global representations, self-attention-based vision trans-formers (ViTs) have been adopted. Unlike CNNs, ViTs are heavy-weight. In this paper, we ask the following question: is it possible to combine the strengths of CNNs and ViTs to build a light-weight and low latency network for mobile vision tasks? Towards this end, we introduce MobileViT, a light-weight and general-purpose vision transformer for mobile devices. MobileViT presents a different perspective for the global processing of information with transformers, i.e., transformers as convolutions. Our results show that MobileViT significantly outperforms CNN- and ViT-based networks across different tasks and datasets. On the ImageNet-1k dataset, MobileViT achieves top-1 accuracy of 78.4% with about 6 million parameters, which is 3.2% and 6.2% more accurate than MobileNetv3 (CNN-based) and DeIT (ViT-based) for a similar number of parameters. On the MS-COCO object detection task, MobileViT is 5.7% more accurate than Mo-bileNetv3 for a similar number of parameters.- import torch- import torch.nn as nn- from kornia.models.vit_mobile import MobileViT+ **Tasks:** Image Classification, Object Detection, Semantic Segmentation- classifier = nn.Sequential(- MobileViT(mode='xxs'),- nn.AvgPool2d(256 // 32, 1),- nn.Flatten(),- nn.Linear(320, 1000)- )+ **Datasets:** ImageNet, MS-COCO, PASCAL VOC++ ++++ **Authors:** Sachin Mehta, Mohammad Rastegari- img = torch.rand(1, 3, 256, 256)- out = classifier(img) # 1x1000+.. image:: https://user-images.githubusercontent.com/67839539/136470152-2573529e-1a24-4494-821d-70eb4647a51d.png+ :align: centerdiff --git a/docs/source/models/yunet.rst b/docs/source/models/yunet.rstindex 8fe3603b3..7c9b2d766 100644--- a/docs/source/models/yunet.rst+++ b/docs/source/models/yunet.rst@@ -7,6 +7,40 @@ YuNet:bdg-primary:`Face detection` :bdg-secondary:`Apache-2.0`+YuNet is a millisecond-level face detector that predicts a box, a confidence and five facial landmarks (eyes, nose,+mouth corners) per face. Kornia exposes it as :class:`~kornia.contrib.FaceDetector`, which takes a ``(B, 3, H, W)``+image with pixel values in ``[0, 255]`` and returns one ``(N, 15)`` tensor per image; wrap each row in+:class:`~kornia.contrib.FaceDetectorResult` to read the fields by name.++Run it+------++.. code-block:: python++ from kornia.io import load_image+ from kornia.contrib import FaceDetector, FaceDetectorResult, FaceKeypoint++ image = load_image("crowd.jpg")[None] * 255.0 # (1, 3, H, W); YuNet expects pixel values in [0, 255]++ detector = FaceDetector() # downloads the YuNet weights when constructed+ faces = [FaceDetectorResult(f) for f in detector(image)[0]] # one result per detected face++ for face in faces:+ print(face.score, face.xmin, face.ymin, face.xmax, face.ymax, face.get_keypoint(FaceKeypoint.NOSE))++.. figure:: /_static/img/models/yunet.jpg+ :align: center+ :alt: A crowd photo (left) and the same photo with a green box and five yellow landmarks on each detected face (right).++ Boxes and landmarks returned by ``FaceDetector()`` with its defaults (``confidence_threshold=0.3``,+ ``nms_threshold=0.3``) on a 900×587 crowd image.++``FaceDetector(confidence_threshold=..., nms_threshold=..., top_k=..., keep_top_k=...)`` tunes the post-processing.+See :doc:`the face detection application page </applications/face_detection>` for a complete script that draws the results.++Paper+-----+.. card:::link: https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=9429909diff --git a/kornia/contrib/visual_prompter.py b/kornia/contrib/visual_prompter.pyindex c194d6dc7..d3df414bc 100644--- a/kornia/contrib/visual_prompter.py+++ b/kornia/contrib/visual_prompter.py@@ -239,7 +239,9 @@ class VisualPrompter:if isinstance(masks, torch.Tensor):self._valid_masks(masks)- data = self._transform_prompts(*to_transform, data_keys=data_keys)+ # No prompt at all is a valid query (SAM then predicts from the image embedding alone); the+ # augmentation container cannot be called with nothing to transform.+ data = self._transform_prompts(*to_transform, data_keys=data_keys) if to_transform else {}if "keypoints" in data and isinstance(data["keypoints"], Keypoints):kpts_tensor = data["keypoints"].to_tensor()diff --git a/tests/contrib/test_visual_prompter.py b/tests/contrib/test_visual_prompter.pyindex acad3c7aa..3a3f13c91 100644--- a/tests/contrib/test_visual_prompter.py+++ b/tests/contrib/test_visual_prompter.py@@ -80,6 +80,18 @@ class TestVisualPrompter(BaseTester):assert results.logits.shape == (batch_size, 3, 256, 256)+ @pytest.mark.slow+ def test_predict_without_prompts(self, device, dtype):+ if dtype not in (torch.float32, torch.float16):+ pytest.skip("VisualPrompter (SAM) primarily supports float32 and float16")+ prompter = VisualPrompter(SamConfig("mobile_sam"), device=device, dtype=dtype)+ prompter.set_image(torch.rand(3, 256, 256, device=device, dtype=dtype))++ results = prompter.predict(multimask_output=True) # no keypoints, boxes or masks++ assert results.logits.shape == (1, 3, 256, 256)+ assert results.scores.shape == (1, 3)+def test_gradcheck(self, device):pytest.skip("Gradcheck is not currently applicable for VisualPrompter inference.")