kornia.contrib#
Contributed image operations, and task-level wrappers that pair a kornia model with its pre- and post-processing. The image operations:
Sliding-window patches:
extract_tensor_patches()cuts them,combine_tensor_patches()puts them back and averages overlaps, andcompute_padding()gives the padding that makes the windows fit.Connected components:
connected_components()labels them with a fixed number of pooling steps andconnected_components_union_find()exactly; Choosing a labeling method compares the two.Distances to the nearest positive pixel:
distance_transform().Histogram matching to a template:
histogram_matching(), built on the 1-D interpolationinterp().Plasma-fractal noise maps:
diamond_square().K-means clustering:
KMeans.A Python callable as a module:
Lambda.The geometry of one augmentation pipeline call:
audit(), described in Augmentation Geometry Audit.
Augmentation Geometry Audit#
kornia.contrib.augmentation_audit.audit executes an
AugmentationSequential once and returns (outputs, report). It records the
executed operation order, native parameter snapshots, image shapes, effective
flags, and coordinate matrices. It also checks keypoint and box round trips against
the labels actually returned by the pipeline. The ordinary forward path has no
reporting overhead.
For example, a training-data validation step can inspect coordinates and export a report without storing image pixels:
import json
from pathlib import Path
import torch
import kornia.augmentation as K
from kornia.contrib import audit
image = torch.rand(2, 3, 32, 48)
points = torch.tensor([[[4., 6.], [20., 15.]]]).expand(2, -1, -1)
pipeline = K.AugmentationSequential(
K.RandomHorizontalFlip(p=1.0),
K.RandomAffine(degrees=15, p=1.0),
data_keys=["input", "keypoints"],
)
(image_out, points_out), report = audit(
pipeline, image, points, roundtrip_tolerance=1e-3, out_of_frame_tolerance=0.25,
)
print(report.summary())
point_audit = report.spatial[0]
assert report.geometry_status == "available"
assert torch.equal(point_audit.roundtrip_valid_count, point_audit.count)
assert bool((point_audit.roundtrip_max <= 1e-3).all())
Path("augmentation-audit.json").write_text(report.to_json(), encoding="utf-8")
assert json.loads(report.to_json())["image_reconstruction_evaluated"] is False
# Native parameter snapshots replay the run with this pipeline configuration.
replay_image, replay_points = pipeline(image, points, params=report.params)
torch.testing.assert_close(replay_image, image_out)
torch.testing.assert_close(replay_points, points_out)
Interpreting the report#
matrixmaps original pixel coordinates to final image coordinates, includingRandomCropprepadding when it belongs to the returned image mapping.inverse_matrixis its algebraic inverse, with nonfinite entries for batches that cannot be inverted.invertibleidentifies those batches explicitly.geometry_status="available"describes matrix availability rather than spatial alignment. Round trips inverse-map the returned labels and compare them with the source. An invertible matrix can therefore accompany a nonzero label error.Keypoint errors are Euclidean distances. Box errors are symmetric Hausdorff distances between corner sets. Tensor box exports take axis-aligned envelopes, so rotation or shear can introduce measurable loss;
Boxesobjects retain the transformed quadrilateral.Per-batch statistics include only finite errors. Inspect
roundtrip_valid_counttogether with the mean, median, or maximum. Empty labels and unavailable inverses do not produce a successful zero-error measurement.Out-of-frame counts use inclusive pixel centers from zero to
width - 1andheight - 1for keypoints and for tensor boxes under the bare"bbox"and"bbox_xyxy"keys. Exclusive boxes,Boxesobjects and"bbox_xywh"tensors, are checked on their edges, from zero towidthandheight, and mapped back on pixel centres for the round trip. A box is outside when any corner is outside. Nonfinite labels are counted separately.Box rows that the pipeline returns without a box are left out of every count and statistic: rows a
Boxesobject marks invalid, and the all-zero rows that replace zero-extent rows under"bbox_xywh". Input rows that hold no box come back that way. Zero rows under the bare"bbox"and"bbox_xyxy"keys are coordinates and are counted.Crop matrices can invert coordinates even after image content has been discarded. The report records this distinction and never evaluates image reconstruction. Cropping and downsampling emit possible content-loss warnings.
A
RandomCropskipped for the whole batch leaves images and labels unchanged, including withpaddingorpad_if_needed(#4473). Manually supplied parameters that apply a shape-changing operation to only some rows raiseValueError, as the ordinary forward call does, because the skipped rows cannot keep their shape (#4497). Withp=1.0, p_batch=1.0, an overriddenbatch_probis not consulted: every image row is cropped and the labels move with it (#5585). Passp < 1to skip rows by hand.Non-rigid and unknown operations are explicitly unsupported for matrix composition. A transformation-matrix identity fallback is not treated as proof of correspondence. Supported neighboring operations remain in the provenance.
Captured operations must match the ordered operations selected by the sampled parameters. Missing or out-of-order captures make the geometry unsupported.
RandAugment,AutoAugment,TrivialAugment, and custom sequential subclasses are currently opaque and therefore unsupported when selected.
Diagnostics are computed in float64 for a float64 image and in float32 otherwise, and disable autocast for matrix composition and inverse mapping. The pipeline forward itself inherits the caller’s autocast context, so returned labels remain identical to an ordinary forward call. Autocast can quantize spatial-label propagation and produce real round-trip errors; the report does not suppress those differences.
The API accepts one nonempty BCHW image first, followed by optional batched masks,
keypoints, or boxes in the usual positional data_keys forms. Dictionaries,
ragged or unbatched inputs, video, patch, and 3D containers, and modules registered
under multiple names are unsupported. Repeated sampled operations and nested
built-in 2D sequences are supported. Spatial operations must preserve label shapes
and cardinality. This is an eager diagnostic utility and the same stateful pipeline
must not be audited concurrently.
params is an independent, detached native replay snapshot. JSON is a portable
diagnostic export rather than a replay loader. Tensor exports include dtype, device,
and shape metadata; nonfinite values become JSON null.
- kornia.contrib.audit(sequence, *args, params=None, data_keys=None, roundtrip_tolerance=1e-3, out_of_frame_tolerance=0.0)[source]#
Run an augmentation pipeline once and return its outputs with a geometry audit report.
outputs, report = audit(sequence, image, *labels)runssequenceonce on a nonempty(B, C, H, W)image followed by optional batched masks ((B, C, H, W)or(B, H, W)), keypoints or boxes, in the order ofdata_keys.outputshas the structure, values and gradients of an ordinary forward call, andreportis anAugmentationAuditReportof the executed operations, their composed matrix and the round-trip errors of every keypoint and box input.paramsanddata_keyshave the meaning they have inforward().Unknown or non-rigid operations run normally and make the composed geometry unsupported. Keypoints and boxes through
RandomElasticTransform,RandomThinPlateSplineorRandomFisheyeraiseNotImplementedError, as in the sequence (#4420). The audit runs eagerly; do not audit the same stateful sequence concurrently.- Convention:
Augmentation Geometry Audit states the direction of
report.matrix, the pixel-centre rectangle of the out-of-frame test, the dtypes of the diagnostics and the inputs it accepts.
- Parameters:
sequence (
AugmentationSequential) – The 2D augmentation sequence to execute and inspect.args (
Union[Tensor,List[Tensor],Boxes,Keypoints]) – Image and optional spatial inputs accepted by the sequence.params (
list[ParamItem] |None, optional) – Optional sampled parameters to replay. Default:Nonedata_keys (
list[str|int|DataKey] |None, optional) – Optional positional data-key override. Default:Noneroundtrip_tolerance (
float, optional) – Nonnegative pixel threshold for round-trip warnings. Default:1e-3out_of_frame_tolerance (
float, optional) – Fraction in[0, 1]above which an input gets a warning. Default:0.0
- Return type:
tuple[Union[Tensor,List[Tensor],Boxes,Keypoints,list[Union[Tensor,List[Tensor],Boxes,Keypoints]],dict[str,Union[Tensor,List[Tensor],Boxes,Keypoints]]],AugmentationAuditReport]- Returns:
A pair
(outputs, report).- Raises:
ValueError – if a tolerance is out of range,
data_keysdo not start with the only image or do not match the inputs, a data key is unsupported, the image is not a nonempty(B, C, H, W)tensor, or a label input is unbatched, ragged or on another device; if the pipeline holds a video, patch or 3D augmentation or a module registered under two names, or an operation changes the batch, the layout or the label cardinality.
See also
forward(): the same call without a report.AugmentationAuditReport: the report this returns.
- class kornia.contrib.AugmentationAuditReport(inputs, output_shape, steps, params, configured_extra_args, geometry_status, matrix, inverse_matrix, invertible, spatial, warnings, roundtrip_tolerance, out_of_frame_tolerance, image_reconstruction_evaluated=False)[source]#
Hold the executed operations, composed matrix and label diagnostics of one audit call.
outputs, report = audit(sequence, image, ...)returns it.report.summary()describes it in text,report.to_dict()andreport.to_json()export it, andsequence(image, ..., params=report.params)replays the call.matrixis the(B, 3, 3)map from input to output pixel coordinates composed oversteps, orNonewhengeometry_statusis"unsupported", andspatialholds oneSpatialAuditper keypoint or box input.paramsis a detached snapshot of nativeParamItemvalues. JSON is a diagnostic export, not a parameter deserializer. Reports retain neither image pixels nor autograd graphs. Tensor fields are independent snapshots, not read-only tensors.geometry_statusisunsupportedwhen any executed operation lacks a supported matrix,singularwhen any composed matrix cannot be inverted, oravailable. Inspect the per-batchinvertiblemask and spatial errors rather than interpreting availability as alignment success.inverse_matrixhas NaNs for singular/nonfinite batches. No image inverse is evaluated: coordinate invertibility does not imply pixel reconstruction, particularly after cropping, interpolation or intensity changes.- Convention:
See also
audit(): runs a pipeline and builds this report.AugmentationAuditStep: one entry ofsteps.SpatialAudit: one entry ofspatial.
- summary()[source]#
Describe matrix availability and diagnostic warnings without claiming image invertibility.
- Return type:
- class kornia.contrib.AugmentationAuditStep(name, occurrence, module, input_shape, output_shape, params, flags, matrix, unsupported_reason)[source]#
Record one executed operation of an audit: its parameters, shapes and matrix.
report.stepsof anAugmentationAuditReportlists one step per executed leaf operation, in execution order.nameis the qualified module name in the pipeline,modulethe class name, andoccurrencecounts repeated runs of onenamefrom 0.paramsandflagsare detached copies;flagsinclude the keyword overrides of that image call.input_shapeandoutput_shapeare those of the image.matrixis the(B, 3, 3)map from this operation’s input pixel coordinates to its output coordinates, includingRandomCropprepadding.Nonemeans the operation has no supported 2D matrix, not that it is an identity, andunsupported_reasonthen says why.- Convention:
See also
AugmentationAuditReport: holds the steps and the matrix composed over all of them.SpatialAudit: the label statistics, measured with the composed matrix.
- class kornia.contrib.SpatialAudit(input_index, data_key, metric, count, out_of_frame, nonfinite, out_of_frame_fraction, roundtrip_valid_count, roundtrip_mean, roundtrip_median, roundtrip_max)[source]#
Hold the per-sample out-of-frame counts and round-trip errors of one keypoint or box input.
report.spatialof anAugmentationAuditReporthas one entry per keypoint or box input, and each of its tensor fields is(B,), one value per sample.countholds the items present, andout_of_frame_fractiondivides by it, so an empty input has a NaN fraction.out_of_frameandnonfinitecount present items too. A returned box row that holds no box is not present: a row the returnedBoxesobject marks invalid, or a zero-extent row under"bbox_xywh". The container returns the rows that hold no box in its input that way. The round-trip statistics cover only finite errors of present items, in pixels; a sample with no such error has NaN statistics and a zeroroundtrip_valid_count.- Convention:
See also
AugmentationAuditReport: holds these entries with the composed matrix they invert.AugmentationAuditStep: the per-operation record, without label statistics.
Models#
Base#
- class kornia.models.base.ModelBase(*args, **kwargs)[source]#
Abstract model class with some utilities function.
- compile(*, fullgraph=False, dynamic=False, backend='inductor', mode=None, options=None, disable=False)[source]#
Compile this model with
torch.compile().- Parameters:
fullgraph (
bool, optional) – Whether Dynamo should require a single full graph. Default:Falsedynamic (
bool, optional) – Whether dynamic shape tracing is enabled. Default:Falsebackend (
str, optional) – Compilation backend name passed totorch.compile(). Default:"inductor"mode (
Optional[str], optional) – Optional backend-specific compilation mode. Default:Noneoptions (
Optional[dict[Any,Any]], optional) – Optional backend-specific option dictionary. Default:Nonedisable (
bool, optional) – IfTrue, return an uncompiled model wrapper according to PyTorch’s compile semantics. Default:False
- Return type:
- Returns:
Compiled model object with the same high-level interface as this instance.
EfficientViT#
- class kornia.models.efficient_vit.EfficientViT(backbone)[source]#
EfficientViT backbone model.
The pretrained backbones were trained on images normalized with the ImageNet mean and standard deviation, so a \([0, 1]\) image goes in as
kornia.enhance.normalize(image, torch.tensor([0.485, 0.456, 0.406]), torch.tensor([0.229, 0.224, 0.225])).- __init__(backbone)[source]#
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- static from_config(config)[source]#
Build the EfficientViT model from a configuration object.
- Parameters:
config (
EfficientViTConfig) – EfficientViT configuration object. SeeEfficientViTConfig.- Returns:
the EfficientViT model, in evaluation mode, since it always loads
config.checkpoint(see Pretrained models).- Return type:
- class kornia.models.efficient_vit.EfficientViTConfig(checkpoint=<factory>)[source]#
Configuration to construct EfficientViT model.
Model weights can be loaded from a checkpoint URL or local path. The model weights are hosted on HuggingFace’s model hub: https://huggingface.co/kornia.
- Parameters:
checkpoint (
str, optional) – URL or local path of model weights.EfficientViT.from_config()reads the architecture from the file name, which must start with the model type and a-(b0,b1,b2,b3,l0,l1,l2orl3), as inb1-r224.pt:my_efficientvit.ptraisesValueError. Default:<factory>
Backbones#
- class kornia.models.efficient_vit.backbone.EfficientViTBackbone(width_list, depth_list, in_channels=3, dim=32, expand_ratio=4, norm='bn2d', act_func='hswish')[source]#
Implement the EfficientViT backbone architecture.
EfficientViT is a high-speed vision transformer designed for efficient inference on mobile and edge devices by optimizing the attention mechanism and structural blocks.
- Parameters:
depth_list (
list[int]) – List of depths (number of blocks) for each stage.in_channels (
int, optional) – Number of input image channels. Default: 3.dim (
int, optional) – Dimension of the query, key, and value tensors in the attention mechanism. Default: 32.expand_ratio (
float, optional) – Expansion ratio for the MBConv blocks. Default: 4.norm (
str, optional) – Normalization layer type. Default: “bn2d”.act_func (
str, optional) – Activation function type. Default: “hswish”.
- static build_local_block(in_channels, out_channels, stride, expand_ratio, norm, act_func, fewer_norm=False)[source]#
Build the local convolution block used between EfficientViT stages.
- Parameters:
in_channels (
int) – Number of input feature channels.out_channels (
int) – Number of output feature channels.stride (
int) – Spatial stride for the block.expand_ratio (
float) – Expansion ratio used by MBConv-style blocks.norm (
str) – Normalization layer name.act_func (
str) – Activation function name.fewer_norm (
bool, optional) – IfTrue, omit selected normalization layers. Default:False
- Return type:
- Returns:
Depthwise-separable or inverted-bottleneck convolution block.
- kornia.models.efficient_vit.backbone.efficientvit_backbone_b0(**kwargs)[source]#
Create EfficientViT B0.
- Return type:
- kornia.models.efficient_vit.backbone.efficientvit_backbone_b1(**kwargs)[source]#
Create EfficientViT B1.
- Return type:
- kornia.models.efficient_vit.backbone.efficientvit_backbone_b2(**kwargs)[source]#
Create EfficientViT B2.
- Return type:
- kornia.models.efficient_vit.backbone.efficientvit_backbone_b3(**kwargs)[source]#
Create EfficientViT B3.
- Return type:
- class kornia.models.efficient_vit.backbone.EfficientViTLargeBackbone(width_list, depth_list, in_channels=3, qkv_dim=32, norm='bn2d', act_func='gelu')[source]#
Implement the large-scale variant of the EfficientViT backbone.
This backbone is designed for high-resolution dense prediction tasks. It utilizes multi-scale linear attention to achieve a global receptive field while maintaining linear computational complexity relative to the input resolution.
- Parameters:
width_list (
list[int]) – List of channel widths for each stage of the backbone.depth_list (
list[int]) – List of number of blocks for each stage.in_channels (
int, optional) – Number of input image channels. Default: 3.qkv_dim (
int, optional) – The internal dimension for query, key, and value projections in the attention layers. Default: 32.norm (
str, optional) – Normalization layer type to use (e.g., “bn2d”, “ln”). Default: “bn2d”.act_func (
str, optional) – Activation function type to use (e.g., “gelu”, “relu”). Default: “gelu”.
- static build_local_block(stage_id, in_channels, out_channels, stride, expand_ratio, norm, act_func, fewer_norm=False)[source]#
Build a local block for an EfficientViT large stage.
- Parameters:
stage_id (
int) – Index of the stage being constructed.in_channels (
int) – Number of input feature channels.out_channels (
int) – Number of output feature channels.stride (
int) – Spatial stride for the block.expand_ratio (
float) – Expansion ratio controlling intermediate channels.norm (
str) – Normalization layer name.act_func (
str) – Activation function name.fewer_norm (
bool, optional) – IfTrue, use the reduced-normalization variant. Default:False
- Return type:
- Returns:
Residual, fused-MBConv, or MBConv block chosen for the stage.
- kornia.models.efficient_vit.backbone.efficientvit_backbone_l0(**kwargs)[source]#
Create EfficientViT L0.
- Return type:
- kornia.models.efficient_vit.backbone.efficientvit_backbone_l1(**kwargs)[source]#
Create EfficientViT L.
- Return type:
- kornia.models.efficient_vit.backbone.efficientvit_backbone_l2(**kwargs)[source]#
Create EfficientViT L2.
- Return type:
Structures#
- class kornia.models.structures.SegmentationResults(logits, scores, mask_threshold=0.0, _original_res_logits=None)[source]#
Encapsulate the results obtained by a Segmentation model.
- Parameters:
logits (
Tensor) – Results logits with shape(K, C, H, W)for one image: \(K\) is the number of its prompts (the leading size of its point, box or mask prompts; 1 when it has none), \(C\) the number of masks predicted per prompt (3 withmultimask_output, else 1), and \(H = W = 256\) for SAM.scores (
Tensor) – The predicted IoU of each mask. Shape(K, C)mask_threshold (
float, optional) – The threshold value to generate the binary_masks from the logits Default:0.0
- property binary_masks: Tensor#
Binary mask generated from logits considering the mask_threshold.
Shape will be the same of logits
(K, C, H, W)where \(C\) is the number masks predicted per prompt.Note
If you run original_res_logits, this will generate the masks based on the original resolution logits. Otherwise, this will use the low resolution logits (self.logits).
- original_res_logits(input_size, original_size, image_size_encoder)[source]#
Remove padding and upscale the logits to the original image size.
Resize to image encoder input -> remove padding (bottom and right) -> Resize to original size
Note
This method set a internal original_res_logits which will be used if available for the binary masks.
- Parameters:
input_size (
tuple[int,int]) – The size of the image input to the model, in (H, W) format. Used to remove padding.original_size (
tuple[int,int]) – The original size of the image before resizing for input to the model, in (H, W) format.image_size_encoder (
Optional[tuple[int,int]]) – The size of the input image for image encoder, in (H, W) format. Used to resize the logits back to encoder resolution before remove the padding.
- Return type:
- Returns:
Batched logits in
(K, C, H, W)format, where (H, W) is given by original_size.
- class kornia.models.structures.Prompts(points=None, boxes=None, masks=None)[source]#
Encapsulate the prompts inputs for a Model.
- Parameters:
points (
Optional[tuple[Tensor,Tensor]], optional) – A tuple with the keypoints (coordinates x, y) and their respective labels. Shape(K, N, 2)for the keypoints, and(K, N)Default:Noneboxes (
Optional[Tensor], optional) – Batched box inputs, with shape(K, 4). Expected to be into xyxy format. Default:Nonemasks (
Optional[Tensor], optional) – Batched mask prompts to the model with shape(K, 1, H, W)Default:None
VisualPrompter#
- class kornia.contrib.visual_prompter.VisualPrompter(config=None, device=None, dtype=None)[source]#
Segment one image from point, box and mask prompts with SAM, encoding the image once.
prompter = VisualPrompter(SamConfig("mobile_sam", pretrained=True))builds the SAM model.prompter.set_image(image)encodes one RGB image(3, H, W)or(1, 3, H, W), floating point in \([0, 1]\). Eachresult = prompter.predict(keypoints, keypoints_labels)orprompter.predict(boxes=boxes)then answersKprompts given in that image’s pixels. It returns aSegmentationResultswith(K, M, 256, 256)low-resolutionlogits,(K, M)scoresand(K, M, H, W)binary_masks, withM = 3masks per prompt, or 1 formultimask_output=False.- Convention:
set_image()resizes the image so that its long side equalsimage_encoder.img_size, with the antialiased bilinear filter of SAM’s reference (ResizeLongestSide.apply_image_torch), computed in float32 (float64 for a float64 image) and cast back. It then normalizes it with SAM’s mean and standard deviation, or themeanandstdit is given, and zero-pads it at the bottom and right to the square encoder input (preprocess_image()). The resized size comes fromtransforms, anAugmentationSequentialthat must hold exactly one stage,kornia.augmentation.Resize(img_size, side="long", align_corners=False, antialias=True).The prompts follow the per-axis scales \(s_x = w / W\) and \(s_y = h / H\) from the \(H \times W\) image to the resized \(h \times w\) one, computed in float32 (float64 for a float64 model), and come out in that dtype. A keypoint marks a pixel centre and follows the half-pixel map \(x \mapsto (x + 0.5)\,s_x - 0.5\) (likewise for \(y\)), the map the resize samples on. A box marks pixel edges, kornia’s
xyxyconvention (width = x2 - x1), and both its corners follow \(x \mapsto x\,s_x\), as in the reference’sapply_boxes: at \(s = 8\) the box (10, 20, 60, 50) goes to (80, 160, 480, 400), and \((0, 0, W, H)\) to the whole resized image \((0, 0, w, h)\).Two details depart on purpose from Meta’s
SamPredictor(segment-anything@3518c86). The resized short side is truncated, where the reference rounds it (a 1380 x 2076 image becomes 680 x 1024 here and 681 x 1024 there): truncation is the rule ofkornia.augmentation.Resize, and the masks are resized back through the same recorded size. Keypoints follow the half-pixel map above, where the reference’sapply_coordsuses \(x \mapsto x\,s\) for points too: at \(s = 8\), the keypoint (40, 30) goes to (323.5, 243.5) here and to (320, 240) in the reference.The held model follows the mode rule of Pretrained models: a config that loads weights gives a model in evaluation mode, and a randomly initialized one stays in training mode, where MobileSAM’s BatchNorm normalizes with the statistics of the batch. Call
prompter.model.eval()before inference on random weights.
- Parameters:
config (
Optional[SamConfig], optional) – A model config to generate the model. Now just the SAM model is supported. If None, SAM ViT-H, whose weights are downloaded on first use. Default:Nonedevice (
Optional[device], optional) – The desired device to use the model. Default:Nonedtype (
Optional[dtype], optional) – The desired dtype to use the model. Default:None
- Raises:
NotImplementedError – If
configis neither aSamConfignorNone.
See also
Sam: the model itself, for a batch of images each with its own prompts.SegmentationResults: the masks and scorespredict()returns.
Example
>>> # prompter = VisualPrompter() # Will load the vit h for default >>> # You can load a custom SAM type for modifying the config >>> prompter = VisualPrompter(SamConfig('vit_b')) >>> image = torch.rand(3, 25, 30) >>> prompter.set_image(image) >>> # The K box prompts of the image, as a (1, K, 4) xyxy tensor; here K = 1. >>> boxes = Boxes.from_tensor( ... torch.tensor([[[0.0, 0.0, 10.0, 10.0]]], device=prompter.device, dtype=torch.float32), mode='xyxy' ... ) >>> prediction = prompter.predict(boxes=boxes) >>> prediction.logits.shape torch.Size([1, 3, 256, 256])
- compile(*, fullgraph=False, dynamic=False, backend='inductor', mode=None, options=None, disable=False)[source]#
Apply torch.compile(…)/dynamo API into the VisualPrompter API.
Note
For more information about the dynamo API check the official docs https://pytorch.org/docs/stable/generated/torch.compile.html
- Parameters:
fullgraph (
bool, optional) – Whether it is ok to break model into several subgraphs Default:Falsedynamic (
bool, optional) – Use dynamic shape tracing Default:Falsebackend (
str, optional) – backend to be used Default:"inductor"mode (
Optional[str], optional) – Can be either “default”, “reduce-overhead” or “max-autotune” Default:Noneoptions (
Optional[dict[Any,Any]], optional) – A dictionary of options to pass to the backend. Default:Nonedisable (
bool, optional) – Turn torch.compile() into a no-op for testing Default:False
- Return type:
Example
>>> # prompter = VisualPrompter() >>> # prompter.compile() >>> # Use the prompter methods ...
- predict(keypoints=None, keypoints_labels=None, boxes=None, masks=None, multimask_output=True, output_original_size=True)[source]#
Predict masks for the given image based on the input prompts.
- Parameters:
keypoints (
Union[Keypoints,Tensor,None], optional) – Point prompts to the model. Each point is in (X,Y) in pixels. Shape(K, N, 2). WhereNis the number of points andKthe number of prompts. Default:Nonekeypoints_labels (
Optional[Tensor], optional) – Labels for the point prompts. 1 indicates a foreground point and 0 indicates a background point. Shape(K, N). WhereNis the number of points, andKthe number of prompts. Required withkeypoints. Default:Noneboxes (
Union[Boxes,Tensor,None], optional) – Box prompts to the model, one per prompt: a torch.Tensor in xyxy mode, shape(K, 4)or(1, K, 4), whose corners are taken as given, or aBoxesof shape(K, 4, 2)or(1, K, 4, 2), read throughto_tensor(mode="xyxy").Kis the number of prompts. Default:Nonemasks (
Optional[Tensor], optional) – A low resolution mask input to the model, typically coming from a previous prediction iteration. Has shape(K, 1, H, W), where for SAM, H=W=256. Default:Nonemultimask_output (
bool, optional) – If True, three masks per prompt, each with its score inscores; if False, one. Default:Trueoutput_original_size (
bool, optional) – If True,binary_masksis resized to the size of the image set. Default:True
- Return type:
- Returns:
The
(K, M, 256, 256)low-resolutionlogitsand the(K, M)scores(the predicted IoU of each mask), withM3 or 1 bymultimask_output. Withoutput_original_size,binary_masksis(K, M, H, W), at the size of the image set; otherwise it is at the logits’ size.- Raises:
BaseError – If no image is set, or if
keypointscome withoutkeypoints_labels.
- preprocess_image(x, mean=None, std=None)[source]#
Normalize an image by a mean and standard deviation, and zero-pad it to the encoder’s square input.
The image is normalized with
meanandstdwhen both are given, else with SAM’s dataset values set at construction, and zero-padded at the right and bottom toself.model.image_encoder.img_size.
- preprocess_prompts(keypoints=None, keypoints_labels=None, boxes=None, masks=None)[source]#
Validate and preprocess the given prompts to be aligned with the input image.
Keypoints follow the half-pixel map \((x + 0.5)\,s - 0.5\) of a pixel centre, and both corners of each xyxy box the edge map \(x\,s\), as the reference’s
apply_boxesdoes, with the per-axis scales recorded byset_image(). They are computed, and returned, in float32 (float64 for a float64 model). A tensor box is taken as given; aBoxesis read throughto_tensor(mode="xyxy").- Return type:
- reset_image()[source]#
Clear cached image state and prompt-transform metadata.
This method invalidates previously computed image embeddings and resets all size/transform bookkeeping so a new call to
set_image()starts from a clean state.In practice, this resets: - transformed-image parameters and the prompt scales, - original/input/encoder spatial sizes, - cached image embeddings, -
is_image_setstatus flag.- Return type:
- set_image(image, mean=None, std=None)[source]#
Encode one image with the model’s image encoder and keep its embeddings for
predict().Resize the image to the size given by
transforms, with SAM’s filter (see the class docstring), and prepare it withpreprocess_image().- Parameters:
image (
Tensor) – One RGB image, shape(3, H, W)or(1, 3, H, W), in the dtype of the model, floating point with values in \([0, 1]\); it is normalized with the mean and std set at construction unlessmeanandstdare given. A batch of more than one image raises; usekornia.models.sam.Sam.forward()for batches.mean (
Optional[Tensor], optional) – mean value of dataset for normalization. Default:Nonestd (
Optional[Tensor], optional) – standard deviation of dataset for normalization. Default:None
- Return type:
Edge Detection#
- class kornia.contrib.EdgeDetector(model, pre_processor, post_processor, name=None)[source]#
Run an edge network on RGB images and resize its maps back to each image’s size.
edges = EdgeDetector(model, pre_processor, post_processor)(images)runspre_processor,modelandpost_processoron a(B, 3, H, W)tensor or a list of(3, H, W)images and returns what the post-processor returns. With aResizePostProcessor, that is a list with one(1, C, H, W)map per image, at that image’s size (C = 1for DexiNed).- Parameters:
model (
Module) – The edge detection model.pre_processor (
Module) – Pre-processing module (e.g., ResizePreProcessor).post_processor (
Module) – Post-processing module (e.g., ResizePostProcessor).name (
Optional[str], optional) – Optional name for the detector, used in the file names ofsaveandto_onnx. Default:None
See also
EdgeDetectorBuilder: builds this wrapper around the pretrained DexiNed network.canny(): edges from image gradients with hysteresis thresholds, without a network or a download.
Example
>>> detector = EdgeDetectorBuilder.build("dexined", pretrained=True, image_size=352) >>> img = torch.rand(1, 3, 320, 320) # RGB in [0, 1] >>> out = detector(img) # a list with one (1, 1, 320, 320) edge probability map per image
Face Detection#
- class kornia.contrib.FaceDetector(top_k=5000, confidence_threshold=0.3, nms_threshold=0.3, keep_top_k=750)[source]#
Detect faces and five facial landmarks in RGB images in [0, 255] with the pretrained YuNet network.
detect = FaceDetector()downloads the pretrained YuNet weights on first use.dets = detect(images)takes floating-point RGB images(B, 3, H, W)in \([0, 255]\),HandWat least 63. It returns a list ofBtensors(N, 15), one row per face in the input’s pixels, to read withFaceDetectorResult. Scale a \([0, 1]\) image by 255 first. See [FYP+21].- Convention:
The score is
sqrt(class_score * iou_score.clamp(0, 1)). The detections scoring strictly aboveconfidence_thresholdare kept, thetop_kbest of them go through non-maximum suppression at the IoUnms_threshold, and thekeep_top_kbest survivors are returned, highest score first.Boxes and landmarks are not clipped: they can extend past the image border.
- Parameters:
top_k (
int, optional) – the maximum number of detections to return before the nms. Default:5000confidence_threshold (
float, optional) – the threshold used to discard detections. Default:0.3nms_threshold (
float, optional) – the threshold used by the nms for iou. Default:0.3keep_top_k (
int, optional) – the maximum number of detections to return after the nms. Default:750
See also
FaceDetectorResult: named access to the box, landmarks and score of the rows.FaceKeypoint: the names and order of the five landmarks.
Example
>>> img = torch.rand(1, 3, 320, 320) * 255 # RGB in [0, 255] >>> detect = FaceDetector() >>> res = detect(img)
- class kornia.contrib.FaceKeypoint(value)[source]#
Name the five facial landmarks of a FaceDetector detection, left and right as the viewer sees them.
FaceDetectorResult(dets).get_keypoint(FaceKeypoint.NOSE)returns the(x, y)pixel of that landmark for each detection.EYE_LEFTandMOUTH_LEFTare the ones on the left of the image, the subject’s right side for a face that looks at the camera.See also
FaceDetectorResult: reads these landmarks, the box and the score of a detection.FaceDetector: returns the detections.
- EYE_LEFT = 0#
- EYE_RIGHT = 1#
- MOUTH_LEFT = 3#
- MOUTH_RIGHT = 4#
- NOSE = 2#
- class kornia.contrib.FaceDetectorResult(data)[source]#
Read the box, the five landmarks and the score of FaceDetector detections by name.
result = FaceDetectorResult(dets)wraps the(N, 15)detections of one image fromFaceDetector, or one(15,)row. Its properties (xmin,width,top_left,score, …) andresult.get_keypoint(FaceKeypoint.NOSE)return(N,)values and(N, 2)points, or 0-d values and(2,)points for a single row. The box and the landmarks are in the pixels of the image the detector saw.- Parameters:
data (
Tensor) – the detections returned byFaceDetector, one row of 15 values per face with shape(15,)or(N, 15): the boxxmin, ymin, xmax, ymax, five(x, y)landmarks (seeFaceKeypoint) and the score.- Raises:
ValueError – If the last dimension of
datais shorter than 15.
See also
FaceDetector: returns the detections this reads.FaceKeypoint: names the landmarks forget_keypoint().
- property bottom_right: Tensor#
The [x y] position of the bottom-right coordinate of the bounding box.
- get_keypoint(keypoint)[source]#
Get the [x y] position of a given facial keypoint.
- Parameters:
keypoint (
FaceKeypoint) – the keypoint type to return the position.- Return type:
Object Detection#
- class kornia.contrib.object_detection.BoundingBoxDataFormat(value)[source]#
Name the layout of the four values of a BoundingBox: xywh, xyxy or center xywh.
BoundingBoxDataFormat.XYWHtags aBoundingBoxwhose values are the top-leftx, y, the width and the height;XYXYthe top-left and bottom-right corners;CXCYWHthe center, the width and the height.CENTER_XYWHis another name ofCXCYWH, the same member.See also
BoundingBox: the box whose values this names.Boxes: a batch of boxes as tensors, converted between thexyxy,xywhand corner layouts.
- XYWH = 0#
- XYXY = 1#
- CXCYWH = 2#
- CENTER_XYWH = 2#
- class kornia.contrib.object_detection.BoundingBox(data, data_format)[source]#
Hold one box as four Python floats tagged with their BoundingBoxDataFormat.
box = BoundingBox(data=(x, y, w, h), data_format=BoundingBoxDataFormat.XYWH)is a frozen dataclass:dataholds the four values anddata_formatsays how to read them; nothing converts or checks them.results_from_detections()builds one per detection.- Parameters:
See also
BoundingBoxDataFormat: the layouts thatdata_formatnames.ObjectDetectorResult: one detection, holding this box with its class and confidence.Boxes: a batch of boxes as tensors, with layout conversions.
-
data_format:
BoundingBoxDataFormat#
- class kornia.contrib.object_detection.ObjectDetectorResult(class_id, confidence, bbox)[source]#
Hold one detection as a class id, a confidence and a BoundingBox.
result = ObjectDetectorResult(class_id, confidence, bbox)is a frozen dataclass of Python values.results_from_detections()builds one per row of the(D, 6)detections of an image.- Parameters:
class_id (
int) – class id of the detected object.confidence (
float) – confidence score of the detected object.bbox (
BoundingBox) – bounding box of the detected object, whosedata_formatsays the layout of its values.
See also
results_from_detections(): builds these from a detection tensor.BoundingBox: the box it holds.
-
bbox:
BoundingBox#
- class kornia.contrib.object_detection.ObjectDetector(model, pre_processor, post_processor)[source]#
Run a detection network on RGB images and return per-image (class, score, xywh box) rows.
detector = ObjectDetector(model, pre_processor, post_processor)wraps a detection network.dets = detector(images)takes a(B, 3, H, W)tensor or a list of(3, H, W)images, runspre_processor,modelandpost_processorin turn, and returns what the post-processor returns.See also
RTDETRDetectorBuilder: builds this wrapper around a pretrained RT-DETR network.BoxFiltering: keeps the detections above a score and in given classes.results_from_detections(): converts the detections of one image to Python objects.
- compile(*, fullgraph=False, dynamic=False, backend='inductor', mode=None, options=None, disable=False)[source]#
Compile the internal object detection model with
torch.compile().- Return type:
- forward(images)[source]#
Detect objects in a given list of images.
- Parameters:
images (
Union[Tensor,list[Tensor]]) – If list of RGB images. Each image is a torch.Tensor with shape(3, H, W). If torch.Tensor, a torch.Tensor with shape(B, 3, H, W).- Return type:
- Returns:
What the post-processor returns. For a detector from
RTDETRDetectorBuilder.build(), a list with one(D, 6)tensor per image, where \(D\) is the number of detections in that image, each row the class id, the score and thex, y, w, hbox in that image’s pixels; withconfidence_filtering=Falseor a threshold of 0, one(B, Q, 6)tensor of theQbest detections of each image.
- static from_config(config)[source]#
Raise
NotImplementedError: build withRTDETRDetectorBuilder.build()or the constructor.- Parameters:
config (
Any) – Configuration object (not used, kept for interface compatibility).- Raises:
NotImplementedError – Always.
- Return type:
- name: str = 'detection'#
- save(images, detections=None, directory=None)[source]#
Save the images with their boxes drawn by
visualize()as PNG files.
- to_onnx(onnx_name=None, image_size=640, include_pre_and_post_processor=True, save=True, additional_metadata=None, **kwargs)[source]#
Export an RT-DETR object detection model to ONNX format.
Exports this detector, as built by
RTDETRDetectorBuilder.build()or the constructor.- Parameters:
onnx_name (
Optional[str], optional) – The name of the output ONNX file. If not provided,"kornia_<name>_<image_size>.onnx", with the detector’sname, for example"kornia_detection_640.onnx"("kornia_detection_None.onnx"forimage_size=None). Default:Noneimage_size (
Optional[int], optional) – The height and width of the exported graph’s input. If None, both are dynamic. With the pre- and post-processor, the pre-processor resizes the input to the size it was built with, whateverimage_sizeis; without them, the model runs at the size of its input. For RTDETR, recommended scales include [480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800]. Default:640include_pre_and_post_processor (
bool, optional) – Whether to include the pre-processor and post-processor in the exported model. Default:Truesave (
bool, optional) – If True, write the model toonnx_name; it is returned either way. Default:Trueadditional_metadata (
Optional[list[tuple[str,str]]], optional) – Additional metadata to add to the ONNX model. Default:Nonekwargs (
Any) – Additional keyword arguments oftorch.onnx.export().
- Return type:
ModelProto
Note
With a post-processor that returns a list or tuple of per-image detections, as a
kornia.models.rt_detr.DETRPostProcessorthat filters by confidence does, the model is exported for a batch of one image: no ONNX output holds a list as long as the batch. Which kind of output the detector returns is read from one forward pass for one image at the export size, in eval mode and without gradients, and a tuple as long as the batch from a second one at another batch size, which tells per-image results from a fixed set of batched outputs such as(boxes, scores). A per-image result requires a fixed batch; a tensor result is checked again at the actual tracing batch before accepting a dynamic graph. Build an RT-DETR detector withconfidence_filtering=Falseto export a batch of any size. Adynamic_axesordynamic_shapesargument that makes the batch of such an export dynamic raises aValueErrorafter the export, before anything is saved.Without the pre- and post-processor, a model that declares
ONNX_OUTPUT_NAMES, asRTDETRdoes (pred_logitsandpred_boxes), has its outputs exported under those names, each with a dynamic batch; any other model has one output,output.
- visualize(images, detections=None, output_type='torch')[source]#
Draw the boxes of the detections on copies of the images.
- Parameters:
images (
Union[Tensor,list[Tensor]]) – input images, a(B, 3, H, W)tensor or a list of(3, H, W)images.detections (
Optional[Tensor], optional) – the detections of each image, rows ending with thex, y, w, hbox; computed withforward()when None. Default:Noneoutput_type (
str, optional) –"torch"or"pil". Default:"torch"
- Return type:
- Returns:
A list with one
(3, H, W)image per input image, or a list of PIL images foroutput_type="pil".
- class kornia.contrib.object_detection.ResizePreProcessor(height, width, interpolation_mode='bilinear')[source]#
Resize a list of image tensors to the given size.
Additionally, also returns the original image sizes for further post-processing.
- Parameters:
Example
>>> import torch >>> from kornia.models.processors import ResizePreProcessor >>> processor = ResizePreProcessor(height=224, width=224) >>> imgs = torch.randn(2, 3, 480, 640) >>> resized, sizes = processor(imgs) >>> print(resized.shape, sizes.shape) torch.Size([2, 3, 224, 224]) torch.Size([2, 2])
- forward(imgs)[source]#
Resize input images to the target size.
- Parameters:
imgs (
Union[Tensor,List[Tensor]]) – Input images, either a tensor of shape(B, C, H, W)or a list of tensors of shape(C, H, W).- Returns:
resized_imgs: Resized images as a tensor of shape \((B, C, H_{\text{new}}, W_{\text{new}})\).
original_sizes: Original image sizes of shape
(B, 2)containing (height, width), asint64on the images’ device.
- Return type:
Tuple containing
- class kornia.contrib.object_detection.BoxFiltering(confidence_threshold=None, classes_to_keep=None, filter_as_zero=False)[source]#
Keep the detections above a confidence threshold and in given classes, per image.
kept = BoxFiltering(confidence_threshold=0.3, classes_to_keep=[0, 2])(dets)keeps the rows(class_id, score, x, y, w, h)of(B, D, 6)detections that score strictly above the threshold and are inclasses_to_keep. It returns a list ofBtensors(D_b, 6), or, withfilter_as_zero=True, the(B, D, 6)input with the other rows zeroed.- Parameters:
confidence_threshold (
Union[Tensor,float,None], optional) – a float or 0-d tensor; the rows scoring strictly above it are kept. If None, 0. Default:Noneclasses_to_keep (
Union[Tensor,List[int],None], optional) – a list or 1-d tensor of the class ids to keep. If None, keep all classes. Default:Nonefilter_as_zero (
bool, optional) – whether to set the other rows to zero in one(B, D, 6)tensor instead of dropping them. Default:False
See also
DETRPostProcessor: RT-DETR’s post-processor, which filters its detections by score with this class.results_from_detections(): converts the kept rows of one image to Python objects.
- forward(boxes, confidence_threshold=None, classes_to_keep=None)[source]#
Filter boxes according to the desired threshold.
To be ONNX-friendly, the inputs for direct forwarding need to be all tensors.
- Parameters:
boxes (
Tensor) –(B, D, 6), where B is the batch size, D is the number of detections in each image, 6 represent (class_id, confidence_score, x, y, w, h).confidence_threshold (
Optional[Tensor], optional) – a 0-d tensor that replaces the constructor’s threshold for this call. If None, the constructor’s. Default:Noneclasses_to_keep (
Optional[Tensor], optional) – a 1-d torch.Tensor of classes to keep, replacing the constructor’s for this call. If None, the constructor’s. Default:None
- Return type:
- Returns:
If
filter_as_zerois True, the(B, D, 6)input with the filtered-out rows set to zero. Iffilter_as_zerois False, a list ofBtensors(D_b, 6), the rows kept in each image.
- to_onnx(onnx_name=None, input_shape=None, output_shape=None, pseudo_shape=None, model=None, save=True, additional_metadata=None, **kwargs)[source]#
Export the filter with a fixed batch for per-image list outputs.
- Parameters:
onnx_name (
Optional[str], optional) – The output file name. Defaults toKornia-BoxFiltering.onnx. Default:Noneinput_shape (
Optional[list[int]], optional) – The[B, D, 6]input shape, with-1for a dynamic dimension. Defaults to[1, -1, 6]withoutfilter_as_zeroand[-1, -1, 6]with it. Default:Noneoutput_shape (
Optional[list[int]], optional) – The output shape used by the legacy TorchScript exporter. Defaults to[-1, 6]withoutfilter_as_zeroand[-1, -1, 6]with it. The dynamo exporter infers output shapes. Default:Nonepseudo_shape (
Optional[list[int]], optional) – The dummy input shape used for tracing. Withoutfilter_as_zeroandinput_shape, its batch is the exported batch. Explicit input and pseudo shapes must agree on fixed dimensions. Default:Nonemodel (
Optional[Module], optional) – The model to export. Defaults to this filter. Default:Nonesave (
bool, optional) – Whether to save the exported model toonnx_name. Default:Trueadditional_metadata (
Optional[list[tuple[str,str]]], optional) – Additional metadata to add to the ONNX model. Default:None**kwargs (
Any) – Additional arguments totorch.onnx.export().
- Return type:
ModelProto- Returns:
The exported ONNX model.
- Raises:
ValueError – If
input_shapemarks the batch-1withoutfilter_as_zero, or adynamic_axesordynamic_shapesargument makes the exported batch dynamic without it.
Note
The exported graph takes the boxes as its only input and filters at the threshold given to the constructor, or at
0.0when there is none, as eager does.Note
The exporters flatten the Python list into a fixed number of graph outputs. Without
filter_as_zero, the batch is therefore fixed: at the batch ofinput_shape, else ofpseudo_shape, else at 1. ONNX Runtime rejects other batch sizes. Each image’s number of retained detections remains dynamic. Usefilter_as_zero=Truefor one(B, D, 6)output with a dynamic batch.
- kornia.contrib.object_detection.results_from_detections(detections, format)[source]#
Convert the
(D, 6)detections of one image to a list of ObjectDetectorResult.results = results_from_detections(dets, "xywh")takesDrows(class_id, score, b0, b1, b2, b3)and returnsDObjectDetectorResultitems.formatonly tags eachBoundingBox: the four box values are copied, not converted, so pass the layout the detections are in,"xywh"for those ofObjectDetector.- Parameters:
detections (
Tensor) – torch.Tensor with shape(D, 6), where \(D\) is the number of detections in the given image: the class id, the score and the four box values.format (
str|BoundingBoxDataFormat) – the layout of the box values, aBoundingBoxDataFormator its name in any case.
- Return type:
- Returns:
list of
ObjectDetectorResult, one per row, in the order of the rows.- Raises:
ShapeError – If
detectionsis not(D, 6).ValueError – If
formatnames noBoundingBoxDataFormat.
See also
BoxFiltering: keeps the rows above a score and in given classes, before the conversion.ObjectDetector: returns one detection tensor per image in this layout.
Real-Time Detection Transformer (RT-DETR)#
- class kornia.models.rt_detr.RTDETRModelType(value)[source]#
Enum class that maps RT-DETR model type.
- resnet18d = 0#
- resnet34d = 1#
- resnet50d = 2#
- resnet101d = 3#
- hgnetv2_l = 4#
- hgnetv2_x = 5#
- resnet50d_m = 6#
- class kornia.models.rt_detr.RTDETRConfig(model_type, num_classes, input_size=640, checkpoint=None, neck_hidden_dim=None, neck_dim_feedforward=None, neck_expansion=None, head_hidden_dim=256, head_num_queries=300, head_num_decoder_layers=None, confidence_threshold=0.3, eval_idx=None)[source]#
Configuration to construct RT-DETR model.
- Parameters:
model_type (
RTDETRModelType|str|int) –model variant. Available models are
ResNetD-18:
0,'resnet18d'orRTDETRModelType.resnet18dResNetD-34:
1,'resnet34d'orRTDETRModelType.resnet34dResNetD-50:
2,'resnet50d'orRTDETRModelType.resnet50dResNetD-101:
3,'resnet101d'orRTDETRModelType.resnet101dHGNetV2-L:
4,'hgnetv2_l'orRTDETRModelType.hgnetv2_lHGNetV2-X:
5,'hgnetv2_x'orRTDETRModelType.hgnetv2_xResNetD-50-M:
6,'resnet50d_m'orRTDETRModelType.resnet50d_m
num_classes (
int) – number of classes.input_size (
int, optional) – size of the square image thatbuild()resizes the input to. Default:640checkpoint (
Optional[str], optional) – URL or local path of a state dict with kornia’s parameter names, loaded byRTDETR.from_config(). The published RT-DETR checkpoints keep the reference implementation’s names and load only throughRTDETR.from_pretrained(). Default:Noneneck_hidden_dim (
Optional[int], optional) – hidden dim for neck. Default:Noneneck_dim_feedforward (
Optional[int], optional) – feed-forward network dim for neck. Default:Noneneck_expansion (
Optional[float], optional) – expansion ratio for neck. Default:Nonehead_hidden_dim (
int, optional) – hidden dim for head. Default:256head_num_queries (
int, optional) – number of queries for Deformable DETR transformer decoder. Default:300head_num_decoder_layers (
Optional[int], optional) – number of decoder layers for Deformable DETR transformer decoder. Default:Noneconfidence_threshold (
float, optional) – score threshold of the post-processor thatbuild()creates from this config when it is given noconfidence_threshold. Default:0.3eval_idx (
Optional[int], optional) – index of the decoder layer whose predictions the model returns; a negative value counts back from the last layer (-1), and the layers after the selected one do not run.Noneselects the variant’s layer: index 2, the third of six, forresnet50d_m, as in the reference configs of that checkpoint (or the last layer of a decoder with fewer than three), and the last layer for the other variants. Default:None
- static from_name(model_name, num_classes=80)[source]#
Load model without pretrained weights.
- Parameters:
- Return type:
-
model_type:
RTDETRModelType|str|int#
- class kornia.models.rt_detr.RTDETR(backbone, encoder, decoder)[source]#
RT-DETR Object Detection model, as described in https://arxiv.org/abs/2304.08069.
- __init__(backbone, encoder, decoder)[source]#
Construct RT-DETR Object Detection model.
- Parameters:
backbone (
ResNetD|PPHGNetV2) – backbone network for feature extraction.encoder (
HybridEncoder) – neck network for feature fusion.decoder (
RTDETRHead) – head network to decode features into detection results.
- static from_config(config)[source]#
Construct RT-DETR Object Detection model from a config object.
Returns the model in evaluation mode when
config.checkpointloads weights and in training mode otherwise (see Pretrained models).- Parameters:
config (
RTDETRConfig) – configuration object for RT-DETR.- Return type:
Note
For
config.neck_hidden_dim,config.neck_dim_feedforward,config.neck_expansion, andconfig.head_num_decoder_layers, if they areNone, their values will be replaced with the default values depending on theconfig.model_type. See the source code for the default values.
- class kornia.models.rt_detr.DETRPostProcessor(confidence_threshold=None, num_classes=80, num_top_queries=300, confidence_filtering=True, filter_as_zero=False)[source]#
Convert raw DETR model outputs into final bounding box detections.
This module applies the sigmoid function to the class logits, as RT-DETR was trained with a focal loss, keeps the
num_top_querieshighest (query, class) scores of each image, and transforms the normalized(cx, cy, w, h)boxes into(x, y, w, h)in the pixel coordinate system of each input image, scaled by that image’s own size.- Parameters:
num_classes (
int, optional) – The number of object classes. Default:80confidence_threshold (
Optional[float], optional) – The threshold to filter out low-confidence detections. Default:Nonenum_top_queries (
int, optional) – The number of top queries to consider for each image. Default:300confidence_filtering (
bool, optional) – Whether to apply confidence-based filtering. Default:Truefilter_as_zero (
bool, optional) – If True, boxes below the confidence threshold are set to zero instead of being removed. Default:False
- forward(logits, boxes, original_sizes)[source]#
Post-process outputs from DETR.
- Parameters:
logits (
Tensor) – tensor with shape(N, Q, K), where \(N\) is the batch size, \(Q\) is the number of queries, \(K\) is the number of classes.boxes (
Tensor) – tensor with shape(N, Q, 4), where \(N\) is the batch size, \(Q\) is the number of queries.original_sizes (
Tensor) – tensor with shape(N, 2), where \(N\) is the batch size and each element represents the image size of (img_height, img_width).
- Return type:
- Returns:
Processed detections, each a row (class_id, confidence_score, x, y, w, h). A tensor of shape
(N, T, 6), \(T\) =num_top_queries, whenconfidence_filteringisFalseorconfidence_thresholdis 0; withfilter_as_zero, the same tensor with the detections at or below the threshold set to zero. Otherwise a list of \(N\) tensors of shape(D, 6), where \(D\) is the number of detections above the threshold in that image.
Image Segmentation#
- kornia.contrib.connected_components(image, num_iterations=100)[source]#
Label 8-connected foreground components by a fixed number of max-pooling steps.
labels = connected_components(image, num_iterations)takes a(*, 1, H, W)mask whose pixels equal to 1 are foreground and returnsint64labels of the same shape, 0 on the background. A component comes out whole only when every pixel is withinnum_iterations8-connected steps, inside the component, of its last pixel in raster order; otherwise it is split. For the exact partition at any size, useconnected_components_union_find().
The implementation adapts https://gist.github.com/efirdc/5d8bd66859e574c683a504a4690ae8bc.
Warning
This is an experimental API subject to changes and optimization improvements.
Note
See a working example here.
- Convention:
Components are 8-connected: pixels that touch at a corner are connected. Choosing a labeling method maps this onto SciPy, OpenCV and scikit-image.
Foreground is a value exactly equal to 1: 0.5 and 2 are background. Other values and dtypes are accepted.
The label of a component is 1 plus the largest raster index of its pixels in the batch flattened to
(N, H, W); background is 0. Labels are therefore not contiguous, and an image gets other labels at another batch position or transposed.The default 100 already splits a 1 x 102 line, and a filled 120 x 150 rectangle comes out with 1000 labels.
The labels carry no gradient. The function has no host synchronization and compiles with
torch.compile(fullgraph=True).
- Parameters:
- Return type:
- Returns:
int64 labels with the shape of the input.
- Raises:
TypeError – if
imageis not a tensor ornum_iterationsis not a positive integer.ValueError – if
imageis not(*, 1, H, W), or, on MPS, has more than \(2^{24}\) pixels per image.
See also
connected_components_union_find(): the exact partition with no iteration budget, at the cost of host synchronizations and other label values.
Example
>>> img = torch.rand(2, 1, 4, 5) >>> img_labels = connected_components(img, num_iterations=100)
- kornia.contrib.connected_components_union_find(image)[source]#
Label 8-connected foreground components exactly, by block union-find.
labels = connected_components_union_find(image)takes a(*, 1, H, W)mask whose pixels equal to 1 are foreground and returnsint64labels of the same shape and device, 0 on the background. It iterates until the partition converges, so components of any size and shape come out whole.The pure PyTorch implementation contracts each 2x2 block, following Allegretti, Bolelli and Grana, Optimized Block-Based Algorithms to Label Connected Components on GPUs, TPDS 2020, https://doi.org/10.1109/TPDS.2019.2934683. Root hooking with
scatter_reduce_and pointer jumping replace the paper’s custom CUDA union kernels.- Convention:
Choosing a labeling method maps its 8-connectivity onto SciPy, OpenCV and scikit-image, and compares it with
connected_components().
- Parameters:
image (
Tensor) – Binary image of shape(*, 1, H, W). Boolean, integer and floating-point tensors are accepted. Only values equal to 1 are foreground, as inconnected_components().- Return type:
- Returns:
Foreground labels are the minimum 1-based block index in each component, in raster order over flattened batches and the \(\lceil H/2\rceil \times \lceil W/2\rceil\) block grid. Labels are deterministic and distinct across images, but not contiguous and not equal to the labels of the pooling implementation.
Note
This discrete operation is not differentiable. Working memory is linear in the number of pixels. Convergence checks synchronize the device with the host; CUDA graph capture and
torch.compile(fullgraph=True)are not supported. All mask, edge and label computation stays on the input device.- Raises:
TypeError – if
imageis not a tensor.ValueError – if
imageis not(*, 1, H, W).
See also
connected_components(): a fixed number of pooling steps, which compiles withfullgraph=Trueand splits components longer than its budget.
Example
>>> mask = torch.tensor([[[1, 0, 0], [0, 0, 1]]], dtype=torch.bool) >>> connected_components_union_find(mask) tensor([[[1, 0, 0], [0, 0, 2]]])
Choosing a labeling method#
Both functions label 8-connected components: two foreground pixels (pixels equal
to 1) that touch at an edge or a corner belong to one component. SciPy, OpenCV
and scikit-image take any non-zero pixel as foreground, so the same partition is
scipy.ndimage.label(mask == 1, structure=np.ones((3, 3))) (SciPy’s default
structure is 4-connected), cv2.connectedComponents((mask == 1).astype(np.uint8),
connectivity=8) (OpenCV’s default connectivity) and
skimage.measure.label(mask == 1, connectivity=2) (scikit-image’s default for
2-D images). Label values differ between these libraries and between the two
functions: compare foreground partitions, not label values.
connected_components_union_find computes the exact 8-connected partition
with no iteration budget, so long structures such as vessels, roads and text
strokes come out whole. Its convergence checks synchronize the device with the
host, so it does not compile with torch.compile(fullgraph=True) and cannot
be captured in a CUDA graph.
connected_components runs a fixed num_iterations of 3x3 max-pooling
steps, with no host synchronization, and compiles with fullgraph=True. A
component comes out whole only if every pixel is within num_iterations
8-connected steps, inside the component, of its last pixel in raster order: the
default 100 already splits a 1 x 102 line. On
CUDA, 10 steps run several times faster than union-find; on the CPU, union-find
is faster than 10 steps.
Both return int64 labels, 0 on the background, and neither is
differentiable.
Segment Anything (SAM)#
- class kornia.models.sam.SamModelType(value)[source]#
Map the SAM model types.
- vit_h = 0#
- vit_l = 1#
- vit_b = 2#
- mobile_sam = 3#
- class kornia.models.sam.SamConfig(model_type=None, checkpoint=None, pretrained=False, encoder_embed_dim=None, encoder_depth=None, encoder_num_heads=None, encoder_global_attn_indexes=None)[source]#
Encapsulate the Config to build a SAM model.
- Parameters:
model_type (
Union[str,int,SamModelType,None], optional) –the available models are: Default:
None0, ‘vit_h’ or
kornia.models.sam.SamModelType.vit_h1, ‘vit_l’ or
kornia.models.sam.SamModelType.vit_l2, ‘vit_b’ or
kornia.models.sam.SamModelType.vit_b3, ‘mobile_sam’, or
kornia.models.sam.SamModelType.mobile_sam
With
None, the image encoder is a ViT built from the fourencoder_*fields below, which are ignored whenmodel_typeis set.checkpoint (
Optional[str], optional) – URL or a path for a file with the weights of the model Default:Nonepretrained (
bool, optional) – load the released weights ofmodel_type, which must then be set. Acheckpointtakes precedence, with a warning. WithFalse(the default) and nocheckpoint, the weights are randomly initialised. Default:Falseencoder_embed_dim (
Optional[int], optional) – Patch embedding dimension. Default:Noneencoder_depth (
Optional[int], optional) – Depth of ViT. Default:Noneencoder_num_heads (
Optional[int], optional) – Number of attention heads in each ViT block. Default:Noneencoder_global_attn_indexes (
Union[int,tuple[int,...],list[int],None], optional) – Encoder indexes for blocks using global attention: a tuple or a list of indexes, or one index as anint. Default:None
-
model_type:
Union[str,int,SamModelType,None] = None#
- class kornia.models.sam.Sam(image_encoder, prompt_encoder, mask_decoder)[source]#
Implement the Segment Anything Model (SAM) wrapper.
This class coordinates the image encoder, prompt encoder, and mask decoder.
- __init__(image_encoder, prompt_encoder, mask_decoder)[source]#
SAM predicts object masks from an image and input prompts.
- Parameters:
image_encoder (
ImageEncoderViT|TinyViT) – The backbone used to encode the image into image embeddings that allow for efficient mask prediction.prompt_encoder (
PromptEncoder) – Encodes various types of input prompts.mask_decoder (
MaskDecoder) – Predicts masks from the image embeddings and encoded prompts.
- forward(images, batched_prompts, multimask_output)[source]#
Predicts masks end-to-end from provided images and prompts.
This method expects that the images have already been pre-processed, at least been normalized, resized and padded to be compatible with the self.image_encoder.
Note
For each image
(3, H, W), it is possible to input a batch (\(K\)) of \(N\) prompts, the results are batched by the number of prompts batch. So given a prompt with \(K=5\), and \(N=10\), the results will look like \(5xCxHxW\) where \(C\) is determined by multimask_output. And within each of these masks \((5xC)\), it should be possible to find \(N\) instances if the model succeed.- Parameters:
images (
Tensor) – The image as a torch tensor in(B, 3, H, W)format, already transformed for input to the model.batched_prompts (
list[dict[str,Any]]) –- A list over the batch of images (list length should be \(B\)), each a dictionary with
the following keys. If it does not have the respective prompt, it should not be included in this dictionary. The options are:
”points”: tuple of (torch.Tensor, torch.Tensor) within the coordinate keypoints and their respective labels. The tuple should look like (keypoints, labels), where the keypoints (a tensor) are a batched point prompts for this image, with shape
(K, N, 2). Already transformed to the input frame of the model. The labels (a tensor) are a batched labels for point prompts, with shape(K, N). Where 1 indicates a foreground point and 0 indicates a background point.”boxes”: (torch.Tensor) Batched box inputs, with shape
(K, 4). Already transformed to the input frame of the model.”mask_inputs”: (torch.Tensor) Batched mask inputs to the model, in the form
(K, 1, H, W).
multimask_output (
bool) – Whether the model should predict multiple disambiguating masks, or return a single mask.
- Returns:
logits: Low resolution logits with shape
(K, C, H, W). Can be passed as mask input to subsequent iterations of prediction. Where \(K\) is the number of input prompts, \(C\) is determined by multimask_output, and \(H=W=256\) are the model output size.scores: The predicted IoU of each mask,
(K, C).
- Return type:
A list over input images, where each element is as SegmentationResults the following
- static from_config(config)[source]#
Build/load the SAM model based on it’s config.
- Parameters:
config (
SamConfig) – The SamConfig data structure. If the model_type is available, build from it, otherwise will use the parameters set.- Return type:
- Returns:
The respective SAM model, in evaluation mode when it loads weights (
config.pretrainedorconfig.checkpoint) and in training mode otherwise (see Pretrained models).
Example
>>> from kornia.models.sam import SamConfig >>> sam_model = Sam.from_config(SamConfig('vit_b'))
Image Patches#
- kornia.contrib.compute_padding(original_size, window_size, stride=None)[source]#
Compute the
(top, bottom, left, right)padding that makes sliding windows fit.padding = compute_padding(original_size, window_size, stride)returns four ints that, passed aspaddingtoextract_tensor_patches()and asunpaddingtocombine_tensor_patches(), make the last window ofwindow_sizeatstrideend on the padded border, so no row or column is dropped. Withstrideat mostwindow_sizethe windows then cover every pixel. Each padding is split evenly, with the odd pixel at the bottom or right, and an image smaller than one window is padded to one window.- Parameters:
original_size (
Union[int,Tuple[int,int]]) – the image size(H, W), or one int for both.window_size (
Union[int,Tuple[int,int]]) – the size of the sliding window used while extracting patches.stride (
Union[int,Tuple[int,int],None], optional) – the stride of the sliding window. Default:window_size.
- Return type:
- Returns:
The required padding as a tuple of four ints
(top, bottom, left, right).- Raises:
ValueCheckError – if a
window_sizeorstridecomponent is below 1.
See also
extract_tensor_patches(): takes this aspadding.combine_tensor_patches(): takes this asunpadding.
Example
>>> image = torch.arange(12).view(1, 1, 4, 3) >>> padding = compute_padding((4,3), (3,3)) >>> out = extract_tensor_patches(image, window_size=(3, 3), stride=(3, 3), padding=padding) >>> combine_tensor_patches(out, original_size=(4, 3), window_size=(3, 3), stride=(3, 3), unpadding=padding) tensor([[[[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]]]])
- kornia.contrib.extract_tensor_patches(input, window_size, stride=1, padding=0, allow_auto_padding=False)[source]#
Cut an image into sliding-window patches stacked along a new patch dimension.
patches = extract_tensor_patches(image, window_size, stride)takes a(B, C, H, W)image and returns its(B, N, C, h, w)patches, where(h, w)iswindow_sizeandNis the number of window positions.- Convention:
Patches are stacked row-major over the grid of window positions, left to right and then top to bottom, the order of
torch.nn.functional.unfold().window_size,strideand a 2-tuplepaddingare(height, width), or one int for both. A positivepaddingadds zeros and a negative one crops. A 4-tuple is(top, bottom, left, right), not the(left, right, top, bottom)oftorch.nn.functional.pad(); a 2-tuple(ph, pw)addsphrows above and below andpwcolumns left and right.A window that does not fit warns and drops the last rows or columns; an image smaller than the window warns and then raises.
allow_auto_padding=Truepads instead, ascompute_padding()computes.A non-zero
paddingswitches off both the fit warning andallow_auto_padding, so a padding too small for the window drops the last rows or columns silently. An all-zeropaddingcounts as none.The
ValueCheckError(aValueError) for awindow_sizeorstridecomponent below 1 is raised up front, also underpython -Oanddisable_checks(), here, incombine_tensor_patches()andcompute_padding(), and at construction ofExtractTensorPatchesandCombineTensorPatches.An empty batch gives an empty output with the same
N,C,handwas a non-empty one.
- Parameters:
input (
Tensor) – the image to extract the patches from,(B, C, H, W)withCat least 1.window_size (
Union[int,Tuple[int,int]]) – the size(h, w)of the sliding window and of each patch, or one int for both.stride (
Union[int,Tuple[int,int]], optional) – stride of the sliding window, an int or(sh, sw). Default:1padding (
Union[int,Tuple[int,int],Tuple[int,int,int,int]], optional) – zero padding, or cropping where negative: an int,(ph, pw)or(top, bottom, left, right). Default:0allow_auto_padding (
bool, optional) – whether to pad the image ascompute_padding()computes when the windows do not fit. Default:False
- Return type:
- Returns:
The extracted patches,
(B, N, C, h, w).- Raises:
TypeError – if
inputis not a tensor.ValueError – if
inputis not 4-D or has no channel.ValueCheckError – if a
window_sizeorstridecomponent is below 1.AssertionError – if
paddingis a tuple of other than two or four ints.RuntimeError – if the image, after any padding, is smaller than the window.
See also
ExtractTensorPatches: the module form.combine_tensor_patches(): puts the patches back into an image.compute_padding(): thepaddingthat makes the windows fit.
Examples
>>> input = torch.arange(9.).view(1, 1, 3, 3) >>> patches = extract_tensor_patches(input, (2, 3)) >>> input tensor([[[[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]]]]) >>> patches[:, -1] tensor([[[[3., 4., 5.], [6., 7., 8.]]]])
- kornia.contrib.combine_tensor_patches(patches, original_size, window_size, stride, allow_auto_unpadding=False, unpadding=0, eps=None)[source]#
Reassemble sliding-window patches into an image, averaging where they overlap.
image = combine_tensor_patches(patches, original_size, window_size, stride)takes(B, N, C, h, w)patches and returns the(B, C, H, W)image of sizeoriginal_size. Pass thestrideused for the extraction and itspaddingasunpadding. Withstrideat mostwindow_size, a round trip returns the input when the extraction padding is non-negative and makes the windows fit, or when both auto flags are set andpaddingandunpaddingare zero. It is exact for integer andboolpatches (below \(2^{24}\) on MPS before torch 2.9), and exact up to rounding where floating patches overlap.- Convention:
Overlapping patches are averaged: each pixel is divided by the number of patches that cover it, where
torch.nn.functional.fold()sums them. A pixel that no patch covers (patches that do not fit) is 0.The output keeps the dtype of the patches. Integer patches are averaged exactly in
int64, with the mean truncated toward zero (on MPS before torch 2.9 they go throughfloat32, exact up to \(2^{24}\));boolpatches are True where any covering patch is True;float16andbfloat16patches are summed infloat32.unpaddingandallow_auto_unpaddingfollow thepaddingandallow_auto_paddingrules ofextract_tensor_patches(); without either, patches that do not fitoriginal_sizegive a warning.This function takes
allow_auto_unpaddingbeforeunpadding.An empty batch is reconstructed with the same spatial size and unpadding as a non-empty one.
- Parameters:
patches (
Tensor) – the patches,(B, N, C, h, w).original_size (
Union[int,Tuple[int,int]]) – the size(H, W)of the image the patches were extracted from, and of the output.window_size (
Union[int,Tuple[int,int]]) – the size of the sliding window used while extracting patches.stride (
Union[int,Tuple[int,int]]) – stride of the sliding window. Required.allow_auto_unpadding (
bool, optional) – whether to remove the paddingcompute_padding()computes when the windows do not fitoriginal_size. Default:Falseunpadding (
Union[int,Tuple[int,int],Tuple[int,int,int,int]], optional) – the padding used while extracting the patches, removed from the output. Default:0eps (
Optional[float], optional) – deprecated, has no effect. Each covered pixel is divided by its exact overlap count and a pixel no patch covers is 0. Default:None
- Return type:
- Returns:
The combined patches in an image tensor with shape
(B, C, H, W).- Raises:
ValueError – if
patchesis not 5-D.ValueCheckError – if a
window_sizeorstridecomponent is below 1.AssertionError – if
strideis larger thanwindow_size, which leaves pixels uncovered, or ifunpaddingis a tuple of other than two or four ints.RuntimeError – if the number or size of the patches does not match
original_size,window_size,strideandunpadding.
See also
extract_tensor_patches(): cuts the patches this function puts back.CombineTensorPatches: the module form.compute_padding(): theunpaddingthat makes the windows fit.
Example
>>> out = extract_tensor_patches(torch.arange(16).view(1, 1, 4, 4), window_size=(2, 2), stride=(2, 2)) >>> combine_tensor_patches(out, original_size=(4, 4), window_size=(2, 2), stride=(2, 2)) tensor([[[[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]]])
- class kornia.contrib.ExtractTensorPatches(window_size, stride=1, padding=0, allow_auto_padding=False)[source]#
Cut an image into sliding-window patches with stored settings (module form).
extract = ExtractTensorPatches(window_size, stride, padding)stores its arguments, andpatches = extract(image)isextract_tensor_patches()on a(B, C, H, W)image, returning(B, N, C, h, w)patches.- Convention:
See the Convention block on
extract_tensor_patches().
- Parameters:
window_size (
Union[int,Tuple[int,int]]) – the size(h, w)of the sliding window and of each patch, or one int for both.stride (
Union[int,Tuple[int,int]], optional) – stride of the sliding window, an int or(sh, sw). Default: 1.padding (
Union[int,Tuple[int,int],Tuple[int,int,int,int]], optional) – zero padding, or cropping where negative: an int,(ph, pw)or(top, bottom, left, right). Default:0allow_auto_padding (
bool, optional) – whether to pad the image ascompute_padding()computes when the windows do not fit. Default:False
- Shape:
Input:
(B, C, H, W)Output:
(B, N, C, h, w)
- Raises:
ValueCheckError – if a
window_sizeorstridecomponent is below 1; raised from the constructor.
See also
extract_tensor_patches(): the one-call form.CombineTensorPatches: puts the patches back into an image.
Examples
>>> input = torch.arange(9.).view(1, 1, 3, 3) >>> patches = ExtractTensorPatches((2, 3))(input) >>> input tensor([[[[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]]]]) >>> patches[:, -1] tensor([[[[3., 4., 5.], [6., 7., 8.]]]])
- class kornia.contrib.CombineTensorPatches(original_size, window_size, stride=None, unpadding=0, allow_auto_unpadding=False)[source]#
Reassemble sliding-window patches into an image with stored settings (module form).
combine = CombineTensorPatches(original_size, window_size, stride, unpadding)stores its arguments, andimage = combine(patches)iscombine_tensor_patches()on(B, N, C, h, w)patches, returning a(B, C, H, W)image. Unlikecombine_tensor_patches(),stridedefaults towindow_size;ExtractTensorPatchesdefaults it to 1, so pass the samestrideto both.- Convention:
See the Convention block on
combine_tensor_patches().
- Parameters:
original_size (
Tuple[int,int]) – the size(H, W)of the image the patches were extracted from, and of the output.window_size (
Union[int,Tuple[int,int]]) – the size of the sliding window used while extracting patches.stride (
Union[int,Tuple[int,int],None], optional) – stride of the sliding window. Default:window_size.unpadding (
Union[int,Tuple[int,int],Tuple[int,int,int,int]], optional) – the padding used while extracting the patches, removed from the output. Default:0allow_auto_unpadding (
bool, optional) – whether to remove the paddingcompute_padding()computes when the windows do not fitoriginal_size; pass it when the patches were extracted withallow_auto_padding=True. Default:False
- Shape:
Input:
(B, N, C, h, w)Output:
(B, C, H, W)
- Raises:
ValueCheckError – if a
window_sizeorstridecomponent is below 1; raised from the constructor.
See also
combine_tensor_patches(): the one-call form.ExtractTensorPatches: cuts the patches this module puts back.
Example
>>> out = extract_tensor_patches(torch.arange(16).view(1, 1, 4, 4), window_size=(2, 2), stride=(2, 2)) >>> CombineTensorPatches(original_size=(4, 4), window_size=(2, 2))(out) tensor([[[[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]]])
Histogram Matching#
- kornia.contrib.histogram_matching(source, template)[source]#
Remap the values of an image so that its histogram matches the histogram of a template.
out = histogram_matching(source, template)maps each value ofsourceto thetemplatevalue at the same quantile and returns a tensor with the shape ofsource. One histogram covers all ofsource, batch and channels together: to match each image or channel on its own, call the function on each slice. The result is not differentiable.The implementation follows this answer; see also histogram matching.
- Convention:
This is
skimage.exposure.match_histograms(source, template, channel_axis=None), which needs both inputs to have the same number of dimensions (flatten them otherwise).A source value maps to the template value at its quantile, interpolated linearly between template values with
interp(). The result stays inside the template’s range once that range is rounded to the output dtype, so with afloat64template and afloat32source it can pass the unrounded ends by that rounding. It can also fall between template values: auint8template gives fractional values, as in skimage.A floating source keeps its dtype; an integer or
boolsource returnsfloat32. The quantiles are computed infloat32(float64for afloat64source).With a non-empty
source, no gradient reaches it and a backward pass intotemplateraises.An empty
sourcewith a non-emptytemplatereturns an empty tensor, still attached to its autograd graph.
- Parameters:
- Return type:
- Returns:
The transformed output image, with the shape of the source image.
- Raises:
ValueError – if
templateis empty, even whensourceis empty too.
See also
interp(): the linear interpolation that maps the quantiles.equalize(): flattens the histogram of each channel, with no template.
- kornia.contrib.interp(x, xp, fp)[source]#
Interpolate samples
(xp, fp)linearly at query points, extrapolating the end segments.y = interp(x, xp, fp)evaluates the piecewise-linear function through the 1-D samplesxp(increasing) andfpat every element ofxand returns a tensor with the shape ofx. Outside[xp[0], xp[-1]]it extends the first and last segments, wherenumpy.interp()clamps tofp[0]andfp[-1]. It is differentiable inx,xpandfp.- Convention:
SciPy’s
interp1d(xp, fp, fill_value="extrapolate")makes the same extrapolation choice. At a knot the result is that knot’sfp.xpmust be increasing, which is not checked.The output dtype is the promoted dtype of
x,xpandfp, or the default float dtype when all three are integer. A complexfpinterpolates its real and imaginary parts separately.A
float16orbfloat16result is computed infloat32and cast to the output dtype once, so coordinate differences above 65504 do not overflow the weight and a segment whosefpdifference overflows the output dtype stays finite. Inside a segment the result is within about half an ulp of the segment’s larger end value, and the knots are exact.float32andfloat64results are computed in their own dtype. An integerxorxpmixed with floating coordinates is converted to the dtype the result is computed in, so infloat32it is exact only up to \(2^{24}\): larger integer knots can merge and larger integer queries are rounded.
- Parameters:
- Return type:
- Returns:
the interpolated values, with the shape of
x.
See also
histogram_matching(): maps image values through this interpolation of template quantiles.
Image Classification#
- class kornia.models.vit.VisionTransformer(image_size=224, patch_size=16, in_channels=3, embed_dim=768, depth=12, num_heads=12, dropout_rate=0.0, dropout_attn=0.0, backbone=None)[source]#
Vision transformer (ViT) module.
The module is expected to be used as operator for different vision tasks.
The method is inspired from existing implementations of the paper [DBK+21].
Without a
backbone, the input must beimage_sizesquare within_channelschannels. With one, the backbone’s token grid must be the one it gives for animage_sizeinput, which the position embeddings are built for; a backbone that ends in adaptive pooling, for example, gives that grid at any input size. The AugReg weights thatfrom_config()loads were trained on images normalized with mean = std = 0.5 per channel, so a \([0, 1]\) image goes in askornia.enhance.normalize(image, torch.tensor([0.5, 0.5, 0.5]), torch.tensor([0.5, 0.5, 0.5])).Warning
This is an experimental API subject to changes in favor of flexibility.
- Parameters:
image_size (
int, optional) – the size of the input image. Default:224patch_size (
int, optional) – the size of the patch to compute the embedding. Default:16in_channels (
int, optional) – the number of channels for the input. Default:3embed_dim (
int, optional) – the embedding dimension inside the transformer encoder. Default:768depth (
int, optional) – the depth of the transformer. Default:12num_heads (
int, optional) – the number of attention heads. Default:12dropout_rate (
float, optional) – dropout rate. Default:0.0dropout_attn (
float, optional) – attention dropout rate. Default:0.0backbone (
Module|None, optional) – an nn.Module to compute the image patches embeddings, as a \((B, D, h, w)\) map. The position embeddings are sized by probing animage_sizeinput in evaluation mode. The backbone must give the same patch grid in training and evaluation modes for that input size. Default:None
Example
>>> img = torch.rand(1, 3, 224, 224) >>> vit = VisionTransformer(image_size=224, patch_size=16) >>> vit(img).shape torch.Size([1, 197, 768])
- property encoder_results: list[Tensor]#
Return intermediate outputs captured by the transformer encoder.
- Returns:
List of tensors produced by the encoder blocks. Each tensor stores token embeddings for a layer, typically shaped
(B, N, D), where \(B\) is batch size, \(N\) is token count, and \(D\) is embedding dimension.
- forward(x)[source]#
Encode an image batch into Vision Transformer token embeddings.
- Parameters:
x (
Tensor) – Image tensor with shape(B, C, H, W). Without abackbone, \(C\) must equalself.in_channelsand \(H\) and \(W\) must both equalself.image_size; with one, the backbone’s token grid must be the one it gives for animage_sizeinput. The position embeddings are a fixed table, one row per token of that grid.- Return type:
- Returns:
Normalized token embedding tensor produced by patch embedding and the transformer encoder. The output shape follows the encoder layout, usually
(B, N, D).- Raises:
ValueError – without a
backbone, if \(C\) is notin_channelsor(H, W)is not(image_size, image_size); with one, if the backbone’s token grid is not the one it gives for animage_sizeinput.
- static from_config(variant, pretrained=False, **kwargs)[source]#
Build ViT model based on the given config string.
The format is
vit_{size}/{patch_size}. E.g.vit_b/16means ViT-Base, patch size 16x16. Ifpretrained=True, AugReg weights are loaded. The weights are hosted on HuggingFace’s model hub: https://huggingface.co/kornia.Note
The available weights are:
vit_l/16,vit_b/16,vit_s/16,vit_ti/16,vit_b/32,vit_s/32.- Parameters:
variant (
str) – ViT model variant e.g.vit_b/16.pretrained (
bool, optional) – whether to load pre-trained AugReg weights. Default:Falsekwargs (
Any) – other keyword arguments that will be passed tokornia.models.vit.VisionTransformer().
- Return type:
- Returns:
The respective ViT model, in evaluation mode when
pretrained=Trueloads weights and in training mode otherwise (see Pretrained models).
Example
>>> from kornia.models.vit import VisionTransformer >>> vit_model = VisionTransformer.from_config("vit_b/16", pretrained=True)
- class kornia.models.vit_mobile.MobileViT(mode='xxs', in_channels=3, patch_size=(2, 2), dropout=0.0)[source]#
Module MobileViT. Default arguments is for MobileViT XXS.
Paper: https://arxiv.org/abs/2110.02178 Based on: chinhsuanwu/mobilevit-pytorch
- Parameters:
mode (
str, optional) – ‘xxs’, ‘xs’ or ‘s’, defaults to ‘xxs’. Default:"xxs"in_channels (
int, optional) – the number of channels for the input image. Default:3patch_size (
Tuple[int,int], optional) – the patch size \((p_h, p_w)\) the MobileViT blocks unfold their feature maps into, at strides 8, 16 and 32 of the input. Each of those maps must split into whole patches, which an input height and width that are multiples of \(32 p_h\) and \(32 p_w\) guarantee: with the default(2, 2), 192, 256 and 320 px run, and 224 and 288 px raise. Default:(2, 2)dropout (
float, optional) – dropout ratio in Transformer. Default:0.0
- Raises:
ValueError – if
modeis not'xxs','xs'or's'.
Example
>>> img = torch.rand(1, 3, 256, 256) >>> mvit = MobileViT(mode='xxs') >>> mvit(img).shape torch.Size([1, 320, 8, 8])
- class kornia.contrib.TinyViT(img_size=224, in_chans=3, num_classes=1000, embed_dims=(96, 192, 384, 768), depths=(2, 2, 6, 2), num_heads=(3, 6, 12, 24), window_sizes=(7, 7, 14, 7), mlp_ratio=4.0, drop_rate=0.0, drop_path_rate=0.0, use_checkpoint=False, mbconv_expand_ratio=4.0, local_conv_size=3, activation=nn.GELU, mobile_sam=False)[source]#
TinyViT model, as described in https://arxiv.org/abs/2207.10666.
The pretrained checkpoints of
from_config()were trained on images normalized with the ImageNet mean and standard deviation, so a \([0, 1]\) image goes in askornia.enhance.normalize(image, torch.tensor([0.485, 0.456, 0.406]), torch.tensor([0.229, 0.224, 0.225])).- Parameters:
img_size (
int, optional) – Size of the square input image, a multiple of 32 (of 16 withmobile_sam=True). The attention stages are built for the token grid of animg_sizeimage (seeforward()). Default:224in_chans (
int, optional) – Number of input image’s channels. Default:3num_classes (
int, optional) – Number of output classes. Default:1000embed_dims (
Sequence[int], optional) – List of embedding dimensions. Default:(96, 192, 384, 768)depths (
Sequence[int], optional) – List of block count for each downsampling stage Default:(2, 2, 6, 2)num_heads (
Sequence[int], optional) – List of attention heads used in self-attention for each downsampling stage. Default:(3, 6, 12, 24)window_sizes (
Sequence[int], optional) – List of self-attention’s window size for each downsampling stage. Default:(7, 7, 14, 7)mlp_ratio (
float, optional) – Ratio of MLP dimension to embedding dimension in self-attention. Default:4.0drop_rate (
float, optional) – Dropout rate. Default:0.0drop_path_rate (
float, optional) – Stochastic depth rate. Default:0.0use_checkpoint (
bool, optional) – Whether to use activation checkpointing to trade compute for memory. Default:Falsembconv_expand_ratio (
float, optional) – Expansion ratio used in MBConv block. Default:4.0local_conv_size (
int, optional) – Kernel size of convolution used in TinyViTBlock Default:3activation (
type[Module], optional) – activation function. Default:nn.GELUmobile_sam (
bool, optional) – Whether to use modifications for MobileSAM. Default:False
- forward(x)[source]#
Classify images if
mobile_sam=False, produce feature maps ifmobile_sam=True.- Parameters:
x (
Tensor) – images(B, C, H, W)with \(H = W =\)img_size. The strided convolutions before the first attention stage round up, so \(H\) and \(W\) fromimg_size - 7toimg_sizegive the same token grid and run too.- Raises:
ValueError – if the input gives a token grid other than that of an
img_sizeimage.- Return type:
- static from_config(variant, pretrained=False, **kwargs)[source]#
Create a TinyViT model from pre-defined variants.
Returns the model in evaluation mode when
pretrainedloads the complete weights, classification head included, and in training mode otherwise (see Pretrained models).- Parameters:
variant (
str) – TinyViT variant. Possible values:'5m','11m','21m'.pretrained (
bool|str, optional) – whether to use pre-trained weights. Possible values:False,True,'in22k','in1k'. For TinyViT-21M (variant='21m'),'in1k_384','in1k_512'are also available; named, they build at theimg_sizeyou pass (224 by default), so passimg_size=384or512to run them at their resolution. Default:False**kwargs (
Any) – other keyword arguments that will be passed toTinyViT. They override the variant’sembed_dims,depths,num_heads,window_sizesanddrop_path_rate.
- Return type:
Note
pretrained=Trueloads the ImageNet-1k checkpoint ('in1k'); for TinyViT-21M it loads'in1k_384'whenimg_sizeis at least 384 and'in1k_512'when it is at least 512. For feature extraction or fine-tuning, the ImageNet-22k checkpoint ('in22k') is preferred.img_sizedoes not change the window sizes: they are the 224-px[7, 7, 14, 7]at everyimg_size, except that the TinyViT-21M'in1k_384'and'in1k_512'checkpoints get the windows they were trained with,[12, 12, 24, 12]and[16, 16, 32, 16], and the stochastic depth rate they were fine-tuned with,drop_path_rate=0.1instead of TinyViT-21M’s 0.2. Awindow_sizesordrop_path_rateargument overrides them. The checkpoint’s attention biases are interpolated (bicubic) only when the window sizes differ from the checkpoint’s.img_sizemust be a multiple of 32 (of 16 withmobile_sam=True), and a checkpoint’s accuracy is not preserved away from the resolution it was trained at: on the panda image of the TinyViT example, TinyViT-5M’s probability of the right class drops from 0.37 at 224 px to 0.02 atimg_size=256.With
pretrainedand anum_classesother than the checkpoint’s, the classification head is reset to zeros, and the model, a pretrained backbone to fine-tune, stays in training mode. The'in22k'checkpoints have a 21841-class head: passnum_classes=21841to get the complete model in evaluation mode. With the defaultnum_classes=1000the head is reset and the model stays in training mode, so call.eval()before extracting features.
Image Stitching#
- class kornia.contrib.ImageStitcher(matcher, estimator='ransac', blending_method='naive')[source]#
Stitch overlapping RGB images, ordered left to right, into one panorama by matched homographies.
stitcher = ImageStitcher(KF.LoFTR(pretrained="outdoor"))builds the stitcher.panorama = stitcher(img_left, img_right, ...)takes RGB images(B, 3, H, W)of one height, ordered left to right, and returns one(B, 3, H, W_pano)panorama in the first image’s pixel frame. Each next image is matched to the panorama so far, and warped onto it with the homography of those matches.- Convention:
matcheris aLoFTRor aLocalFeatureMatcher, which gets grayscale copies of the images; any other matcher raisesNotImplementedError.The panorama has the first image’s height: content that maps left of its first column, or above or below its rows, is lost. Every sample needs 4 matches, or a
RuntimeErrornames the sample."naive"blending keeps the warped image wherever it covers a pixel completely, so in an overlap the right image replaces the left one; a pixel it covers only in part keeps the panorama’s value.W_panois at most the sum of the widths: the result drops the empty trailing columns, those after the last column that any sample covers; an uncovered column before it, the first one included, is kept. A batch shares one crop, so it is cropped to its widest sample and a narrower sample keeps zero columns on its right.estimator="ransac"fits the inliers thatRANSACfinds for"homography"(inl_th=2.0)."vanilla"fits every match withfind_homography_dlt_iterated(), which down-weights matches by their transfer error after the first fit.
- Parameters:
matcher (
Module) – image feature matching module,LoFTRorLocalFeatureMatcher.estimator (
str, optional) – method to compute homography,"ransac"or"vanilla"; another value raisesNotImplementedError. Default:"ransac"blending_method (
str, optional) – method to blend two images together. Only “naive” is currently supported. Default:"naive"
import torch import kornia.feature as KF from kornia.contrib import ImageStitcher device = torch.device("cuda" if torch.cuda.is_available() else "cpu") stitcher = ImageStitcher(KF.LoFTR(pretrained="outdoor"), estimator="ransac").to(device) # img_left and img_right: (1, 3, H, W) RGB images of one height on `device` with torch.inference_mode(): panorama = stitcher(img_left, img_right)
See Image Stitching for a complete example.
See also
ImageRegistrator: aligns one image to another by optimising a homography on the pixels, without matches and without a panorama.HomographyTracker: returns a planar target’s homography in each video frame, starting from the previous frame’s, and builds no panorama.warp_perspective(): warps one image by a homography you already have.RANSAC: the robust homography estimator ofestimator="ransac".
Lambda#
- class kornia.contrib.Lambda(func)[source]#
Wrap a Python callable as an
nn.Modulethat applies it to its input.f = Lambda(func)storesfunc, andout = f(img, *args, **kwargs)returnsfunc(img, *args, **kwargs)unchecked; it need not be a tensor. Use it to put a plain function into annn.Sequentialor an augmentation container.- Parameters:
- Raises:
TypeError – if
funcis not callable; raised from the constructor.
See also
ImageSequential: chains augmentations; aLambdaruns in it as one step.
Example
>>> import kornia >>> x = torch.rand(1, 3, 5, 5) >>> f = Lambda(lambda x: kornia.color.rgb_to_grayscale(x)) >>> f(x).shape torch.Size([1, 1, 5, 5])
Distance Transform#
- kornia.contrib.distance_transform(image, kernel_size=3, h=0.35)[source]#
Compute the distance to the nearest positive pixel per channel, weighted for values below 1, in 2D or 3D.
dist = distance_transform(image)takes a floating(B, C, H, W)image or(B, C, D, H, W)volume and returns, per channel, the distance to the nearest positive pixel. For a binary mask it is the Euclidean distance in pixels, exact up to floating-point rounding. A value \(0 < v < 1\) is a soft source that adds \(-h \log v\) to the squared distance, and the result is piecewise differentiable in the image:\[D(p) = \sqrt{\min_{q: v(q)>0} \left(\|p-q\|_2^2 - h\log v(q)\right)}, \qquad v = \operatorname{clip}(\mathrm{image}, 0, 1).\]The separable minimum-convolution formulation follows section 2.2 of Distance Transforms of Sampled Functions (Felzenszwalb and Huttenlocher, 2012). The implementation uses tiled tensor reductions, not the paper’s linear-time envelope algorithm: its work scales as the number of input elements times the sum of the spatial dimensions.
- Convention:
Distances are to positive pixels, whereas SciPy and OpenCV measure distances to zero pixels. On a nonempty binary mask this matches
scipy.ndimage.distance_transform_edt(image == 0)per batch/channel.A channel without positive pixels returns zeros, preserving the empty-mask convention.
A fractional source adds
-h * log(v)to the squared distance, including at the source itself. Its influence extends throughout the image. Multiple sources compete by their minimum cost; they do not lower distances by being counted repeatedly.The operation is piecewise differentiable. For a unique minimizing source and
D(p) > 0, its derivative is-h / (2 * v(q) * D(p)). At ties, one minimizing source receives the gradient (the first selected by the axis-wise reductions). At zero distance the derivative is defined as zero to avoid the square-root singularity. Nonpositive inputs and values above 1 have zero gradient; the derivative of clipping at exactly 1 passes through. There is no straight-through estimator.For dense fractional masks, a pixel with
-h * log(v) < 1selects itself: every other pixel is at least one squared pixel away. Increasehto let stronger neighbours compete over longer distances.float16andbfloat16inputs are computed infloat32and cast back.
- Parameters:
image (
Tensor) – Floating-point image or volume of shape(B, C, H, W)or(B, C, D, H, W).kernel_size (
int, optional) – Odd integer of at least 3, retained for call compatibility. It does not change the result: the transform considers the entire spatial domain. Default:3h (
float, optional) – Positive finite weight of the fractional-source cost in squared pixel units. It does not affect binary distances.h, source costs and gradients must remain representable in the working dtype. Default:0.35
- Return type:
- Returns:
Distances with the input’s shape, dtype and device.
- Raises:
BaseError – if
imageis not a floating tensor of 4 or 5 dimensions with nonempty spatial sizes,kernel_sizeis not an odd int of at least 3, orhis not positive and finite.
See also
DistanceTransform: the module form.
Example
>>> image = torch.zeros(1, 1, 5, 5) >>> image[:, :, 0, 0] = 1 >>> distance_transform(image)[0, 0, 3, 4] tensor(5.)
- class kornia.contrib.DistanceTransform(kernel_size=3, h=0.35)[source]#
Compute the distance to the nearest positive pixel per channel (module form).
dt = DistanceTransform(h=0.35)stores its arguments, anddist = dt(image)isdistance_transform()on a(B, C, H, W)image or(B, C, D, H, W)volume, returning distances of the same shape, dtype and device.- Convention:
See the Convention block on
distance_transform().
- Parameters:
kernel_size (
int, optional) – Odd integer of at least 3, retained for compatibility; does not affect distances. Default:3h (
float, optional) – Positive finite weight of the squared-distance source cost. Seedistance_transform(). Default:0.35
See also
distance_transform(): the one-call form, with the gradient conventions.
Plasma Fractal Noise#
- kornia.contrib.diamond_square(output_size, roughness=0.5, random_scale=1.0, random_fn=torch.rand, normalize_range=None, device=None, dtype=None)[source]#
Generate plasma-fractal noise maps by the diamond-square algorithm.
noise = diamond_square((B, C, H, W))returns a(B, C, H, W)map of spatially correlated noise, an independent fractal in each(b, c)plane.roughnessandrandom_scaleset how much of each finer level is random rather than interpolated, andnormalize_rangerescales each plane to a given range. It ports tormentor’s variant of the diamond-square algorithm.- Convention:
The map is grown on a \(2^n + 1\) grid and cropped to
output_sizeat its top-left corner. The seed is a \(3 \times K\) grid, transposed to \(K \times 3\) for a map taller than wide, whose cell corners, the even nodes of its first and last rows (columns when transposed), arerandom_fndraws, and whose other nodes are the means of their neighbours. Each level sets a new node to \((1 - s_k)\,\overline{n} + s_k\,u\), the mean \(\overline{n}\) of its neighbours mixed with arandom_fndraw \(u\) by the weight \(s_k = \mathrm{random\_scale} \cdot \mathrm{roughness}^k\) at level \(k \geq 1\).random_scaleandroughnessact only through \(s_k\), a mixing weight, not an amplitude. A border node of the square step averages its three neighbours; the diamond step’s nodes are all interior, so itsreflectpadding never reaches them.random_fnis called asrandom_fn(shape, device=device, dtype=dtype)and is the only source of randomness, sofunctools.partial(torch.rand, generator=g)leaves the global generator alone. Withtorch.randthe map stays in \([0, 1]\) without normalization whilerandom_scaleandroughnessare in \([0, 1]\), and it is flat in mean (0.5 at every pixel) for everyrandom_scale, though its variance varies across the map.roughnessandrandom_scaleare a float, a 0-d tensor or a(B,)tensor with one value per sample, and followdeviceanddtype; withdtype=Nonea tensor keeps its dtype and a float takes the default dtype. Whenrandom_fnreturns the dtype it is asked for, the map has the dtype thatdtype(the default dtype forNone),roughnessandrandom_scalepromote to, at every map size. Arandom_fnthat returns another dtype also promotes the levels’ arithmetic to its dtype, but not a map with a side of 3 px or less, which is the seed alone and stores the draws in the requested dtype.Without
normalize_rangethe result can be a non-contiguous view, which.view(B, -1)cannot flatten; use.reshape, or call.contiguous()first.normalize_range=(min, max)rescales each \((b, c)\) plane to that range withnormalize_min_max(), whoseepskeeps the maximum just belowmax.
- Parameters:
output_size (
Tuple[int,int,int,int]) – the(B, C, H, W)size of the map to generate.roughness (
Union[float,Tensor], optional) – the factor that scales the mixing weight at each recursion step. Default:0.5random_scale (
Union[float,Tensor], optional) – scales the per-level mixing weight \(s_k = \mathrm{random\_scale} \cdot \mathrm{roughness}^k\), \(k \geq 1\). Default:1.0random_fn (
Callable[...,Tensor], optional) – the callable function to use to sample a random tensor. Default:torch.randnormalize_range (
Optional[Tuple[float,float]], optional) – if given, the(min, max)range each plane is min-max normalized to. Default:Nonedevice (
Optional[device], optional) – the torch device to place the output map. Default:Nonedtype (
Optional[dtype], optional) – the torch dtype to place the output map. Default:None
- Return type:
- Returns:
The fractal map,
(B, C, H, W).- Raises:
BaseError – if
output_sizedoes not have four entries.
See also
RandomPlasmaShadow: darkens image regions with these maps.RandomPlasmaBrightness: shifts image brightness by these maps.RandomPlasmaContrast: scales image contrast by these maps.
KMeans#
- class kornia.contrib.KMeans(num_clusters, cluster_centers, tolerance=10e-4, max_iterations=0, seed=None)[source]#
Cluster
(N, D)points intonum_clustersgroups by k-means with Euclidean distance.kmeans = KMeans(num_clusters, cluster_centers)stores the settings, andkmeans.fit(X)alternates nearest-centre assignment and centre means on the(N, D)pointsX.labels = kmeans.predict(x)returns theint64index of the nearest centre for each row of(M, D)points. Afterfit(),cluster_centersis(num_clusters, D)andcluster_assignmentsholds the(N,)labels ofX.- Convention:
fit()stops after the first update whose squared total centre shift, \((\sum_k \lVert c_k^{\text{new}} - c_k \rVert)^2\), is at mosttolerance, or aftermax_iterationsupdates.max_iterations=0sets no limit, sotolerancemust not beNonethen.seedcallstorch.manual_seed(seed), which reseeds the global generator. The initial centres and the points that empty clusters move to are drawn from it; there is nogeneratorargument. A secondfit()on the same data therefore starts from other centres unless the global generator is reseeded first.A point at the same distance from two centres goes to the one with the lower index. A cluster that gets no point moves to a random data point.
Distances and means are computed in the promoted dtype of the data and the centres, at least
float32(int64for integer data and centres). The centres keep the dtype of the data, so an integer mean is truncated toward zero.
- Parameters:
num_clusters (
int) – number of clusters the data has to be assigned to, a positive integer. Required, also withcluster_centers; without them,fit()needs at leastnum_clusterssamples.cluster_centers (
Tensor|None) – the(num_clusters, D)starting centres, orNoneto sample them from the data in eachfit(). PassNoneexplicitly; the argument has no default.tolerance (
float, optional) – the bound on the squared total centre shift that stopsfit(), orNoneto stop only aftermax_iterationsupdates. Default:10e-4max_iterations (
int, optional) – the maximum number of updates; 0 sets no limit. Default:0seed (
int|None, optional) – if given, passed totorch.manual_seedwhen the object is created. Default:None
- Raises:
BaseError – if
num_clustersis not a positive integer,max_iterationsortoleranceis negative,tolerance=Nonecomes withmax_iterations=0, orcluster_centersis not(num_clusters, D).
Example
>>> kmeans = kornia.contrib.KMeans(3, None, 10e-4, 100, 0) >>> kmeans.fit(torch.rand((1000, 5))) >>> predictions = kmeans.predict(torch.rand((10, 5)))
- property cluster_assignments: Tensor#
Return cluster labels assigned during the most recent
fitcall.
- property cluster_centers: Tensor#
Return the current cluster centers.
- Returns:
Cis the number of clusters.Dis the feature dimension of each sample.
If
fit()has already been called, this returns the learned final centers. Otherwise, it returns the initialization provided during construction.- Return type:
A tensor with shape
(C, D)- Raises:
TypeError – If no initial centers were provided and
fithas not been run.
- predict(x)[source]#
Return the index of the nearest cluster centre for each row of
x.- Parameters:
x (
Tensor) – the(M, D)points, with theDofcluster_centers.- Return type:
- Returns:
The
(M,)int64cluster indices.
Super Resolution#
- class kornia.contrib.SuperResolution(model, pre_processor, post_processor, name=None)[source]#
Run a super-resolution network on RGB images with its pre- and post-processing.
sr = SuperResolution(model, pre_processor, post_processor)wraps a super-resolution network.out = sr(images)takes a(B, 3, H, W)tensor or a list of(3, H, W)images, runspre_processor,modelandpost_processorin turn, and returns what the post-processor returns. For the pretrained models, useRRDBNetBuilder,SmallSRBuilderorfrom_config().See also
RRDBNetBuilder: Real-ESRGAN weights, x4 or x2, without resizing the input first.SmallSRBuilder: a small network that upscales a 224 x 224 resize by 3.SuperResolutionConfig: picks either builder by name, forfrom_config().resize(): interpolation to any size, without a network.
- forward(images)[source]#
Forward pass of the super resolution model.
- Parameters:
images (
Union[Tensor,List[Tensor]]) – If list of RGB images. Each image is a torch.Tensor with shape(3, H, W). If torch.Tensor, a torch.Tensor with shape(B, 3, H, W).- Returns:
for the builders’ models, see
RRDBNetBuilderandSmallSRBuilder.- Return type:
What the post-processor returns
- static from_config(config)[source]#
Build a super-resolution model from a configuration object.
Dispatches to
SmallSRBuilderfor the lightweight variant and toRRDBNetBuilderfor the RRDB variants.- Parameters:
config (
SuperResolutionConfig) – Super-resolution configuration. SeeSuperResolutionConfig.- Return type:
- Returns:
A
SuperResolutionwrapper ready for inference.- Raises:
ValueError – If
config.model_nameis not a supported variant.
- save(images, edge_maps=None, directory=None, output_type='torch')[source]#
Save the input images and their super-resolved images as PNG files.
- Parameters:
edge_maps (
Union[Tensor,List[Tensor],None], optional) – super-resolved images; computed withforward()when None. Default:Nonedirectory (
Optional[str], optional) – where to save outputs. Default:Noneoutput_type (
str, optional) – “torch” or “pil”, passed tovisualize(); the files hold the same pixels either way. Default:"torch"
- Return type:
- to_onnx(onnx_name=None, include_pre_and_post_processor=True, save=True, additional_metadata=None, **kwargs)[source]#
Export the current super resolution model to an ONNX model file.
- Parameters:
onnx_name (
Optional[str], optional) – The name of the output ONNX file. If not provided,"kornia_<name>.onnx", with the model’sname, for example"kornia_small_sr.onnx". Default:Noneinclude_pre_and_post_processor (
bool, optional) – Whether to include the pre-processor and post-processor in the exported model. Default:Truesave (
bool, optional) – If True, write the model toonnx_name; it is returned either way. Default:Trueadditional_metadata (
Optional[List[Tuple[str,str]]], optional) – Additional metadata to add to the ONNX model. Default:Nonekwargs (
Any) – Additional keyword arguments oftorch.onnx.export().
- Return type:
ModelProto- Returns:
The exported ONNX model.
- Raises:
ValueError – With the pre- and post-processor, if the output is a list (or tuple) with one image per input image and the exported batch is dynamic, from a
dynamic_axesordynamic_shapesargument or, with the TorchScript exporter, because the list comes only for more than one image.
Note
With the pre- and post-processor, an output that is a list with one image per input image, or a tuple as long as the batch at two batch sizes, is exported for a batch of one image: the exporters turn such a sequence into one graph output per traced image, so a dynamic batch would return the traced batch’s images at any batch size. The list comes from a post-processor that returns one, from the network itself, or from a pre-processor that returns a list of images, which
forward()runs through the network one at a time. Known tensor-output networks (the builders’ RRDB and SmallSR networks,nn.Identityandnn.Conv2d) withnn.IdentityorResizePreProcessorbefore them andnn.IdentityorOutputRangePostProcessorafter them keep a dynamic batch without a probe, provided the wrapper and each component retain their knownforwardimplementations and no forward hook applies to them, a global one included. Other combinations are probed on one image at the export size in eval mode, without gradients and outside the export. A list result requires a fixed batch; a tensor result is checked again on the actual tracing batch before accepting a dynamic graph. A dynamic graph with per-image outputs raises aValueErrorafter the export, before anything is saved.
- class kornia.contrib.SuperResolutionConfig(model_name='small_sr', pretrained=True, upscale_factor=3, image_size=None)[source]#
Choose a super-resolution model by name, to build with SuperResolution.from_config.
sr = SuperResolution.from_config(SuperResolutionConfig("RealESRGAN_x4plus"))builds that model withRRDBNetBuilder.build();"small_sr", the default, builds withSmallSRBuilder.build(). The fields are the arguments of those builders:upscale_factorandimage_sizeapply only to"small_sr".- Parameters:
model_name (
str, optional) – Name of the model variant to build. RRDB variants are"RealESRGAN_x4plus","RealESRNet_x4plus","RealESRGAN_x4plus_anime_6B"and"RealESRGAN_x2plus", spelled exactly; the lightweight variant is"small_sr", in any case. Default:'small_sr'pretrained (
bool, optional) – IfTrue, load pretrained weights for the selected variant. Default:Trueupscale_factor (
int, optional) – Integer scale of"small_sr"(seeSmallSRBuilder.build()). Ignored by the RRDB variants, whose scale is fixed bymodel_name. Default:3image_size (
Optional[int], optional) – The fixed input size of"small_sr"for ONNX export (seeSmallSRBuilder.build()). Default:None
See also
SuperResolution: the model thatSuperResolution.from_config()builds from this.RRDBNetBuilder: builds the RRDB variants directly.SmallSRBuilder: builds"small_sr"directly.
- class kornia.contrib.SmallSRBuilder[source]#
Build a SuperResolution model around a small sub-pixel network that upscales a 224 x 224 resize.
sr = SmallSRBuilder.build()downloads the weights on first use and returns aSuperResolution.out = sr(images)resizes each RGB image in \([0, 1]\) to 224 x 224, discarding its aspect ratio, and returns one(B, 3, 224 r, 224 r)tensor in \([0, 1]\),r = upscale_factor.See also
RRDBNetBuilder: Real-ESRGAN weights, x4 or x2, keeping the aspect ratio.SuperResolutionConfig: picks this builder or the other by name.
- static build(model_name='small_sr', pretrained=True, upscale_factor=3, image_size=None)[source]#
Build the small super-resolution model.
- Parameters:
model_name (
str, optional) – Name of the model variant to build. Only"small_sr"(any case) is supported. Default:"small_sr"pretrained (
bool, optional) – IfTrue, load pretrained weights for the selected model. Default:Trueupscale_factor (
int, optional) – Integer scale used bySmallSRNetWrapper. The pre-processor first resizes every input to 224 x 224, discarding its aspect ratio, so the output is224 * upscale_factorsquare: with3, a 100 x 50 and a 480 x 640 input both give 672 x 672. Pretrained weights exist only for3; another factor withpretrained=Trueraises a size-mismatchRuntimeError. Default:3image_size (
Optional[int], optional) – Optional fixed input height and width of the graph thatSuperResolution.to_onnx()exports;Noneleaves them dynamic. It does not change the pre-processor, which always resizes to 224, so the output side stays224 * upscale_factor. Default:None
- Return type:
- Returns:
A
SuperResolutioninstance configured with resizing pre-processing and identity post-processing, the network’s output being in \([0, 1]\) already.- Raises:
ValueError – If
model_nameis not supported.
- class kornia.contrib.RRDBNetBuilder[source]#
Build a SuperResolution model around a Real-ESRGAN RRDB generator that upscales by 4 or 2.
sr = RRDBNetBuilder.build("RealESRNet_x4plus")downloads the released Real-ESRGAN weights on first use and returns aSuperResolution.out = sr(images)upscales RGB images without resizing them first: a(B, 3, H, W)tensor becomes(B, 3, 4 H, 4 W), or(B, 3, 2 H, 2 W)for"RealESRGAN_x2plus", clamped to \([0, 1]\). A list of(3, H, W)images, of any sizes, returns a list.See also
SmallSRBuilder: a small network that upscales a 224 x 224 resize by 3.RRDBNet: the generator itself, to train or to load other weights.SuperResolutionConfig: picks this builder or the other by name.
- static build(model_name='RealESRNet_x4plus', pretrained=True)[source]#
Build a Real-ESRGAN super-resolution model.
- Parameters:
model_name (
str, optional) – Name of the RRDB variant to construct, spelled exactly:"RealESRGAN_x4plus"and"RealESRNet_x4plus"(23 blocks, x4),"RealESRGAN_x4plus_anime_6B"(6 blocks, x4) and"RealESRGAN_x2plus"(23 blocks, x2), which needs evenHandW. Default:"RealESRNet_x4plus"pretrained (
bool, optional) – IfTrue, download and load pretrained weights for the selected model variant; otherwise the network is randomly initialized. Default:True
- Return type:
- Returns:
A
SuperResolutionwrapper ready for inference.- Raises:
ValueError – If
model_nameis not one of the supported variants.