Conventions & Pitfalls#
Every Kornia function follows the conventions below unless its documentation explicitly says otherwise. If you are generating code (human or LLM), read this page first — nearly every subtle Kornia bug is a convention mismatch, not a math error.
Image tensors#
Images are 4D float tensors
(B, C, H, W), channel order RGB, values in[0, 1]. The batched layout is accepted everywhere; some op families (e.g. color conversions) also accept(*, C, H, W)with arbitrary leading dims.Ops run on the device/dtype of their inputs. There is no implicit
.cuda(),.float(), or value rescaling.Convert NumPy HWC images with
kornia.image.image_to_tensor()(kornia.utils.image_to_tensoris deprecated since 0.8.3):
import numpy as np
import torch
import kornia
np_img = (np.random.rand(48, 64, 3) * 255).astype(np.uint8) # (H, W, C) uint8
t = kornia.image.image_to_tensor(np_img)[None].float() / 255.0 # (1, 3, 48, 64) in [0, 1]
Files and arrays#
kornia.io.load_image() returns a (C, H, W) tensor in RGB order, with alpha last. The load type fixes its
channels, dtype and range, whatever the file holds:
|
channels |
dtype and range |
|---|---|---|
|
1, 3, 4 |
|
|
1, 3 |
|
|
the file’s |
the file’s: |
Every type except
UNCHANGEDloads an 8-bit palette PNG as its colours and raises for a file of more than 8 bits;RGBA8keeps the alpha, and the other types composite it over white.UNCHANGEDreturns a palette PNG’s indices, keeps an alpha channel as stored and ignores atRNSchunk.The EXIF orientation is ignored: the pixels come back as stored.
kornia.io.write_image()writes the tensor as it is, channels first, RGB with alpha last, without scaling: JPEG takesuint8, PNGuint8anduint16, and TIFFuint8,uint16andfloat32, each with 1 or 3 channels, and PNG also with 4.kornia.image.image_to_tensor()andkornia.image.tensor_to_image()do not rescale the values and, by default, share memory with a CPU array instead of copying it; their Convention blocks list the exceptions.kornia.image.image_list_to_tensor()copies.
The same tasks in OpenCV, Pillow and torchvision:
Their call |
kornia |
Difference |
|---|---|---|
|
|
OpenCV returns |
|
|
kornia converts the decoded RGB image as |
|
|
Both keep 16-bit data and alpha, OpenCV in BGR(A) order. OpenCV expands a palette PNG into colours; kornia returns its indices. |
|
|
OpenCV takes |
Pillow |
|
Pillow drops alpha instead of compositing it, and its gray can differ from kornia’s by one level. Neither turns
the image by its EXIF orientation; |
Pillow |
|
Both give the palette indices of an 8-bit palette PNG; kornia raises for 1, 2 or 4 bits per pixel. |
Pillow |
|
Pillow’s JPEG quality defaults to 75, kornia’s to 80. |
torchvision |
|
|
torchvision |
|
|
Drawing#
The drawing functions take points as (x, y) in the pixel frame of Coordinates and
sizes, draw into the image they are given and return it, and cast the colour to the image’s dtype without
rescaling it, so a [0, 1] colour on a uint8 image draws black or almost black. Clone the image first to keep
the original; a leaf tensor that requires grad cannot be drawn on.
draw_point2d(),draw_line()anddraw_rectangle()put a fractional coordinate on the pixel whose centre is nearest, halfway rounding up, as OpenCV’s fixed-pointshiftargument does; Pillow and torchvision truncate, so their shapes can sit one pixel up or to the left of kornia’s.draw_convex_polygon()does not round its vertices.A point or a line endpoint outside the image raises
ValueError, where OpenCV and Pillow clip the line; rectangles and polygons are clipped to the image.A single-value colour is written to every channel, where OpenCV’s and Pillow’s scalar colours fill only the first.
Coordinates and sizes#
Point coordinates are
(x, y): x indexes columns, y indexes rows, origin at the top-left pixel. Keypoint tensors are(B, N, 2).Sizes and
dsizearguments are(h, w)— the opposite order from points.warp_perspective(img, M, dsize=(2, 8))produces a 2-row, 8-column image.Normalized coordinates, where used, are
[-1, 1]in both axes.kornia.geometry.grid.create_meshgrid()defaults to a corner-aligned normalized grid (normalized_coordinates=True,align_corners=True), matchingtorch.nn.functional.grid_sample()withalign_corners=True: the first and last pixel centres map to the endpoints. Passingalign_corners=Falsetocreate_meshgriduses the half-pixel mapping that matchesgrid_sample(..., align_corners=False)instead, where the endpoints are the outer pixel edges. Use the same flag in both calls.3D grids and 3D pixel coordinates are
(d, x, y)— depth first, not(x, y, z);kornia.geometry.grid.create_meshgrid3d()produces this order and the*_pixel_coordinates3dconversions consume it.torch.nn.functional.grid_sample()reads a 3D grid as(x, y, z): passgrid[..., [1, 2, 0]]andalign_corners=True, because the normalized 3D grid is corner-aligned and has noalign_cornersargument (#4503).Sub-pixel outputs follow the same orders: the soft-argmax functions of kornia.geometry.subpix return
(x, y)in 2D and(d, x, y)in 3D, and the quadratic refiners (conv_quad_interp3d,iterative_quad_interp3d) return(d, x, y)voxel indices of their input. Normalized outputs are corner-aligned, as above.Non-maximum suppression is strict in
kornia.geometry.subpix.nms2d(),nms3d,nms3d_minmaxand the detectors built on them: with a window of at least 3 on every axis, every pixel of a plateau is suppressed.skimage.feature.peak_local_maxat its defaultmin_distance=1,scipy.ndimage.maximum_filter(x, size=k) == xandcv2.dilate(x, kernel) == xkeep every pixel of the plateau instead.Pixel
(0, 0)is centred at(0, 0)— the OpenCV “integer” convention, not COLMAP’s half-pixel one. Camera and world conventions across the ecosystem catalogues the pixel-centre and camera-frame conventions of the surrounding ecosystem and the converters between them.
Angles and rotations#
Angles are degrees in the 2D image APIs (
rotate,get_rotation_matrix2d,RandomRotation,angle_to_rotation_matrix), and radians in the 3D rotation-representation APIs (axis_angle_to_rotation_matrix,So3) and in the polar conversionscart2pol/pol2cart(rad2deg/deg2radexist to convert).2D image rotations: positive angle rotates counter-clockwise as displayed (top-left origin, matching OpenCV):
import torch
from kornia.geometry.transform import rotate
img = torch.zeros(1, 1, 5, 5)
img[0, 0, 1, 3] = 1.0 # marker up-right of center
out = rotate(img, torch.tensor([90.0]))
assert out[0, 0].round().nonzero().tolist() == [[1, 1]] # moved up-LEFT: CCW on screen
3D rotation conversions follow the right-hand rule in math convention. Because image y points down, a positive rotation about +z from
kornia.geometry.conversions.axis_angle_to_rotation_matrix()moves image points clockwise on screen — the opposite screen direction fromrotate(img, +angle). Do not mix the two without negating the angle:
import torch
from kornia.geometry.conversions import axis_angle_to_rotation_matrix
R = axis_angle_to_rotation_matrix(torch.tensor([[0.0, 0.0, torch.pi / 2]]))
# math convention: (1, 0) -> (0, 1). With y down on screen, that points DOWNWARD.
assert torch.allclose(R[0, :2, :2], torch.tensor([[0.0, -1.0], [1.0, 0.0]]), atol=1e-6)
Quaternions use WXYZ coefficient order (scalar first):
from kornia.geometry.quaternion import Quaternion
q = Quaternion.identity()
assert q.data.tolist() == [1.0, 0.0, 0.0, 0.0] # w, x, y, z
Rotations and rigid motions#
Quaternion multiplies by the Hamilton product, so (q1 * q2).matrix() is
q1.matrix() @ q2.matrix(): the right operand acts first. The Lie groups So3,
Se3, So2 and
Se2 compose the same way and act on a point as R p + t, with R the
matrix() of the rotation part. So2 and Se2 do so for any complex number, and a non-unit one also scales by
its modulus; So3 and Se3 rotate by the direction \(q / |q|\) of a non-unit quaternion, without scaling,
like Quaternion.matrix(). The tangent vectors of Se3 and Se2 put the
rotation part, in radians, last: [υ, ω] and [vx, vy, θ]. log is principal: its rotation angle is at most
\(\pi\) in magnitude. The Jacobians of So3 satisfy
\(\exp(\omega + \delta) \approx \exp(\omega) \exp(J_r \delta) = \exp(J_l \delta) \exp(\omega)\). A transform
trans_01 maps frame-1 coordinates into frame 0, and
relative_transformation() of trans_01 and trans_02 is trans_12;
NamedPose names the same transform dst_from_src.
Topic |
kornia |
scipy |
Sophus |
Eigen |
|---|---|---|---|---|
quaternion storage |
|
|
|
the |
composition |
|
|
|
|
SE(3) tangent |
|
|
|
|
rotation |
principal |
|
|
|
|
the short arc |
|
|
|
frame naming |
|
|
|
no frames |
Transformation matrices and homographies#
Transformation matrices are batched: homographies
(B, 3, 3), affine(B, 2, 3). Add the batch dim to a single matrix withM[None].kornia.geometry.transform.warp_perspective()takes the source→destination homography in pixel coordinates.kornia.geometry.transform.homography_warp()is different on every axis: it takes the destination→source homography, normalized to[-1, 1]by default (normalized_coordinates=True), and defaults toalign_corners=False.normalized_coordinates=Falsetakes the same destination→source homography in pixels, andnormalized_homography=Falsetakes a pixel source→destination homography instead and hands it towarp_perspective.homography_warp3d()andHomographyWarperread the homography the same way but have nonormalized_homographyswitch. For a pixel source→destination homography, asRANSACandfind_homography_dlt()return it, usewarp_perspective(), or in 3Dwarp_perspective3d()withalign_corners=True, because its defaultalign_corners=Falseresamples even an identity (#4503). Passed tohomography_warpunchanged, such a homography usually samples outside the source and the warp comes back mostly or entirely as zeros. To keephomography_warp, convert a pixel source→destination homography by normalizing it FIRST withkornia.geometry.conversions.normalize_homography()(which expects the forward src→dst homography) and inverting AFTER — inverting first with unswapped sizes is silently wrong whenever the source and destination sizes differ:
import torch
from kornia.geometry.conversions import normalize_homography
from kornia.geometry.transform import homography_warp, warp_perspective
img = torch.rand(1, 1, 8, 8)
M = torch.tensor([[[1.0, 0.0, 2.0], [0.0, 1.0, 1.0], [0.0, 0.0, 1.0]]]) # src->dst, pixels
a = warp_perspective(img, M, (16, 8)) # note: dst size differs from src
M_norm_inv = torch.inverse(normalize_homography(M, (8, 8), (16, 8))) # normalize, THEN invert
b = homography_warp(img, M_norm_inv, (16, 8), align_corners=True)
assert torch.allclose(a, b, atol=1e-5)
normalize_homography takes its own align_corners (default True),
and it must match the one you pass to the warp — the normalized [-1, 1]
coordinates mean different things under the two conventions. Above, both are
True; note that homography_warp alone would default to False.
align_corners defaults#
Defaults are not uniform across the library. When mixing Kornia warps
with torch.nn.functional.interpolate/grid_sample, pass
align_corners explicitly everywhere.
Function |
|
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The flag selects only how Kornia normalizes coordinates for grid_sample
(True: pixel centers 0 and size-1 sit at ±1; False: the outer
pixel edges do). Transforms you pass in are pixel-space either way, so a warp
that should be an identity is one under both settings, and warp_affine and
warp_perspective agree with each other:
import torch
from kornia.geometry.transform import get_perspective_transform, warp_affine, warp_perspective
img = torch.arange(16.0).view(1, 1, 4, 4)
pts = torch.tensor([[[0.0, 0.0], [3.0, 0.0], [3.0, 3.0], [0.0, 3.0]]])
M = get_perspective_transform(pts, pts) # identity
for align_corners in (True, False):
a = warp_affine(img, M[:, :2, :], (4, 4), align_corners=align_corners)
p = warp_perspective(img, M, (4, 4), align_corners=align_corners)
assert torch.allclose(a, img, atol=1e-4)
assert torch.allclose(p, img, atol=1e-4)
Where the two settings genuinely differ is out-of-bounds sampling, since ±1
covers a slightly different extent of the source image.
Warning
kornia.geometry.transform.remap() is the 2D exception left: it normalizes its
pixel maps with the align_corners=True convention regardless of the flag it passes
to grid_sample, so with its default (None, i.e. False) even an identity
pixel map resamples the image, by 11.25 on a 4x4 arange image. Pass
align_corners=True until this is fixed. Tracked in
#4504.
The 3-D warps are the other exception. normal_transform_pixel3d and
normalize_homography3d take no align_corners at all, so
kornia.geometry.transform.warp_affine3d() and
kornia.geometry.transform.warp_perspective3d() normalize with the corner-aligned
convention whatever flag they pass to grid_sample, and have the same mismatch at
align_corners=False: an identity warp_perspective3d changes a 4x4x4 arange
volume by up to 55.1 there, against roundoff at align_corners=True: exactly
0 in float32 on torch 2.14 and about 2e-6 on torch 2.5.1. Pass
align_corners=True to the 3-D warps until this is fixed. Tracked in
#4503.
Bounding boxes#
The
kornia.geometry.bboxmodule uses(B, 4, 2)corner format: clockwise from top-left,(x, y)per corner.Width/height are inclusive:
kornia.geometry.bbox.infer_bbox_shape()computeswidth = x_right - x_left + 1. A box with corners (1,1) and (2,2) has width 2, not 1:
import torch
from kornia.geometry.bbox import infer_bbox_shape
boxes = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]])
h, w = infer_bbox_shape(boxes)
assert (h.item(), w.item()) == (2.0, 2.0)
kornia.augmentation.container.AugmentationSequentialaccepts three box formats viadata_keys:"bbox"(4-corner),"bbox_xyxy", and"bbox_xywh". Keypoints are"keypoints",(B, N, 2)in(x, y).
Color#
Color-space conversions use channel axis -3 in (*, C, H, W). The color space determines
channel units; converted data is not generally a unit-range RGB image.
Space |
Channels |
Input encoding |
|---|---|---|
HSV and HLS |
Hue in radians; saturation and value or lightness in unit range |
Nonlinear RGB in unit range |
XYZ |
X, Y, Z |
Linear RGB; |
Lab and Luv |
L*, a*, b* or L*, u*, v*, with L* on the 0–100 scale |
Nonlinear sRGB, linearized internally; D65 / 2° reference white |
YCbCr |
Y, Cb, Cr; chroma is offset by 0.5 |
RGB in unit range |
YUV |
Y, U, V; chroma is signed |
RGB in unit range |
Use kornia.color.rgb_to_linear_rgb() and kornia.color.linear_rgb_to_rgb() to change
transfer encoding. kornia.color.lab_to_rgb() clips its final RGB output unless clip=False;
kornia.color.luv_to_rgb() does not clip its output. kornia.color.ycbcr_to_rgb()
clips its final RGB output to the unit range.
A result of these clips, of kornia.color.rgb_to_rgb255() and kornia.color.normals_to_rgb255(), and of the
clamps inside kornia.color.hls_to_rgb() and kornia.color.lab_to_rgb() (of a negative Z) exactly on a
bound has no unique derivative. They use the one-sided derivative from inside the range on every torch version, as the
intensity ops do (see Enhancement); plain torch.clamp gives 0 there from torch 2.14. A result
outside the range gets the bound and a zero gradient. A graph captured by torch.jit.trace or torch.export keeps
the plain clamp.
See the individual color conversion pages for RAW mosaic layouts, chroma subsampling, and known defects.
Enhancement#
kornia.enhance.adjust_brightness()adds its factor, whilekornia.enhance.adjust_brightness_accumulative()multiplies by it.kornia.enhance.adjust_contrast()multiplies pixel values; the mean-subtraction variant adjusts contrast around an image mean. torchvision and PIL brightness, contrast and saturation correspond to the_accumulative,_with_mean_subtractionand_with_gray_subtractionvariants.A result of these intensity ops exactly on
0or1has no unique derivative. These ops use the one-sided derivative from inside the range on every torch version; plaintorch.clampgives 0 there from torch 2.14. A result outside the range gets the bound and a zero gradient. A graph captured bytorch.jit.traceortorch.exportkeeps the plain clamp.kornia.enhance.adjust_hue()andkornia.enhance.adjust_hue_raw()take radians (torchvision’shue_factorisfactor / (2 * pi)); the raw hue and saturation helpers operate on HSV data.kornia.enhance.normalize()andkornia.enhance.denormalize()use channel axis 1 in(B, C, ...).kornia.enhance.normalize_min_max()takes(*, C, H, W)and rescales eachH x Wplane independently.kornia.enhance.integral_image()sums inclusively over the last two axes. The returned image has the input shape, without an extra zero border.kornia.enhance.ZCAWhiteningusesdimas the sample axis and flattens all other axes into features.unbiased=Trueselects theN - 1covariance denominator.
See the enhancement API for clipping, histogram ranges, and known defects.
Augmentations#
Most augmentations apply per sample with probability
pand default top=0.5:RandomRotation(degrees=30.0)leaves about half the batch unrotated.kornia.augmentation.RandomGrayscaledefaults to0.1andkornia.augmentation.RandomMosaicto0.7; every class exported fromkornia.augmentationwith a default below1states it on its first docstring line. These default top=1.0:CenterCrop,CenterCrop3D,ColorJiggle,ColorJitter,Denormalize,LongestMaxSize,Normalize,PatchMix,RandomAutoContrast,RandomBrightness,RandomContrast,RandomCrop,RandomCrop3D,RandomCutMixV2,RandomGamma,RandomHue,RandomJPEG,RandomMixUpV2,RandomResizedCrop,RandomSaturation,RandomSnow,ResizeandSmallestMaxSize.The crop, resize and mix classes (
RandomCrop,CenterCrop,RandomResizedCrop,Resize,LongestMaxSize,SmallestMaxSize,RandomCrop3D,CenterCrop3D,RandomMixUpV2,RandomCutMixV2,PatchMix) take theirpas one draw for the whole batch;Normalize,Denormalizeandkornia.augmentation.RandomDissolvingshare one draw across the batch, andsame_on_batch=Trueshares the draw for any class (see Randomness in augmentations below).torchvision’s
RandomRotation,RandomAffine,ElasticTransform,GaussianBlur,GaussianNoiseandRandomChannelPermutationalways apply: passp=1.0for that behaviour. The reverse holds forRandomAutoContrast, which defaults top=1.0while torchvision’sRandomAutocontrastdefaults top=0.5.Use one
kornia.augmentation.container.AugmentationSequentialcall for an image and its annotations. Geometric children that implement a data key’s handler share their recorded parameters across the inputs; a transform matrix alone does not mean every data key is supported..inverse()restores keypoints to numerical precision when every geometric step is invertible. The 3D geometric augmentations raise; intensity and non-rigid children are skipped, so their effect stays. Tensor box outputs are axis-aligned enclosures, so a rotation round trip does not restore a box.Non-rigid children cannot move coordinate annotations, so a pipeline that contains
kornia.augmentation.RandomElasticTransform,kornia.augmentation.RandomThinPlateSplineorkornia.augmentation.RandomFisheyeraisesNotImplementedErroron a keypoint or box data key, even atp=0. Elastic warps masks; the other two raise on masks (#4420).Intensity augmentations leave masks unchanged, except
kornia.augmentation.RandomErasing, which erases the same rectangle in the mask and fills it with0(background) whatevervaluefills the image.Geometric children normally resample masks with nearest interpolation, so labels are not blended, but padding can introduce its fill value. The container processes a floating mask in the dtype of the image it is working on (the most recent image argument before the mask, or the call’s first image when the mask comes first) and returns it in the mask’s own dtype. Integer masks use at least float32, or float64 with a float64 image, so half-precision images do not round their class labels. Labels not exactly representable in that working dtype raise
RuntimeError; remap them to smaller integers or use a float64 image where supported. On accelerators the asynchronous assertion may report at the next synchronization; MPS before torch 2.13 checks on the host. A direct geometrictransform_maskscall requires a floating tensor.A mask list has one tensor per image sample, in sample order. Entries may have different channel counts and use their sample’s gate, parameters and matrix in forward, replay and inverse, including nested image sequences and auto-augment policies. Video, mix and 3D children, and a geometric
PatchSequential, do not support mask lists and raiseNotImplementedError. Each entry is(H, W),(C, H, W)or(1, C, H, W)with the image’s spatial size. Invalid lengths or shapes raiseValueError. Use separatemaskkeys for multiple full-batch masks.Boxes use the inclusive
xyxy_plusconvention ofkornia.geometry.boxes.Boxes(see Bounding boxes above). Flips use integer pixel centres:x' = W - 1 - x.Nested
AugmentationSequentialchildren contribute matrices from the current call under their own matrix mode. PlainImageSequentialchildren contribute their geometric operations insilentmode, including repeated members of a sampled sequence.rigidstill rejects a plain image sequence, andskiprecords no matrix.Dictionary keys match a data-key name exactly or before an
_/-suffix, the longest match winning. Unrecognized keys are returned unchanged as metadata, and the caller’s dictionary is not modified.A positive
degreesturns the displayed image counter-clockwise withkornia.augmentation.RandomRotation, matchingkornia.geometry.transform.rotate(), and clockwise withkornia.augmentation.RandomAffine(#4408).A 2D intensity augmentation whose arithmetic assumes unit-range images clamps its input into
[0, 1]before operating, and clamps its output too. This includes colour adjustments, illumination, snow, JPEG and histogram equalization. Samples skipped by the probability gate retain their original values. Range-independent operations, such as blurs, noise, channel operations, erasing, grayscale, inversion,NormalizeandDenormalize, do not clamp their input.RandomAutoContrastrescales each channel’s full input range instead of clipping it.RandomBrightnessandRandomContrastpreserve raw arithmetic withclip_output=False. See each class’s Convention block. The functionalkornia.enhance.equalizeandequalize_claheAPIs retain their strict range checks; their augmentation wrappers clamp first.
import torch
import kornia.augmentation as K
aug = K.AugmentationSequential(
K.RandomAffine(degrees=30.0, p=1.0),
data_keys=["input", "mask", "keypoints"],
)
image = torch.rand(1, 3, 64, 64)
mask = (torch.rand(1, 1, 64, 64) > 0.5).float()
kpts = torch.tensor([[[16.0, 16.0], [48.0, 32.0]]])
img_out, mask_out, kpts_out = aug(image, mask, kpts)
img_back, mask_back, kpts_back = aug.inverse(img_out, mask_out, kpts_out)
assert (kpts_back - kpts).abs().max() < 1e-3
Randomness in augmentations#
Parameters are drawn from torch’s global generator, on the CPU by default whatever the image device, so
torch.manual_seedreproduces a run for the same configuration, inputs, device and dtype. There is no per-instancegenerator=: standard augmentation forwards warn and ignore unknown keywords,generator=included, while mix forwards reject them (#4427). Under atorch.utils.data.DataLoader, aworker_init_fnthat reseeds every worker to the same value duplicates the augmentations across workers (see Randomness in multi-process data loading)..to(...)andset_rng_device_and_dtypemove the gate and ask the parameter generators to rebuild their samplers, but some generators keep CPU tensors or ignore the requested precision, and returned parameters need not follow: numeric-rangeRandomAffinereturns CPUfloat32parameters whilebatch_probis on the accelerator. Do not infer where draws ran from_params(#4426).To replay a transform, pass its recorded
_paramsasparams=. The standard 2D forward uses that dictionary as given, without a copy, and fills a missingbatch_probin place with an all-true gate; mix augmentations require the key. The recorded parameters capture every draw except the VAE latent thatkornia.augmentation.RandomDissolvingsamples while it is applied.A kornia release can change how many draws an augmentation consumes, so a seeded pipeline is not bit-stable across kornia versions.
same_on_batch=Trueshares the per-sample gate and the sampled factors across the batch; it does not make mix pairing indices equal. The colour order ofColorJiggleandColorJitteris shared across the batch regardless. OnAugmentationSequential,same_on_batch=Nonekeeps each child’s setting, andTrueorFalseoverwrites it.Every augmentation honours
p_batchas an attribute, and onlyRandomHorizontalFlip,RandomVerticalFlip,RandomTransplantationandRandomTransplantation3Dtake it in the constructor; whether a constructor’spsets the per-sample or the whole-batch gate depends on the concrete class. A sample the gate skips comes back with its input values, its values cannot make the call raise, and where they are finite its gradient is the identity. Belowp=1the transform still runs on the whole batch before the gate selects; classes whose transform checks input values or has an unbounded derivative (RandomEqualize,RandomEqualize3D,RandomClahe,RandomGamma) run it on the value 0.5 for skipped samples. An augmentation that changes the sample shape, such asRandomCroporResize, still raisesValueErrorwhen the gate mixes applied and skipped samples (#4497).
Serializing an augmentation#
state_dict()is not a complete record of an augmentation’s configuration: rebuild the augmentation from its constructor arguments. Numeric ranges create no trainable parameters, and with numeric ranges the 3D and mix augmentations have an emptystate_dict().nn.Parameterranges (RandomRotationandRandomAffineamong others) are registered and receive gradients. Some numeric ranges are copied into_param_generator.*buffers, and loading one that differs builds the samplers again from the loaded range. The constructor’s domain check applies to it where the class passes one to its generator; a range it refuses raises the constructor’sValueErrorand leaves the buffer and the samplers as they were. A checkpoint that holds the same range changes nothing. The auto policies’_probabilityentries are still not read back (#4428).A learnable range is read again before each draw, so an optimizer step, an in-place update,
load_state_dictandAveragedModel.update_parametersall reach the next draw, for a(2,)range and for a 0-d half-width alike. Its value is checked when the augmentation is built, and otherwise only by the classes named below: to read it on every call would wait for the GPU and break atorch.compilegraph, so a range that training takes out of its domain (a negative half-width, say) is drawn from as it is. Keep it inside by clamping it after the optimizer step, or withtorch.nn.utils.parametrize.register_parametrizationonaug._param_generator; PyTorch then serializes that generator throughstate_dict()only, andcopy.deepcopyandpickleof it raise. There are two limits.RandomErasing,RandomResizedCrop,RandomPosterize,RandomRotation90andRandomCutMixV2decide things from the values of their range when they build their samplers and pass it no gradient, so an update reaches them throughload_state_dictand copies only. Those builds check the range, soRandomErasing,RandomPosterize,RandomRotation90andRandomCutMixV2raise the constructor’sValueErrorwhen a range outside their domain is loaded, or when the module is moved (.to(torch.float64), say) after an in-place update took it out. A range on an accelerator in an augmentation left on the CPU (or the reverse) is copied to the generator’s device only after an in-place update or a change of grad mode (a forward undertorch.no_grad()after a training one, or the reverse), and each copy waits for the GPU once.pickleandcopy.deepcopykeep the configuration and the recorded_params, which replay on the same input. This includes thekornia.augmentation.autopolicies: a policy pickles when every operation wrapper in it does, and a wrapper does when its magnitude mapping is picklable (the built-in mappings are). What lazily computed matrices retain is described in Base Classes.A copy made with
copy.deepcopy,pickleortorch.saveof an augmentation or container with annn.Parameterrange owns a copy of that parameter, and its gradients reach that copy rather than the original. It draws from the current value of its own parameter. The_paramsit inherits from the last call keep their values, detached.
Morphology#
kornia.morphology.dilation() reflects the kernel and kornia.morphology.erosion() does not; origin
is a [row, col] index and border_type takes torch’s pad names. Below, K is a kernel of shape
\((k_h, k_w)\), and each call row assumes the matching border from the border rows:
Behaviour |
kornia |
|
scikit-image |
OpenCV |
|---|---|---|---|---|
|
yes |
yes |
no |
no |
kornia call equal to their dilation by |
(reference) |
|
|
|
|
rows 1-2, cols 2-3 |
rows 1-2, cols 2-3 |
rows 1-2, cols 2-3 |
rows 2-3, cols 3-4 |
kornia call equal to their erosion by |
(reference) |
|
|
|
kornia call equal to their opening / closing by |
(reference) |
|
|
|
origin/anchor semantics |
|
offset from |
not exposed |
|
default border |
|
|
|
ignore outside |
kornia’s |
|
|
|
default border |
torch’s |
|
|
|
|
torch’s |
|
|
|
|
torch’s |
|
|
|
no equivalent: |
The equivalences cover empty geodesic windows too: scipy, scikit-image and kornia all return -inf from
such a window in a dilation and +inf in an erosion, whatever the data range.
Filtering#
kornia.filters follows torch’s vocabulary: its kernels are correlated by default, border_type
takes the torch.nn.functional.pad() mode names, and an even kernel is anchored where
F.conv2d(padding='same') anchors it. The correlation matches cv2.filter2D and scipy.ndimage.correlate; the
border names and the even-kernel anchor do not. filter2d(),
filter2d_separable(), filter3d(), fft_conv(),
box_blur(), gaussian_blur2d(), laplacian(),
motion_blur(), bilateral_blur(),
joint_bilateral_blur(), guided_blur(), canny(),
unsharp_mask(), median_blur(), spatial_gradient(),
spatial_gradient3d(), sobel() and their modules filter an integer or bool
image in float32 and return
float32 on its own scale, neither rescaled to \([0, 1]\) nor rounded and clamped to its dtype, where
cv2.filter2D(img, -1, k), cv2.GaussianBlur and cv2.blur return a uint8 image rounded and saturated to
uint8; a floating image keeps its dtype. guided_blur() returns the promoted dtype of its
guidance and input, an integer one counting as float32. The blur pools are network layers and expect a
floating input: they raise a TypeCheckError (a TypeError) for a non-floating
input instead of promoting it.
filter2d(),filter3d()andfft_conv()correlate by default, ascv2.filter2Dandscipy.ndimage.correlatedo;behaviour='conv'flips the kernel first, asscipy.ndimage.convolvedoes.correlate2d()andconvolve2d()arefilter2d()withbehaviourfixed to'corr'and'conv';correlate3d()andconvolve3d()are the same forfilter3d().filter2d_separable()takeskernel_x(alongW) beforekernel_y, the order ofcv2.sepFilter2D(src, ddepth, kernelX, kernelY).
The border modes, shown padding a b c d by two samples on each side. kornia.morphology uses
the same names for its non-geodesic borders:
kornia |
pads |
|
OpenCV |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
no kornia mode |
|
|
|
Filters extend reflect and circular borders to any positive axis length, even when a kernel reaches beyond
one period of the input. Reflection has period 2 * (n - 1) for an axis of length n > 1; a singleton axis
repeats its pixel. Circular padding has period n. Calls accepted by F.pad retain that native path.
An even kernel has no centre tap. The filters anchor a kernel k taps long at (k - 1) // 2, the anchor of
F.conv2d(padding='same'). OpenCV and scipy anchor it at k // 2 by default, and so does the default origin of
erosion() (see Morphology), so along every even axis a correlated output sits one pixel
before theirs; behaviour='conv' needs no shift (below). An odd kernel is anchored at its centre by all of them.
For a kernel K of shape (kh, kw), with the border mapped by the table above:
filter2d(x, K[None])equalsscipy.ndimage.correlate(x, K, origin=o)witho = -1on each even axis and0on each odd one, andcv2.filter2D(x, -1, K, anchor=((kw - 1) // 2, (kh - 1) // 2)).filter2d(x, K[None], behaviour='conv')equalsscipy.ndimage.convolve(x, K)at scipy’s default origin, even for an evenK.
The kernel builders against their references:
get_gaussian_kernel1d()samples the Gaussian: for an oddkandsigma > 0it equalscv2.getGaussianKernel(k, sigma)and the weightsscipy.ndimage.gaussian_filter1dapplies withradius=k // 2.get_gaussian_erf_kernel1d()is the pixel-integrated Gaussian andget_gaussian_discrete_kernel1d()is Lindeberg’s discrete Gaussian,scipy.special.ive(abs(n), sigma**2)normalized.get_hanning_kernel1d()is the symmetric window ofnumpy.hanning(k),scipy.signal.windows.hann(k)andtorch.hann_window(k, periodic=False); torch’s default periodic window differs.get_spatial_gradient_kernel2d()with('sobel', 1)stacks the outer products of OpenCV’sgetDerivKernels(1, 0, 3)andgetDerivKernels(0, 1, 3), and answers 8 to a unit slope, ascv2.Sobelandscipy.ndimage.sobeldo; scikit-image’ssobel_handsobel_vanswer 2.get_laplacian_kernel2d()of size 3 is the 8-neighbour stencil and estimates \(3 \nabla^2\), wherescipy.ndimage.laplaceandcv2.Laplacian(ksize=1)return \(\nabla^2\),cv2.Laplacian(ksize=3)\(4 \nabla^2\) andskimage.filters.laplace\(-\nabla^2\).A builder raises for an integer or bool
dtypethat cannot hold its taps instead of truncating or wrapping them. The box, Gaussian and 3-D difference kernels have fractional taps, so they raise for every integerdtype, ascv2.getGaussianKernelaccepts onlyCV_32FandCV_64F. The Laplacian kernels accept a signed integerdtypewide enough for their negative centre, and raise for uint8, bool and a narrower one (#5155).
The derivative filters apply those kernels at different scales, and canny() thresholds the raw
one:
spatial_gradient()andsobel()use normalized first-order gradients by default: an interior axis-aligned unit slope gives 1 in the correspondingspatial_gradientchannel, andsobelreturns \(\sqrt{1 + \epsilon}\).normalized=Falsereturns the raw Sobel response above.spatial_gradient()always replicates the border, socv2.Sobel(x, cv2.CV_64F, 1, 0, borderType=cv2.BORDER_REPLICATE)andscipy.ndimage.sobel(x, axis=-1, mode='nearest')equal channel 0 ofspatial_gradient(x, normalized=False); OpenCV’s defaultBORDER_REFLECT_101differs on the outermost rows and columns.skimage.filters.sobel(x, mode='nearest')equalssqrt(2) * sobel(x, eps=0).laplacian()is normalized by default too, but by the stencil’s absolute sum, 16 for size 3:laplacian(x, 3)estimates \(3 \nabla^2 / 16\), andnormalized=Falsethe \(3 \nabla^2\) above.canny()compares its thresholds with the unnormalized Sobel magnitude of the blurred image, about eight times whatsobel()returns by default, up to theepsinside the square root. For a single-channel grayscale uint8 imageimg,cv2.Canny(img, t1, t2, L2gradient=True)corresponds tocanny(x, t1 / 255, t2 / 255, kernel_size=1, eps=0)for edge-map comparison, withxthe float32 or float64 tensorimg / 255: the thresholds scale with the image andkernel_size=1skips the Gaussian blur that OpenCV does not apply. OpenCV’s default L1 magnitude \(|g_x| + |g_y|\) has no kornia counterpart.canny()resolves ties along the gradient as OpenCV does, but floating-point rounding ofimg / 255, the gradient and threshold comparisons can still change a near-tie or near-threshold decision. With the defaulteps=1e-6, the square root raises the magnitude above itseps=0value, when retained by the dtype’s precision: it can promote a pixel even when the threshold is slightly above the raw magnitude, without an exact tie. Color images need separate preprocessing: Kornia converts RGB to grayscale, while OpenCV’s color Canny selects the channel with the strongest gradient, so this correspondence does not apply directly to a 3-channel image.skimage.feature.cannythresholds the same unnormalized magnitude of a floating-point image and has the same defaults, 0.1 and 0.2, so thresholds carry over; its Gaussian blur and its interpolating suppression differ fromcanny()’s, so the edge maps do not match.
The blurs give sizes and standard deviations rows first, as torch orders (H, W): kernel_size is
(kh, kw) and sigma is \((\sigma_y, \sigma_x)\) in gaussian_blur2d(),
box_blur(), median_blur() and the filters built on them. OpenCV passes
both pairs x first, so swap them when porting; scipy uses kornia’s order. For odd kh and kw, with the border
mapped by the table above (OpenCV accepts BORDER_WRAP in these calls only for some dtypes and sizes):
gaussian_blur2d(x, (kh, kw), (sy, sx))equalscv2.GaussianBlur(x, (kw, kh), sigmaX=sx, sigmaY=sy)andscipy.ndimage.gaussian_filter(x, sigma=(sy, sx), radius=(kh // 2, kw // 2)).box_blur(x, (kh, kw))equalscv2.blur(x, (kw, kh))andscipy.ndimage.uniform_filter(x, size=(kh, kw)).
The edge-preserving filters, the sharpening and the blur pools against their references:
bilateral_blur()with'l1'uses the colour distance ofcv2.bilateralFilter, but weighs the wholekernel_sizerectangle where OpenCV weighs only the disc of radiusd // 2, so the two differ even forkernel_size=(d, d).guided_blur(guide, src, 2 * r + 1, eps)equalscv2.ximgproc.guidedFilter(guide, src, r, eps)away from the border:epsis the same quantity, but OpenCV pads withBORDER_REFLECT, which has no kornia mode.joint_bilateral_blur()takes its guide second, wherecv2.ximgproc.jointBilateralFilter(joint, src, ...)takes it first.unsharp_mask(x, (k, k), (r, r))withk = 2 * int(4 * r + 0.5) + 1, the window scikit-image truncates its Gaussian to, equalsskimage.filters.unsharp_mask(x, radius=r, amount=1, preserve_range=True)away from the border. scikit-image pads with scipy’sreflect, which has no kornia mode, and with its defaultpreserve_range=Falseit clips the result, whichunsharp_mask()never does.blur_pool2d(x, k, s)equals the antialiased-cnnsBlurPool(channels, pad_type='zero', filt_size=k, stride=s), which definesfilt_sizeup to 7. The reference’s defaultpad_type='reflect'keeps a constant map constant whereblur_pool2d()zero-pads and darkens its border.blur_pool2d(x, 5, 2)blurs with the 5 x 5 binomial kernel ofpyrdown()but samples differently: it zero-pads and keeps every second pixel from index 0, \(\lceil H / 2 \rceil\) rows, wherepyrdownreflects the border and interpolates between pixels, \(\lfloor H / 2 \rfloor\) rows.
Losses and metrics#
kornia.losses and kornia.metrics take the prediction first and the target second,
as torch’s losses do. The order does not change the value of the symmetric functions, among them SSIM, MS-SSIM, PSNR,
the robust losses and the Jensen-Shannon divergence, but it does for others: kl_div_loss_2d() takes
pred first and returns \(\mathrm{KL}(\text{target} \,\|\, \text{pred})\), and
inverse_depth_smoothness_loss() takes the inverse depth it penalises first and the image that
weights it second.
What the families take:
ssim(),ssim3d(),psnr(), the SSIM losses andMS_SSIMLosscompare images with values in[0, L], whereLis the data range:max_valeverywhere except inMS_SSIMLoss, which calls itdata_rangeas scikit-image, pytorch-msssim and torchmetrics do.Lsets the SSIM constants \(C_1 = (0.01 L)^2\) and \(C_2 = (0.03 L)^2\) and the PSNR peak \(\text{MAX}_I\). Pixel values are never rescaled, so images in[0, 255]needmax_val=255.0ordata_range=255.0. The default is1.0(psnr,psnr_lossandPSNRLosshave none), where pytorch-msssim defaults to 255.The robust losses take two tensors of the same, arbitrary shape; the residual is in the units of the data.
total_variation()takes one image(*, H, W).kl_div_loss_2d()andjs_div_loss_2d()take probabilities: every(b, n)slice of a(B, N, H, W)input is a distribution overH x W.The losses on the segmentation page take raw logits (see Dense-prediction losses) and
HausdorffERLosstakes probabilities; the mutual-information losses take intensities of any range, which they normalise per signal: per channel of each sample for an image batch.
Where a function takes reduction, the names are torch’s: 'none', 'mean' and 'sum'. What is averaged or
added and the default differ between families, so each Convention block states both; the table lists the defaults. A
string outside a function’s vocabulary raises, BaseError from the robust losses and
total_variation() and NotImplementedError from the others.
functions |
default |
default output |
|---|---|---|
|
|
one value per element, in the shape of the prediction |
|
|
a scalar |
|
one value per leading index, |
|
|
no |
a scalar |
|
no |
one value per signal: |
no |
stated by each function |
The modules take the reduction of their functions, except TotalVariation, which has none
and always sums.
Porting from other libraries:
ssim(x, y, 11, max_val=L, eps=0.0, padding='valid').mean()for one image matches scikit-image’sstructural_similarity(x, y, gaussian_weights=True, sigma=1.5, use_sample_covariance=False, data_range=L, channel_axis=-1)on the(H, W, C)arrays up to floating-point differences, and over a batch it matches pytorch-msssim’sssim(x, y, data_range=L). Seteps=0.0to remove Kornia’s added denominator term when matching these implementations. The defaulteps=1e-12can matter: identical black images score about0.99998889atL=1.0,0.9atL=0.1and0.00089919atL=0.01, where the references give 1. scikit-image’s defaults, a 7 x 7 uniform window with the sample covariance, give another value. torchmetrics’structural_similarity_index_measure(x, y, data_range=L)averages over a reflected'same'map instead; it has no added denominator epsilon and clamps negative variance estimates from roundoff to zero.ssim_loss()is the structural dissimilarity(1 - SSIM) / 2, clamped to[0, 1]. The1 - SSIMloss is twice that:1 - ssim(x, y, w).mean()equals2 * ssim_loss(x, y, w)wherever the clamp does not act.ssim3d_loss()uses the same clamped DSSIM formula for volumes.MS_SSIMLossfilters with one Gaussian per entry ofsigmasat full resolution, the approximation of Zhao et al.; pytorch-msssim’sms_ssimand torchmetrics’multiscale_structural_similarity_index_measuredownsample through a dyadic pyramid, so1 - ms_ssim(x, y)is notMS_SSIMLoss(alpha=1.0, compensation=1.0)(x, y).psnr()of a batch pools one MSE over all its images: it equals scikit-image’speak_signal_noise_ratio(x, y, data_range=L)on the whole batch array and torchmetrics’peak_signal_noise_ratio(x, y, data_range=L)at its defaultdim=None. The mean of per-image PSNRs is scikit-image’s value averaged over the images, or torchmetrics’ withdim=(1, 2, 3).general.lossfun(x - y, alpha, scale)of Barron’srobust_loss_pytorchequals the kornia robust loss ofx / scaleandy / scalewith the samealpha: 1 forcharbonnier_loss(), 0 forcauchy_loss(), -2 forgeman_mcclure_loss()and-infforwelsch_loss().torchmetrics’
total_variation(img, reduction='none')equalstotal_variation(img).sum(-1)for a(B, C, H, W)batch. Its'mean'averages those per-image sums over the batch, where the'mean'oftotal_variation()averages each difference term over its own count.For strictly positive probabilities,
kl_div_loss_2d(pred, target)equalsF.kl_div(pred.log(), target, reduction='batchmean')on the(B * N, H * W)reshape; torch’sreduction='mean'divides by every element instead. Kornia defines zero-target cells with finite nonnegative predictions as contributing zero, including shared zero cells, where the raw PyTorch recipe returns NaN. Replace both arguments with 1 in these cells before taking the logarithm to reproduce Kornia’s handling. torchmetrics’kl_divergence(target, pred)on the reshape matches Kornia’s value, including shared zeros. For scipy, reshapepredandtargetto NumPy arrayspandqof shape(B, N, H * W). Thenscipy.stats.entropy(q, p, axis=-1).mean()matches the default KL loss, and(scipy.spatial.distance.jensenshannon(p, q, axis=-1) ** 2).mean()matchesjs_div_loss_2d(), using scipy’s default natural logarithm. Without the finalmean(), each returns(B, N), matchingreduction='none'. SciPy normalises its inputs, so these mappings require each spatial slice to sum to one.inverse_depth_smoothness_loss()does not normalise the inverse depth, where Monodepth2 divides the disparity by its mean plus1e-7before its smoothness term: passidepth / (idepth.mean((2, 3), keepdim=True) + 1e-7)to port it, keeping zero inverse depth finite.
Dense-prediction losses#
The losses on the segmentation page take raw logits, not probabilities;
focal_loss() documents the multi-class input, with the classes on axis 1 and an integer label map
as the target.
Class 0 is the background wherever a loss or a metric singles one class out:
focal_loss() weights class 0 by 1 - alpha and classes 1 to C - 1 by alpha, and
mean_average_precision() never scores class 0, which its n_classes still counts. Keep the
background at label 0 when porting a label map: moving it changes both results. focal_loss with alpha=None,
dice_loss(), tversky_loss(), lovasz_softmax_loss() and
HausdorffERLoss treat class 0 like every other class.
With alpha=None and gamma=0, the target slice of focal_loss() is the cross entropy, but
its 'mean' is not that of cross_entropy(). It divides the sum by every element of the
(B, C, *) output, C times the pixel count, ignored pixels included, and it does not normalise weight, where
cross_entropy divides by the summed weights of the target classes of the non-ignored pixels. To port
F.cross_entropy(pred, target, weight=w, ignore_index=i), divide
focal_loss(pred, target, alpha=None, gamma=0.0, reduction='sum', weight=w, ignore_index=i) by
w[target[target != i]].sum(), or by the number of non-ignored pixels when there is no w.
The other dense-prediction losses against their references:
binary_focal_loss_with_logits()with its defaults,alpha=0.25on the positive term,gamma=2andreduction='none', equalstorchvision.ops.sigmoid_focal_losson targets of 0 and 1. On a fractional targettthey differ: kornia weights its positive and negative focal terms bytand1 - t, torchvision appliesalpha_t * (1 - p_t) ** gammato the whole binary cross entropy. Itspos_weightof shape(C,)runs along dim 1:binary_focal_loss_with_logits(pred, target, alpha=None, gamma=0.0, pos_weight=pw)equalsF.binary_cross_entropy_with_logits(pred, target, pos_weight=pw.view(C, 1, 1), reduction='none')on(B, C, H, W), where torch broadcasts a(C,)pos_weightalong the last axis.The Lovász losses score each image on its own, as the reference implementation of Berman et al. (
bermanmaxim/LovaszSoftmax) does withper_image=True:lovasz_hinge_loss()is itslovasz_hinge(pred[:, 0], target, per_image=True), the reference default, andlovasz_softmax_loss()islovasz_softmax(pred.softmax(1), target, classes='all', per_image=True). Thelovasz_softmaxdefaults,classes='present'andper_image=False, score only the classes present and flatten the batch into one image, which gives another value.
A class absent from the target has no overlap to score, and the per-class functions treat it differently:
mean_iou()returns IoU 1 for a class absent from both the target and the prediction, through itseps, and leaves the averaging over classes to the caller: drop the classes that occur in neither map before averaging its(B, K)output. scikit-learn’sjaccard_scoreleaves such a class out unlesslabelsnames it, and then scores it 0, or 1 withzero_division=1.0.dice_loss(average='macro')andtversky_loss()leave it out of the sample’s mean, whether it is predicted or not.mean_average_precision()pools the images and leaves out a class without a ground-truth object in any of them, detected or not; its entry in the per-class dictionary is-1.
Task metrics#
confusion_matrix() puts the target class on the rows and the predicted class on the columns, and
mean_iou() reads its per-class IoU from that matrix.
The task metrics differ in what they return, in what they pool and in their scale: percent, fraction, pixels or degrees. Each Convention block states its own, and the table collects them. For the background class 0 and for a class absent from a sample, see Dense-prediction losses.
functions |
output |
pooled over |
scale |
|---|---|---|---|
a list of 0-d tensors, one per entry of |
the batch |
percent, |
|
|
nothing: one matrix per sample |
counts |
|
|
nothing: one IoU per sample and class |
fraction, |
|
|
nothing: one IoU per pair of boxes |
fraction, |
|
a 0-d tensor and a |
the detections of all images, per class, then a mean over the classes with objects |
fraction, |
|
0-d, or |
every position of every sample |
the units of the flow |
|
|
0-d, or |
every valid pixel of every image |
pixels |
0-d, or |
every valid pixel of every image |
fraction, |
|
|
nothing: one angle per pair |
degrees |
|
a dict of |
nothing: one error per pose |
degrees |
|
|
nothing: one distance per sample |
the units of the translations |
|
a |
all errors |
percent, |
|
|
every update, weighted by its |
the scale of the values passed |
Porting the task metrics from other libraries:
scikit-learn takes the target first and kornia the prediction; both put the target on the rows:
confusion_matrix(pred, target, K)[b]equalssklearn.metrics.confusion_matrix(target[b].ravel(), pred[b].ravel(), labels=range(K)).normalized=Trueisnormalize='true'up to the1e-6added to every row sum, not the per-predictionnormalize='pred'. Without tied scores,accuracy(pred, target, topk=(k,))[0]is 100 timestop_k_accuracy_score(target, pred, k=k, labels=range(C))for more than two classes, and 100 timesaccuracy_score(target, pred.argmax(1))fork=1.The IoU of a whole batch or dataset, which
jaccard_score(target.ravel(), pred.ravel(), labels=range(K), average=None)and torchmetrics’MulticlassJaccardIndex(num_classes=K, average='none')report, is the IoU of the summed matrixconfusion_matrix(pred, target, K).sum(0), not the mean ofmean_iou()over the batch.mean_average_precision()matches a detection to an object only when their IoU is strictly greater thanthreshold, asvoc_evalof py-faster-rcnn does, and computes that IoU on exclusive boxes, asmean_iou_bbox()does, where py-faster-rcnn and the PASCAL VOC devkit add 1 to every box width and height. The devkit (VOCevaldet.m) matches atIoU >= 0.5, so a detection whose IoU equals the threshold is a false positive in kornia and a true positive there.COCO’s evaluation, run as torchmetrics’
MeanAveragePrecision(iou_thresholds=[0.5], rec_thresholds=[i / 10 for i in range(11)], backend='pycocotools'), pools the detections of all images, interpolates at kornia’s 11 recall levels and leaves a class without objects out of the mean, with AP-1where it lists one, as kornia does. It reproduces kornia’s AP except in five cases: it matches atIoU >= 0.5; it gives a detection whose best object is already matched to the best object still free; it scores class 0 like every other class; it scores only the 100 highest-scoring detections of a class in each image; and it ranks detections of equal score by image, then in input order, where kornia leaves their order totorch.sort.torchvision’s RAFT models return a list of
(B, 2, H, W)flows, channel first, whereaepe()takes(B, H, W, 2). The endpoint error of RAFT’s training code,((pred - gt) ** 2).sum(1).sqrt()on channel-first flows (sum(0)on one flow in its evaluation code), equalsaepe(pred.permute(0, 2, 3, 1), gt.permute(0, 2, 3, 1), reduction='none'). Its mean is the default'mean'where every pixel is valid, as in RAFT’s Chairs and Sintel evaluation; RAFT’s training metrics and its KITTI evaluation average only the valid pixels, KITTI image by image, so take those means of the'none'map.kitti_d1_error()applies the outlier rule of the KITTI 2015 devkit (evaluate_scene_flow.cpp) and pools like it: the devkit adds up outliers and valid pixels over all images before dividing, so its value is not the mean of per-image D1. The devkit also reads a ground-truth disparity of 0 as invalid and scores its own interpolated version of the estimate: pass a dense prediction andvalid_mask=target > 0to reproduce its number.SuperGlue’s
pose_aucand thecal_error_aucof glue-factory, the evaluation code of LightGlue, return the pose AUC as a fraction, glue-factory’s rounded to four decimals. Both equalauc_from_errors()divided by 100 for errors without NaN: the references count a NaN as a failure, kornia propagates it. SuperGlue’smatch_pairs.pyprints 100 times that fraction, a percentage like kornia’s; glue-factory reports the fraction itself. glue-factory’s pose error, the larger of the rotation angle and the folded translation angle, is the"max_err"ofpose_errors()with the defaultfold_translation=True. For a zero ground-truth translation glue-factory reads a translation error of 90 degrees, wherepose_errors()returns NaN.
Two-view geometry#
The two-view estimators take the first image’s points first and follow OpenCV’s order:
find_fundamental() returns an F with \(x_2^\top F x_1 = 0\) in image
coordinates and find_essential() an E with \(x_2^\top E x_1 = 0\) in
normalised camera coordinates, and find_homography_dlt() and
RANSAC with model_type="homography" return an H that maps points1 to
points2. Extrinsics are world-to-camera, as in Camera and world conventions across the ecosystem. Side by side:
Topic |
kornia |
OpenCV |
|---|---|---|
fundamental matrix |
|
|
essential matrix |
|
|
homography |
|
|
pose from |
|
|
projection matrix |
|
|
triangulation |
|
|
epipolar lines |
|
|
Sampson distance |
|
|
RANSAC threshold |
|
|
polynomial roots |
|
|
Local features#
The learned models in kornia.feature that take a pretrained flag (HardNet, HardNet8, HyNet,
SOSNet, TFeat, OriNet, LAFAffNetShapeEstimator, KeyNet, KeyNetDetector, DeFMO,
SOLD2, SOLD2_detector) default to their pretrained weights, downloaded on first use. KeyNetDetector puts
only its KeyNet network in evaluation mode: the detector itself stays in training mode, and an ori_module or
aff_module you pass keeps its own mode. DISK, DeDoDe, ALIKED, XFeat and CLIDD build their
learned weights at random in their constructor and load them with from_pretrained. DeDoDe with its default G
descriptor also downloads a frozen, pretrained DINOv2 backbone in its constructor, and DeDoDe.detect and
describe switch the model to evaluation mode themselves. LoFTR(pretrained=None) and
LightGlue(features=None) are random. Until .eval() is called, a random LoFTR runs its supervised training
branch, which raises without ground-truth matches. See Pretrained models for the shared mode rule.
A local affine frame (LAF) describes a keypoint by a 2 x 3 matrix [A | c], and a set of them is a
(B, N, 2, 3) tensor. The centre c = (x, y) is in the pixel frame of
Coordinates and sizes, with pixel centres at integers: the centre of a 5-pixel axis is
2, not 2.5. A maps the patch frame onto the image, in pixels: its first column is the image of the patch’s
x axis and its second column that of the patch’s y axis. The Convention blocks of
laf_from_center_scale_ori() and extract_patches_from_pyramid() give the
full rules.
The scale is \(\sqrt{|\det A|}\) and the orientation is
atan2(a12, a11)in degrees. For a LAF of positive determinant, a positive orientation turns the patch’s x axis counter-clockwise on screen, with image y pointing down: with an orientation of90, the+xside of the patch shows what lies above the centre. For a mirrored LAF, of negative determinant, it turns clockwise, and90puts the+xside below the centre.The region of a LAF is the ellipse
c + A uover the unit vectorsu, and aPS x PSpatch covers the squarec + A [-1, 1]^2: patch row 0 is on the patch’s-yside, the top for an upright LAF, and the columns run along the patch’s x axis.normalize_laf()divides the centre bymax(W - 1, 1)andmax(H - 1, 1)andAby the smaller of the two; its Convention block covers moving a LAF to an image of another size.kornia’s LAF detectors pad unused slots with an all-zero LAF and a zero response, so that a batch is one tensor.
laf_is_filled()is true for detections; index LAFs, responses and descriptors with it to drop padding before matching.The
match_*functions return(dists, idxs), one row per match; a lowerdistsis a better match. See the Convention block ofmatch_nn()for each matcher’s distance definition.idxsholds(index in desc1, index in desc2)for unbatched matchers.match_smnn_batched()prepends the batch index:(batch_index, index in desc1, index in desc2).LightGlueMatcherreturns a score in place ofdists; a higher score is a better match.
OpenCV keypoints and SIFT descriptors convert as follows:
Topic |
kornia |
OpenCV |
|---|---|---|
centre |
|
|
orientation |
degrees, counter-clockwise on screen for a LAF of positive determinant (clockwise for a mirrored one), read by
|
For a circular similarity frame |
scale |
\(\sqrt{|\det A|}\), read by |
|
SIFT descriptor |
kornia’s bin layout |
OpenCV’s bin layout; |
For example, from the pt, size and angle of cv2.SIFT keypoints:
import torch
import kornia.feature as KF
pt = torch.tensor([[70.0, 40.0], [21.5, 13.0]]) # KeyPoint.pt
size = torch.tensor([5.3, 7.1]) # KeyPoint.size
angle = torch.tensor([296.5, 32.2]) # KeyPoint.angle
lafs = KF.laf_from_center_scale_ori(pt[None], 3.0 * size.view(1, -1, 1, 1), -angle.view(1, -1, 1))
assert torch.allclose(-KF.get_laf_orientation(lafs).flatten() % 360.0, angle)
Pretrained models#
A model built with complete pretrained weights comes back in evaluation mode (
model.trainingisFalse). A randomly initialised model stays in PyTorch’s default training mode. So does a model whose weights are only partly pretrained, such as a pretrained backbone with a newly initialised classification head. Call.train()to fine-tune a pretrained model, and.eval()before running inference on a random one.KeyNetDetectorandLAFDescriptorare the exceptions: they put only their default pretrainedKeyNetandHardNetnetworks in evaluation mode and reporttrainingasTruethemselves, so that anori_module,aff_moduleorpatch_descriptor_moduleyou pass keeps its own mode (see Local features).Constructors,
from_config,from_pretrainedand the builders set the mode once, when they build the model.load_checkpointandload_state_dicton an existing module leave its mode as it is: after loading your own weights, call.eval().Task wrappers that take a model (
ObjectDetector,EdgeDetector,SuperResolution,SemanticSegmentation) put that model in evaluation mode: they run inference.
Pitfall checklist#
Quick self-review for generated code, most common first:
(H, W, C)NumPy array passed where a tensor is expected — convert withkornia.image.image_to_tensor(np_img)[None].(w, h)passed to adsize/sizeargument — they are(h, w).(y, x)(row, col) point order — points are(x, y).Assuming uniform
align_cornersdefaults — see the table above.Unbatched
(3, 3)homography — add the batch dim:M[None].Radians passed to the degree APIs (
rotate,get_rotation_matrix2d) or degrees passed to the radian APIs (axis_angle_*).Uint8
[0, 255]values where float[0, 1]is expected.Image and mask augmented through two separate augmentation calls.
homography_warpfed a source→destination pixel homography — it wants destination→source, normalized; usewarp_perspective(or passnormalized_homography=False).Mixing
axis_angle_to_rotation_matrix(math convention; screen- clockwise for +z) withrotate(screen-counter-clockwise) without negating the angle.Treating
infer_bbox_shapeoutput as exclusive width/height — it is inclusive (+ 1).Quaternions constructed in XYZW order — Kornia uses WXYZ.
Expecting hue in
[0, 360]or[0, 1]—rgb_to_hsvreturns radians[0, 2π).Wrong
data_keysbox format —"bbox"means 4-corner(B, N, 4, 2); use"bbox_xyxy"/"bbox_xywh"for coordinate formats.Assuming one rotation direction across the augmentations — a positive
degreesonRandomAffineturns the image clockwise, onRandomRotationcounter-clockwise.Expecting
RandomElasticTransform,RandomThinPlateSplineorRandomFisheyeto move boxes and keypoints with the image — they do not.Feeding mean/std-normalized or otherwise out-of-
[0, 1]tensors through a range-dependent intensity augmentation — input clamping discards out-of-range information and can produce zeros for an all-negative image. Normalize after augmenting instead.
Tip
Machine-readable copies of these conventions live at llms.txt and llms-full.txt at the docs root.